octocode 0.14.1

AI-powered code intelligence with semantic search, knowledge graphs, and built-in MCP server. Transform your codebase into a queryable knowledge graph for AI assistants.
Documentation
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
// Copyright 2026 Muvon Un Limited
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! MCP Server implementation using official rmcp SDK
//!
//! Supports both stdio and Streamable HTTP transports.
//! All core logic from the original server.rs is preserved:
//! - Semantic search, view signatures, GraphRAG tools
//! - LSP tools (goto_definition, hover, find_references, document_symbols, workspace_symbols, completion)
//! - File watcher with debounced background indexing
//! - Structured logging, graceful shutdown

use super::graphrag::GraphRagProvider;
use super::logging::{
	init_mcp_logging, log_critical_anyhow_error, log_indexing_operation, log_watcher_event,
};
use super::semantic_code::SemanticCodeProvider;
use super::watcher::run_watcher;
use crate::config::Config;
use crate::indexer;
use crate::lock::IndexLock;
use crate::state;
use crate::store::Store;
use crate::watcher_config::{DEFAULT_ADDITIONAL_DELAY_MS, MCP_DEFAULT_DEBOUNCE_MS};
use anyhow::Result;
use rmcp::{
	handler::server::{router::tool::ToolRouter, wrapper::Parameters},
	model::{Implementation, ServerCapabilities, ServerInfo},
	schemars, tool, tool_handler, tool_router, ServerHandler, ServiceExt,
};
use serde::{Deserialize, Serialize};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::sync::{mpsc, Mutex};
use tokio::time::{sleep, Duration, Instant};
use tracing::{debug, info, warn};

// Configurable debounce settings
const MCP_DEBOUNCE_MS: u64 = MCP_DEFAULT_DEBOUNCE_MS; // 2000ms = 2 seconds
const MCP_MAX_PENDING_EVENTS: usize = 100;
const MCP_INDEX_TIMEOUT_MS: u64 = 300_000; // 5 minutes

// ---------------------------------------------------------------------------
// Parameter structs for rmcp tool schema generation
// ---------------------------------------------------------------------------

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct SemanticSearchParams {
	/// String or array of strings describing functionality to find. Array preferred for comprehensive results.
	pub query: serde_json::Value,
	/// Max results to return (default: 3)
	#[serde(default, skip_serializing_if = "Option::is_none")]
	#[schemars(range(min = 1, max = 20), extend("default" = 3))]
	pub max_results: Option<usize>,
	/// Result verbosity: 'signatures' (declarations only), 'partial' (truncated, default), 'full' (complete bodies)
	#[serde(default, skip_serializing_if = "Option::is_none")]
	#[schemars(extend("enum" = ["signatures", "partial", "full"]), extend("default" = "partial"))]
	pub detail_level: Option<String>,
	/// Filter code results by language (rust, python, typescript, go, etc.)
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub language: Option<String>,
	/// Content type filter: 'code' (functions/classes), 'text' (plain text), 'docs' (markdown/README), 'commits' (git commit history), 'all' (default, excludes commits)
	#[serde(default, skip_serializing_if = "Option::is_none")]
	#[schemars(extend("enum" = ["code", "text", "docs", "commits", "all"]), extend("default" = "all"))]
	pub mode: Option<String>,
	/// Similarity cutoff 0.0-1.0 (higher = stricter match)
	#[serde(default, skip_serializing_if = "Option::is_none")]
	#[schemars(range(min = 0, max = 1))]
	pub threshold: Option<f32>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct ViewSignaturesParams {
	/// File paths or glob patterns (e.g. 'src/main.rs', '**/*.py', 'src/**/*.ts')
	#[schemars(length(min = 1, max = 100))]
	pub files: Vec<String>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct GraphRagParams {
	/// 'search' (semantic node search), 'get-node' (node details), 'get-relationships' (node connections), 'find-path' (path between two nodes), 'overview' (graph stats)
	#[schemars(extend("enum" = ["search", "get-node", "get-relationships", "find-path", "overview"]))]
	pub operation: String,
	/// Search query for 'search' operation
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub query: Option<String>,
	/// Node ID for 'get-node'/'get-relationships' (format: 'path/to/file' or 'path/to/file/symbol')
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub node_id: Option<String>,
	/// Source node ID for 'find-path'
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub source_id: Option<String>,
	/// Target node ID for 'find-path'
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub target_id: Option<String>,
	/// Max path depth for 'find-path' (default: 3)
	#[serde(default, skip_serializing_if = "Option::is_none")]
	#[schemars(range(min = 1, max = 10), extend("default" = 3))]
	pub max_depth: Option<usize>,
	/// Output format (default: 'text')
	#[serde(default, skip_serializing_if = "Option::is_none")]
	#[schemars(extend("enum" = ["text", "json", "markdown"]), extend("default" = "text"))]
	pub format: Option<String>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct StructuralSearchParams {
	/// AST pattern using ast-grep syntax (e.g. '$FUNC.unwrap()', 'if err != nil { $$$ }')
	pub pattern: String,
	/// Language to search (required: rust, javascript, typescript, python, go, java, cpp, php, ruby, lua, bash, css, json)
	pub language: String,
	/// File paths or glob patterns to search (default: current directory)
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub paths: Option<Vec<String>>,
	/// Number of context lines around matches
	#[serde(default, skip_serializing_if = "Option::is_none")]
	#[schemars(range(min = 0, max = 10))]
	pub context: Option<usize>,
	/// Max results to return (default: 50)
	#[serde(default, skip_serializing_if = "Option::is_none")]
	#[schemars(range(min = 1, max = 200), extend("default" = 50))]
	pub max_results: Option<usize>,
	/// Rewrite template with metavariable substitution (e.g. '$VAR.expect("reason")'). When provided, matched code is rewritten.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub rewrite: Option<String>,
	/// Apply rewrites to files in-place. When false or absent, returns a diff preview. Requires rewrite parameter.
	#[serde(default, skip_serializing_if = "Option::is_none")]
	pub update_all: Option<bool>,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct LspPositionParams {
	/// Relative file path
	pub file_path: String,
	/// 1-indexed line number
	pub line: u32,
	/// Symbol name on that line
	pub symbol: String,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct LspFindReferencesParams {
	/// Relative file path
	pub file_path: String,
	/// 1-indexed line number
	pub line: u32,
	/// Symbol name on that line
	pub symbol: String,
	/// Include the declaration site in results
	#[serde(default = "default_true")]
	pub include_declaration: bool,
}

fn default_true() -> bool {
	true
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct LspDocumentSymbolsParams {
	/// Relative file path
	pub file_path: String,
}

#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
pub struct LspWorkspaceSymbolsParams {
	/// Symbol name or prefix to search
	pub query: String,
}

// ---------------------------------------------------------------------------
// Background services: watcher + indexing (preserves all original logic)
// ---------------------------------------------------------------------------

/// Manages background tasks (file watcher, debouncer, indexing).
/// Abort-on-drop ensures clean shutdown.
pub struct BackgroundServices {
	watcher_handle: Option<tokio::task::JoinHandle<()>>,
	index_handle: Option<tokio::task::JoinHandle<()>>,
	indexing_handle: Option<tokio::task::JoinHandle<()>>,
}

impl Drop for BackgroundServices {
	fn drop(&mut self) {
		if let Some(h) = self.watcher_handle.take() {
			h.abort();
		}
		if let Some(h) = self.index_handle.take() {
			h.abort();
		}
		if let Some(h) = self.indexing_handle.take() {
			h.abort();
		}
	}
}

// ---------------------------------------------------------------------------
// McpServer
// ---------------------------------------------------------------------------

/// MCP Server implementation using rmcp SDK.
#[derive(Clone)]
pub struct McpServer {
	semantic_code: SemanticCodeProvider,
	graphrag: Option<GraphRagProvider>,
	lsp: Option<Arc<Mutex<crate::mcp::lsp::LspProvider>>>,
	indexer_enabled: bool,
	tool_router: ToolRouter<Self>,
}

/// Tool execution error -> CallToolResult with is_error=true (MCP spec).
#[tool_router]
impl McpServer {
	#[tool(
		description = "Search codebase by meaning. Finds code by what it does, not exact symbol names. Prefer an array of related terms over a single query for broader coverage."
	)]
	async fn semantic_search(
		&self,
		Parameters(params): Parameters<SemanticSearchParams>,
	) -> Result<String, String> {
		debug!("Executing semantic_search with query: {:?}", params.query);

		let mut arguments = match serde_json::to_value(&params) {
			Ok(v) => v,
			Err(e) => return Err(format!("Failed to serialize params: {}", e)),
		};

		// Apply default for max_results if not provided
		if params.max_results.is_none() {
			arguments["max_results"] = serde_json::json!(3);
		}

		match self.semantic_code.execute_search(&arguments).await {
			Ok(result) => Ok(result),
			Err(e) => Err(e.to_string()),
		}
	}

	#[tool(
		description = "Extract function signatures, class definitions, and declarations from files without implementation bodies. Supports Rust, JS/TS, Python, Go, C++, PHP, Ruby, Bash, JSON, CSS, Svelte, Markdown."
	)]
	async fn view_signatures(
		&self,
		Parameters(params): Parameters<ViewSignaturesParams>,
	) -> Result<String, String> {
		debug!("Executing view_signatures for {} files", params.files.len());

		let arguments = match serde_json::to_value(&params) {
			Ok(v) => v,
			Err(e) => return Err(format!("Failed to serialize params: {}", e)),
		};

		match self.semantic_code.execute_view_signatures(&arguments).await {
			Ok(result) => Ok(result),
			Err(e) => Err(e.to_string()),
		}
	}

	#[tool(
		description = "Knowledge graph operations over the indexed codebase. Use for architectural queries: component relationships, dependency chains, data flows. For simple code lookup use semantic_search instead."
	)]
	async fn graphrag(
		&self,
		Parameters(params): Parameters<GraphRagParams>,
	) -> Result<String, String> {
		debug!("Executing graphrag with operation: {}", params.operation);

		match &self.graphrag {
			Some(provider) => {
				let arguments = match serde_json::to_value(&params) {
					Ok(v) => v,
					Err(e) => return Err(format!("Failed to serialize params: {}", e)),
				};

				match provider.execute(&arguments).await {
					Ok(result) => Ok(result),
					Err(e) => Err(e.to_string()),
				}
			}
			None => Err(
				"GraphRAG is not enabled in the current configuration. Please enable GraphRAG in octocode.toml to use relationship-aware search.".to_string(),
			),
		}
	}

	// --- LSP tools ---

	#[tool(description = "Jump to the definition of a symbol via LSP.")]
	async fn lsp_goto_definition(
		&self,
		Parameters(params): Parameters<LspPositionParams>,
	) -> Result<String, String> {
		let Some(ref provider) = self.lsp else {
			return Err("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.".to_string());
		};
		let args = serde_json::to_value(&params).unwrap_or_default();
		provider
			.lock()
			.await
			.execute_goto_definition(&args)
			.await
			.map_err(|e| e.to_string())
	}

	#[tool(description = "Get type info and documentation for a symbol via LSP.")]
	async fn lsp_hover(
		&self,
		Parameters(params): Parameters<LspPositionParams>,
	) -> Result<String, String> {
		let Some(ref provider) = self.lsp else {
			return Err("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.".to_string());
		};
		let args = serde_json::to_value(&params).unwrap_or_default();
		provider
			.lock()
			.await
			.execute_hover(&args)
			.await
			.map_err(|e| e.to_string())
	}

	#[tool(description = "Find all usages of a symbol across the workspace via LSP.")]
	async fn lsp_find_references(
		&self,
		Parameters(params): Parameters<LspFindReferencesParams>,
	) -> Result<String, String> {
		let Some(ref provider) = self.lsp else {
			return Err("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.".to_string());
		};
		let args = serde_json::to_value(&params).unwrap_or_default();
		provider
			.lock()
			.await
			.execute_find_references(&args)
			.await
			.map_err(|e| e.to_string())
	}

	#[tool(
		description = "List all symbols (functions, types, variables) defined in a file via LSP."
	)]
	async fn lsp_document_symbols(
		&self,
		Parameters(params): Parameters<LspDocumentSymbolsParams>,
	) -> Result<String, String> {
		let Some(ref provider) = self.lsp else {
			return Err("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.".to_string());
		};
		let args = serde_json::to_value(&params).unwrap_or_default();
		provider
			.lock()
			.await
			.execute_document_symbols(&args)
			.await
			.map_err(|e| e.to_string())
	}

	#[tool(description = "Search for symbols by name across the entire workspace via LSP.")]
	async fn lsp_workspace_symbols(
		&self,
		Parameters(params): Parameters<LspWorkspaceSymbolsParams>,
	) -> Result<String, String> {
		let Some(ref provider) = self.lsp else {
			return Err("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.".to_string());
		};
		let args = serde_json::to_value(&params).unwrap_or_default();
		provider
			.lock()
			.await
			.execute_workspace_symbols(&args)
			.await
			.map_err(|e| e.to_string())
	}

	#[tool(description = "Get code completion suggestions at a symbol position via LSP.")]
	async fn lsp_completion(
		&self,
		Parameters(params): Parameters<LspPositionParams>,
	) -> Result<String, String> {
		let Some(ref provider) = self.lsp else {
			return Err("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.".to_string());
		};
		let args = serde_json::to_value(&params).unwrap_or_default();
		provider
			.lock()
			.await
			.execute_completion(&args)
			.await
			.map_err(|e| e.to_string())
	}

	// --- Structural search tool ---

	#[tool(
		description = "Search or rewrite code by AST structure using ast-grep pattern syntax. Finds code matching structural patterns like '$FUNC.unwrap()', 'if let Some($X) = $Y { $$$ }'. Optionally rewrite matches using a template with metavariable substitution. Complements semantic_search: use this for structural/syntactic patterns, semantic_search for meaning-based queries."
	)]
	async fn structural_search(
		&self,
		Parameters(params): Parameters<StructuralSearchParams>,
	) -> Result<String, String> {
		debug!(
			"Executing structural_search with pattern: {} lang: {}",
			params.pattern, params.language
		);

		let current_dir = std::env::current_dir().map_err(|e| e.to_string())?;
		let max_results = params.max_results.unwrap_or(50);
		let context = params.context.unwrap_or(0);

		// Collect matching files
		let walker = ignore::WalkBuilder::new(&current_dir)
			.git_ignore(true)
			.git_global(true)
			.git_exclude(true)
			.hidden(true)
			.build();

		let mut files = Vec::new();
		for entry in walker.flatten() {
			if !entry.file_type().is_some_and(|ft| ft.is_file()) {
				continue;
			}
			let path = entry.path();
			if crate::grep::language_from_extension(path) != Some(params.language.as_str()) {
				continue;
			}
			if let Some(ref filter_paths) = params.paths {
				let rel = path
					.strip_prefix(&current_dir)
					.unwrap_or(path)
					.to_string_lossy();
				if !filter_paths.iter().any(|p| rel.contains(p)) {
					continue;
				}
			}
			files.push(path.to_path_buf());
		}

		// Branch: rewrite mode vs search mode
		if let Some(ref rewrite_template) = params.rewrite {
			return self.structural_rewrite(
				&files,
				&current_dir,
				&params.pattern,
				rewrite_template,
				&params.language,
				params.update_all.unwrap_or(false),
			);
		}

		let mut all_matches = Vec::new();
		let mut source_map = std::collections::HashMap::new();

		for path in &files {
			if all_matches.len() >= max_results {
				break;
			}
			let source = match std::fs::read_to_string(path) {
				Ok(s) => s,
				Err(_) => continue,
			};
			let display_path = path
				.strip_prefix(&current_dir)
				.unwrap_or(path)
				.to_string_lossy()
				.to_string();
			match crate::grep::search_file(
				&display_path,
				&source,
				&params.pattern,
				&params.language,
			) {
				Ok(matches) => {
					if context > 0 && !matches.is_empty() {
						source_map.insert(display_path.clone(), source);
					}
					all_matches.extend(matches);
				}
				Err(_) => continue,
			}
		}

		if all_matches.is_empty() {
			return Ok("No matches found.".to_string());
		}

		all_matches.truncate(max_results);

		let output = if context > 0 {
			crate::grep::format_matches_with_context(&all_matches, &source_map, context)
		} else {
			crate::grep::format_matches_grouped(&all_matches)
		};

		Ok(format!(
			"{}\n\n{} matches found.",
			output,
			all_matches.len()
		))
	}
}

#[tool_handler(router = self.tool_router)]
impl ServerHandler for McpServer {
	fn get_info(&self) -> ServerInfo {
		let capabilities = ServerCapabilities::builder().enable_tools().build();

		let instructions = if self.indexer_enabled {
			"This server provides modular AI tools: semantic code search, view signatures, and GraphRAG (if available). Use 'semantic_search' for code/documentation searches and 'graphrag' (if enabled) for relationship queries."
		} else {
			"WARNING: Octocode indexer is disabled: not in a git repository root. Run with --no-git to enable indexing outside git repos. Tools available: semantic_search, view_signatures, graphrag (if enabled)."
		};

		ServerInfo::new(capabilities)
			.with_server_info(
				Implementation::new("octocode-mcp", env!("CARGO_PKG_VERSION"))
					.with_description("Semantic code search server with vector embeddings and optional GraphRAG support"),
			)
			.with_instructions(instructions)
	}
}

impl McpServer {
	fn structural_rewrite(
		&self,
		files: &[std::path::PathBuf],
		current_dir: &std::path::Path,
		pattern: &str,
		rewrite_template: &str,
		language: &str,
		update_all: bool,
	) -> Result<String, String> {
		let mut results = Vec::new();
		let mut total_replacements = 0;

		for path in files {
			let source = match std::fs::read_to_string(path) {
				Ok(s) => s,
				Err(_) => continue,
			};
			let display_path = path
				.strip_prefix(current_dir)
				.unwrap_or(path)
				.to_string_lossy()
				.to_string();

			match crate::grep::rewrite_file(
				&display_path,
				&source,
				pattern,
				rewrite_template,
				language,
			) {
				Ok(Some(result)) => {
					total_replacements += result.replacements;
					results.push((path.clone(), result));
				}
				Ok(None) => {}
				Err(e) => {
					debug!("Error rewriting {}: {}", display_path, e);
				}
			}
		}

		if results.is_empty() {
			return Ok("No matches found.".to_string());
		}

		if update_all {
			for (path, result) in &results {
				if let Err(e) = std::fs::write(path, &result.rewritten_source) {
					return Err(format!("Failed to write {}: {}", result.file, e));
				}
			}
			Ok(format!(
				"Applied {} replacements across {} files.",
				total_replacements,
				results.len()
			))
		} else {
			let mut output = String::new();
			for (_, result) in &results {
				output.push_str(&crate::grep::format_rewrite_diff(result));
				output.push_str("\n\n");
			}
			output.push_str(&format!(
				"{} replacements across {} files (preview, set update_all=true to apply).",
				total_replacements,
				results.len()
			));
			Ok(output)
		}
	}

	/// Lightweight constructor for proxy mode.
	///
	/// Creates only the providers and tool router — no store, no LSP, no
	/// background services, no `set_current_dir`.  The proxy manages its own
	/// lifecycle (indexing, cleanup, logging).
	pub fn new_for_proxy(config: Config, working_directory: std::path::PathBuf) -> Result<Self> {
		let semantic_code = SemanticCodeProvider::new(config.clone(), working_directory.clone());
		let graphrag = GraphRagProvider::new(config, working_directory);

		let mut tool_router = Self::tool_router();

		// Proxy never has LSP — remove LSP tools
		for name in [
			"lsp_goto_definition",
			"lsp_hover",
			"lsp_find_references",
			"lsp_document_symbols",
			"lsp_workspace_symbols",
			"lsp_completion",
		] {
			tool_router.remove_route(name);
		}

		if graphrag.is_none() {
			tool_router.remove_route("graphrag");
		}

		Ok(Self {
			semantic_code,
			graphrag,
			lsp: None,
			indexer_enabled: false,
			tool_router,
		})
	}

	/// Create a new MCP server instance.
	///
	/// Initialises the store, logging, providers, and optionally spawns LSP background init.
	pub async fn new(
		config: Config,
		debug_mode: bool,
		working_directory: std::path::PathBuf,
		no_git: bool,
		lsp_command: Option<String>,
	) -> Result<(Self, BackgroundServices)> {
		// Change to the working directory at server startup
		std::env::set_current_dir(&working_directory).map_err(|e| {
			anyhow::anyhow!(
				"Failed to change to working directory '{}': {}",
				working_directory.display(),
				e
			)
		})?;

		// Initialize the store
		let store = Store::new().await?;
		store.initialize_collections().await?;
		let store = Arc::new(store);

		// Initialize logging
		init_mcp_logging(working_directory.clone(), debug_mode)?;

		let semantic_code = SemanticCodeProvider::new(config.clone(), working_directory.clone());
		let graphrag = GraphRagProvider::new(config.clone(), working_directory.clone());

		// Initialize LSP provider if command is provided (lazy initialization)
		let lsp = if let Some(command) = lsp_command {
			info!(
				"LSP provider will be initialized lazily with command: {}",
				command
			);
			let provider = Arc::new(Mutex::new(crate::mcp::lsp::LspProvider::new(
				working_directory.clone(),
				command,
			)));

			// Start LSP initialization in background (non-blocking)
			let provider_clone = provider.clone();
			tokio::spawn(async move {
				let mut provider_guard = provider_clone.lock().await;
				if let Err(e) = provider_guard.start_initialization().await {
					warn!("LSP initialization failed: {}", e);
				}
			});

			Some(provider)
		} else {
			None
		};

		// Determine if indexer should start
		let should_start_indexer = if !no_git && config.index.require_git {
			indexer::git::is_git_repo_root(&working_directory)
		} else {
			true
		};

		if !should_start_indexer {
			warn!(
				"Indexer not started: Not in a git repository and --no-git flag not set. \
				 Use --no-git to enable indexing outside git repos."
			);
		}

		// Build tool router — LSP tools return helpful errors when LSP is not configured
		let mut tool_router = Self::tool_router();

		// Remove LSP tools from router if LSP is not configured (matching old server behaviour)
		if lsp.is_none() {
			for name in [
				"lsp_goto_definition",
				"lsp_hover",
				"lsp_find_references",
				"lsp_document_symbols",
				"lsp_workspace_symbols",
				"lsp_completion",
			] {
				tool_router.remove_route(name);
			}
		}

		// Remove GraphRAG tool if not configured
		if graphrag.is_none() {
			tool_router.remove_route("graphrag");
		}

		let server = Self {
			semantic_code,
			graphrag,
			lsp,
			indexer_enabled: should_start_indexer,
			tool_router,
		};

		// Start background services (watcher + indexing)
		let bg = if should_start_indexer {
			start_background_services(
				config,
				store,
				working_directory,
				no_git,
				debug_mode,
				server.lsp.clone(),
			)
			.await?
		} else {
			BackgroundServices {
				watcher_handle: None,
				index_handle: None,
				indexing_handle: None,
			}
		};

		info!(
			"MCP Server initialized (debug_mode={}, indexer={}, debounce={}ms, timeout={}ms, max_events={})",
			debug_mode, should_start_indexer, MCP_DEBOUNCE_MS, MCP_INDEX_TIMEOUT_MS, MCP_MAX_PENDING_EVENTS
		);

		Ok((server, bg))
	}

	/// Run the server using stdio transport (default MCP mode)
	pub async fn run_stdio(self, _bg: BackgroundServices) -> Result<()> {
		// Guard against panics in tool handlers crashing the whole server
		let original_hook = std::panic::take_hook();
		std::panic::set_hook(Box::new(move |info| {
			super::logging::log_critical_anyhow_error(
				"Panic in MCP server",
				&anyhow::anyhow!("{}", info),
			);
			original_hook(info);
		}));

		info!("Starting MCP server in stdio mode");

		let transport = rmcp::transport::io::stdio();
		let service = self.serve(transport).await?;

		// Wait for the service to complete (EOF / client disconnect)
		service.waiting().await?;

		// _bg is dropped here -> background tasks aborted
		Ok(())
	}

	/// Run the server using Streamable HTTP transport (MCP 2025-03-26 spec).
	///
	/// Uses rmcp's `StreamableHttpService` with `LocalSessionManager` for
	/// proper session management. Supports both SSE and plain JSON responses
	/// as required by the spec.
	pub async fn run_http(self, bind_addr: &str, _bg: BackgroundServices) -> Result<()> {
		use hyper_util::rt::TokioIo;
		use hyper_util::service::TowerToHyperService;
		use rmcp::transport::streamable_http_server::{
			session::local::LocalSessionManager, StreamableHttpService,
		};

		info!("Starting MCP server in HTTP mode on {}", bind_addr);

		let server = self.clone();

		// StreamableHttpService handles session lifecycle, SSE vs JSON content
		// negotiation, and MCP protocol compliance automatically.
		let service = StreamableHttpService::new(
			move || Ok(server.clone()),
			Arc::new(LocalSessionManager::default()),
			Default::default(),
		);

		let addr: std::net::SocketAddr = bind_addr
			.parse()
			.map_err(|e| anyhow::anyhow!("Invalid bind address '{}': {}", bind_addr, e))?;

		let listener = tokio::net::TcpListener::bind(addr).await?;
		info!("MCP HTTP server listening on {}", addr);

		loop {
			let (stream, remote_addr) = listener.accept().await?;
			debug!("Accepted connection from {}", remote_addr);

			let service = service.clone();
			tokio::spawn(async move {
				let io = TokioIo::new(stream);
				let hyper_service = TowerToHyperService::new(service);

				if let Err(e) = hyper::server::conn::http1::Builder::new()
					.serve_connection(io, hyper_service)
					.await
				{
					debug!("Connection error from {}: {}", remote_addr, e);
				}
			});
		}
	}
}

// ---------------------------------------------------------------------------
// Background services setup (preserves all watcher + indexing logic)
// ---------------------------------------------------------------------------

async fn start_background_services(
	config: Config,
	store: Arc<Store>,
	working_directory: std::path::PathBuf,
	no_git: bool,
	debug: bool,
	lsp: Option<Arc<Mutex<crate::mcp::lsp::LspProvider>>>,
) -> Result<BackgroundServices> {
	let (file_tx, file_rx) = mpsc::channel(MCP_MAX_PENDING_EVENTS);
	let (index_tx, index_rx) = mpsc::channel(10);

	// 1. File watcher
	let working_dir = working_directory.clone();
	let watcher_handle = tokio::spawn(async move {
		if let Err(e) = run_watcher(file_tx, working_dir, debug, MCP_MAX_PENDING_EVENTS).await {
			log_critical_anyhow_error("Watcher error", &e);
		}
	});

	// 2. Debouncer: accumulates file events, triggers indexing after quiet period
	let indexing_in_progress = Arc::new(AtomicBool::new(false));
	let indexing_flag = indexing_in_progress.clone();
	let debug_mode = debug;
	let index_handle = tokio::spawn(async move {
		let mut file_rx = file_rx;
		let mut last_event_time = None::<Instant>;
		let mut pending_events = 0u32;

		loop {
			let timeout_duration = Duration::from_millis(MCP_DEBOUNCE_MS);

			tokio::select! {
				event_result = file_rx.recv() => {
					match event_result {
						Some(_) => {
							pending_events += 1;
							last_event_time = Some(Instant::now());
							log_watcher_event("file_change", None, pending_events as usize);
						}
						None => {
							debug!("File watcher channel closed, stopping debouncer");
							break;
						}
					}
				}

				_ = sleep(timeout_duration), if last_event_time.is_some() => {
					if let Some(last_time) = last_event_time {
						if last_time.elapsed() >= timeout_duration && pending_events > 0 {
							if indexing_flag
								.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
								.is_ok()
							{
								if debug_mode {
									debug!(
										"Debounce period completed ({} pending events), requesting reindex",
										pending_events
									);
								}
								log_watcher_event("debounce_trigger", None, pending_events as usize);

								if (index_tx.send(()).await).is_err() {
									if debug_mode {
										debug!("Failed to send index request - server may be shutting down");
									}
									indexing_flag.store(false, Ordering::SeqCst);
									break;
								}

								pending_events = 0;
								last_event_time = None;
							} else if debug_mode {
								debug!("Indexing already in progress, will retry after current indexing completes");
							}
						}
					}
				}
			}
		}
	});

	// 3. Background indexing task
	let indexing_flag2 = indexing_in_progress;
	let indexing_handle = tokio::spawn(async move {
		let mut index_rx = index_rx;
		loop {
			match index_rx.recv().await {
				Some(_) => {
					debug!("Processing index request in background");

					// Additional delay to ensure all file operations are complete
					sleep(Duration::from_millis(DEFAULT_ADDITIONAL_DELAY_MS)).await;

					let indexing_result = tokio::time::timeout(
						Duration::from_millis(MCP_INDEX_TIMEOUT_MS),
						perform_indexing(&store, &config, &working_directory, no_git),
					)
					.await;

					match indexing_result {
						Ok(Ok(())) => {
							info!("Background reindex completed successfully");

							// Update LSP with changed files if LSP is enabled
							if let Some(ref lsp_provider) = lsp {
								let mut lsp_guard = lsp_provider.lock().await;
								if let Err(e) =
									update_lsp_after_indexing(&mut lsp_guard, &working_directory)
										.await
								{
									debug!("LSP update after indexing failed: {}", e);
								}
							}
						}
						Ok(Err(e)) => {
							log_critical_anyhow_error("Background reindex error", &e);
						}
						Err(_) => {
							log_critical_anyhow_error(
								"Background reindex timeout",
								&anyhow::anyhow!(
									"Background reindex timed out after {}ms",
									MCP_INDEX_TIMEOUT_MS
								),
							);
						}
					}

					// Always reset the indexing flag
					indexing_flag2.store(false, Ordering::SeqCst);
				}
				None => {
					debug!("Background indexing channel closed, stopping indexing task");
					break;
				}
			}
		}
	});

	Ok(BackgroundServices {
		watcher_handle: Some(watcher_handle),
		index_handle: Some(index_handle),
		indexing_handle: Some(indexing_handle),
	})
}

// ---------------------------------------------------------------------------
// Indexing helpers (preserved from original server.rs)
// ---------------------------------------------------------------------------

pub(crate) async fn perform_indexing(
	store: &Store,
	config: &Config,
	working_directory: &std::path::Path,
	no_git: bool,
) -> Result<()> {
	let start_time = std::time::Instant::now();
	log_indexing_operation("direct_reindex_start", None, None, true);

	let mut lock = IndexLock::new(working_directory)?;
	lock.acquire_async()
		.await
		.map_err(|e| anyhow::anyhow!("Failed to acquire index lock: {}", e))?;
	debug!("MCP server: acquired indexing lock");

	let state = state::create_shared_state();
	state.write().current_directory = working_directory.to_path_buf();

	let git_repo_root = if !no_git {
		indexer::git::find_git_root(working_directory)
	} else {
		None
	};

	let indexing_result = indexer::index_files_with_quiet(
		store,
		state.clone(),
		config,
		git_repo_root.as_deref(),
		true,
	)
	.await;

	lock.release()?;
	debug!("MCP server: released indexing lock");

	let duration_ms = start_time.elapsed().as_millis() as u64;

	match indexing_result {
		Ok(()) => {
			log_indexing_operation("direct_reindex_complete", None, Some(duration_ms), true);
			Ok(())
		}
		Err(e) => {
			log_indexing_operation("direct_reindex_complete", None, Some(duration_ms), false);
			log_critical_anyhow_error("Direct indexing", &e);
			Err(e)
		}
	}
}

/// Update LSP server with recently changed files after indexing
async fn update_lsp_after_indexing(
	lsp_provider: &mut crate::mcp::lsp::LspProvider,
	working_directory: &std::path::Path,
) -> Result<()> {
	use crate::indexer::{detect_language, NoindexWalker, PathUtils};

	debug!("Updating LSP server with changed files");

	let walker = NoindexWalker::create_walker(working_directory).build();
	let mut files_updated = 0;

	for result in walker {
		let entry = match result {
			Ok(entry) => entry,
			Err(_) => continue,
		};

		if !entry.file_type().is_some_and(|ft| ft.is_file()) {
			continue;
		}

		if detect_language(entry.path()).is_some() {
			let relative_path = PathUtils::to_relative_string(entry.path(), working_directory);

			if let Err(e) = lsp_provider.update_file(&relative_path).await {
				debug!("Failed to update file {} in LSP: {}", relative_path, e);
			} else {
				files_updated += 1;
			}
		}
	}

	debug!("LSP update completed: {} files updated", files_updated);
	Ok(())
}