octocode 0.12.0

AI-powered code indexer with semantic search, GraphRAG knowledge graphs, and MCP server for multi-language codebases
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
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
1214
1215
1216
1217
1218
// Copyright 2025 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.

use anyhow::Result;
use serde_json::json;
use std::panic;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpListener;
use tokio::sync::mpsc;
use tokio::sync::Mutex;
use tokio::time::{sleep, Duration, Instant};
use tracing::{debug, info, trace, warn};

use crate::config::Config;
use crate::indexer;
use crate::lock::IndexLock;
use crate::mcp::graphrag::GraphRagProvider;
use crate::mcp::http::{handle_http_connection, HttpServerState};
use crate::mcp::logging::{
	init_mcp_logging, log_critical_anyhow_error, log_critical_error, log_indexing_operation,
	log_mcp_request, log_mcp_response, log_watcher_event,
};
use crate::mcp::semantic_code::SemanticCodeProvider;
use crate::mcp::types::{parse_mcp_error, JsonRpcError, JsonRpcRequest, JsonRpcResponse, McpError};
use crate::mcp::watcher::run_watcher;
use crate::state;
use crate::store::Store;
use crate::watcher_config::{DEFAULT_ADDITIONAL_DELAY_MS, MCP_DEFAULT_DEBOUNCE_MS};

// Configurable debounce settings (code-only configuration for now)
//
// You can modify these constants to tune the MCP server behavior:
// - MCP_DEBOUNCE_MS: How long to wait after the last file change before triggering reindex
// - MCP_MAX_PENDING_EVENTS: Maximum number of file events to queue (prevents memory issues)
// - MCP_INDEX_TIMEOUT_MS: Maximum time to wait for indexing to complete before timing out
// - MCP_ENABLE_VERBOSE_EVENTS: Whether to log individual file events (useful for debugging)
// - MCP_MAX_REQUEST_SIZE: Maximum size of incoming JSON-RPC requests (prevents memory exhaustion)
// - MCP_IO_TIMEOUT_MS: Timeout for individual stdin/stdout operations (prevents hanging on broken pipes, NOT for server lifecycle)
//
pub const MCP_DEBOUNCE_MS: u64 = MCP_DEFAULT_DEBOUNCE_MS; // 2000ms = 2 seconds
pub const MCP_MAX_PENDING_EVENTS: usize = 100;
const MCP_INDEX_TIMEOUT_MS: u64 = 300_000; // 5 minutes
pub const MCP_ENABLE_VERBOSE_EVENTS: bool = false; // Set to true for detailed event logging
const MCP_MAX_REQUEST_SIZE: usize = 10_485_760; // 10MB maximum request size
const MCP_IO_TIMEOUT_MS: u64 = 30_000; // 30 seconds for individual I/O operations (NOT for server lifecycle)

/// MCP Server implementation with modular tool providers
pub struct McpServer {
	semantic_code: SemanticCodeProvider,
	graphrag: Option<GraphRagProvider>,
	lsp: Option<Arc<Mutex<crate::mcp::lsp::LspProvider>>>,
	debug: bool,
	working_directory: std::path::PathBuf,
	no_git: bool,
	indexer_enabled: bool,
	watcher_handle: Option<tokio::task::JoinHandle<()>>,
	index_handle: Option<tokio::task::JoinHandle<()>>,
	indexing_handle: Option<tokio::task::JoinHandle<()>>,
	indexing_in_progress: Arc<AtomicBool>,
	store: Arc<Store>,
	config: Config,
	index_rx: Option<mpsc::Receiver<()>>,
}

impl McpServer {
	pub async fn new(
		config: Config,
		debug: bool,
		working_directory: std::path::PathBuf,
		no_git: bool,
		lsp_command: Option<String>,
	) -> Result<Self> {
		// 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 for the MCP server
		let store = Store::new().await?;
		store.initialize_collections().await?;
		let store = Arc::new(store);

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

		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 {
			tracing::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 {
					tracing::warn!("LSP initialization failed: {}", e);
				}
			});

			Some(provider)
		} else {
			None
		};

		Ok(Self {
			semantic_code,
			graphrag,
			lsp,
			debug,
			working_directory,
			no_git,
			indexer_enabled: false,
			watcher_handle: None,
			index_handle: None,
			indexing_handle: None,
			indexing_in_progress: Arc::new(AtomicBool::new(false)),
			store,
			config,
			index_rx: None,
		})
	}

	pub async fn run(&mut self) -> Result<()> {
		// Set up panic handler to prevent server crashes from tool execution
		let original_hook = panic::take_hook();
		panic::set_hook(Box::new(move |panic_info| {
			log_critical_anyhow_error("Panic in MCP server", &anyhow::anyhow!("{}", panic_info));
			// Call original hook for debugging
			original_hook(panic_info);
		}));

		// Check if we should start the indexer (only if in git repo or --no-git is set)
		let should_start_indexer = if !self.no_git && self.config.index.require_git {
			indexer::git::is_git_repo_root(&self.working_directory)
		} else {
			true
		};

		if should_start_indexer {
			// Start the file watcher as a completely independent background task
			self.start_watcher().await?;

			// Start background indexing task - separate from MCP request handling
			self.start_background_indexing().await?;
		} else {
			// Log warning about indexer not starting
			warn!(
				"Indexer not started: Not in a git repository and --no-git flag not set. Use --no-git to enable indexing outside git repos."
			);
		}

		// Store indexer enabled state for use in initialize response
		self.indexer_enabled = should_start_indexer;

		// Log server startup details using structured logging (no console output for MCP protocol compliance)
		info!(
			debug_mode = self.debug,
			indexer_enabled = should_start_indexer,
			debounce_ms = MCP_DEBOUNCE_MS,
			timeout_ms = MCP_INDEX_TIMEOUT_MS,
			max_events = MCP_MAX_PENDING_EVENTS,
			max_request_size_mb = MCP_MAX_REQUEST_SIZE / 1_048_576,
			io_timeout_ms = MCP_IO_TIMEOUT_MS,
			"MCP Server started"
		);

		// Handle MCP protocol communication (stdin/stdout) with error resilience
		// This runs independently of file watching and indexing
		let stdin = tokio::io::stdin();
		let stdout = tokio::io::stdout();
		let mut reader = BufReader::new(stdin);
		let mut writer = stdout;

		let mut line = String::with_capacity(1024); // Pre-allocate reasonable buffer
		let mut consecutive_errors = 0u32;
		const MAX_CONSECUTIVE_ERRORS: u32 = 10;

		loop {
			line.clear();

			tokio::select! {
				// Handle MCP protocol messages from stdin with timeout and error recovery
				result = tokio::time::timeout(
					Duration::from_millis(MCP_IO_TIMEOUT_MS),
					reader.read_line(&mut line)
				) => {
					match result {
						Ok(Ok(0)) => {
							// EOF reached - normal shutdown
							debug!("MCP Server: EOF received, shutting down gracefully");
							break;
						}
						Ok(Ok(bytes_read)) => {
							// Check for oversized requests to prevent memory exhaustion
							if bytes_read > MCP_MAX_REQUEST_SIZE {
								log_critical_anyhow_error(
									"Request size limit exceeded",
									&anyhow::anyhow!("Request size {} exceeds limit {}", bytes_read, MCP_MAX_REQUEST_SIZE)
								);

								// Send error response for oversized request
								if let Err(e) = self.send_error_response(
									&mut writer,
									None,
									-32700,
									"Request too large",
									Some(json!({"max_size": MCP_MAX_REQUEST_SIZE}))
								).await {
									log_critical_anyhow_error("Failed to send error response", &e);
								}
								continue;
							}

							// Process the request with panic recovery
							// Capture method before moving line into handler
							let request_method_for_notif = {
								serde_json::from_str::<serde_json::Value>(line.trim())
									.ok()
									.and_then(|v| v.get("method").and_then(|m| m.as_str()).map(|s| s.to_string()))
							};
							match self.handle_request_safe(&line).await {
								Ok(Some(response)) => {
									// For initialize: send warning notification BEFORE the response so
									// the client reads it while still in the initialize read loop
									// (which correctly skips notifications). Sending after would cause
									// it to be consumed by the notifications/initialized handshake read.
									if request_method_for_notif.as_deref() == Some("initialize") && !self.indexer_enabled {
										let notif_params = json!({
											"level": "warning",
											"message": "Octocode indexer is disabled: not in a git repository root. Run with --no-git to enable indexing outside git repos."
										});
										if let Err(e) = self.send_notification(&mut writer, "notifications/message", notif_params).await {
											log_critical_anyhow_error("Failed to send indexer-disabled notification", &e);
										}
									}

									// Send response with error handling
									if let Err(e) = self.send_response(&mut writer, &response).await {
										log_critical_anyhow_error("Failed to send response", &e);
										consecutive_errors += 1;
										if consecutive_errors >= MAX_CONSECUTIVE_ERRORS {
											log_critical_anyhow_error(
												"Too many consecutive errors",
												&anyhow::anyhow!("Shutting down after {} consecutive errors", consecutive_errors)
											);
											break;
										}
									} else {
										consecutive_errors = 0; // Reset on successful send
									}
								}
								Ok(None) => {
									// No response needed (e.g., empty request)
									consecutive_errors = 0;
								}
								Err(e) => {
									log_critical_anyhow_error("Request handling failed", &e);
									consecutive_errors += 1;

									// Try to send error response
									if let Err(send_err) = self.send_error_response(
										&mut writer,
										None,
										-32603,
										"Internal server error",
										Some(json!({"error": e.to_string()}))
									).await {
										log_critical_anyhow_error("Failed to send error response", &send_err);
									}

									if consecutive_errors >= MAX_CONSECUTIVE_ERRORS {
										log_critical_anyhow_error(
											"Too many consecutive errors",
											&anyhow::anyhow!("Shutting down after {} consecutive errors", consecutive_errors)
										);
										break;
									}
								}
							}
						}
						Ok(Err(e)) => {
							// I/O error reading from stdin
							if self.is_broken_pipe_error(&e) {
								debug!("MCP Server: Broken pipe detected, shutting down gracefully");
								break;
							} else {
								log_critical_error("Error reading from stdin", &e);
								consecutive_errors += 1;
								if consecutive_errors >= MAX_CONSECUTIVE_ERRORS {
									break;
								}
								// Brief delay before retrying
								tokio::time::sleep(Duration::from_millis(100)).await;
							}
						}
				Err(_) => {
					// Timeout on stdin read - this is normal when no client requests are pending
					// MCP servers should wait indefinitely for client requests, not terminate on timeouts
					trace!("MCP Server: Timeout reading from stdin (normal - waiting for client requests)");
					// Do NOT increment consecutive_errors for timeouts - this is expected behavior
					// Reset consecutive_errors since timeout is not an actual error
					consecutive_errors = 0;
				}
					}
				}

				// MCP request handling only - indexing moved to background task
			}
		}

		// Cleanup: abort background tasks
		if let Some(handle) = self.watcher_handle.take() {
			handle.abort();
		}
		if let Some(handle) = self.index_handle.take() {
			handle.abort();
		}
		if let Some(handle) = self.indexing_handle.take() {
			handle.abort();
		}

		debug!("MCP Server stopped");

		Ok(())
	}

	/// Run MCP server over HTTP instead of stdin/stdout
	pub async fn run_http(&mut self, bind_addr: &str) -> Result<()> {
		// Set up panic handler to prevent server crashes from tool execution
		let original_hook = panic::take_hook();
		panic::set_hook(Box::new(move |panic_info| {
			log_critical_anyhow_error("Panic in MCP server", &anyhow::anyhow!("{}", panic_info));
			// Call original hook for debugging
			original_hook(panic_info);
		}));

		// Check if we should start the indexer (only if in git repo or --no-git is set)
		let should_start_indexer = if !self.no_git && self.config.index.require_git {
			indexer::git::is_git_repo_root(&self.working_directory)
		} else {
			true
		};

		if should_start_indexer {
			// Start the file watcher as a completely independent background task
			self.start_watcher().await?;
		} else {
			// Log warning about indexer not starting
			warn!(
				"Indexer not started: Not in a git repository and --no-git flag not set. Use --no-git to enable indexing outside git repos."
			);
		}

		// Store indexer enabled state for use in initialize response
		self.indexer_enabled = should_start_indexer;

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

		// Log server startup details
		info!(
			debug_mode = self.debug,
			bind_address = %addr,
			indexer_enabled = should_start_indexer,
			debounce_ms = MCP_DEBOUNCE_MS,
			timeout_ms = MCP_INDEX_TIMEOUT_MS,
			max_events = MCP_MAX_PENDING_EVENTS,
			max_request_size_mb = MCP_MAX_REQUEST_SIZE / 1_048_576,
			io_timeout_ms = MCP_IO_TIMEOUT_MS,
			"MCP Server started in HTTP mode"
		);

		// Get the index receiver for handling indexing requests (only if indexer is enabled)
		let mut index_rx = if should_start_indexer {
			self.index_rx.take().unwrap()
		} else {
			// Create a dummy channel that will never receive messages
			let (_, rx) = mpsc::channel(1);
			rx
		};

		// Create shared server state for HTTP handlers
		let server_state = Arc::new(Mutex::new(HttpServerState {
			semantic_code: self.semantic_code.clone(),
			graphrag: self.graphrag.clone(),
			lsp: self.lsp.clone(),
		}));

		// Start HTTP server
		let listener = TcpListener::bind(&addr)
			.await
			.map_err(|e| anyhow::anyhow!("Failed to bind to {}: {}", addr, e))?;

		info!("MCP HTTP server listening on {}", addr);

		// Clone state for the server task
		let state_for_server = server_state.clone();
		let mut server_handle = tokio::spawn(async move {
			loop {
				match listener.accept().await {
					Ok((stream, addr)) => {
						let state = state_for_server.clone();
						tokio::spawn(async move {
							if let Err(e) = handle_http_connection(stream, state).await {
								debug!("HTTP connection error from {}: {}", addr, e);
							}
						});
					}
					Err(e) => {
						log_critical_anyhow_error(
							"HTTP server accept error",
							&anyhow::anyhow!("{}", e),
						);
						break;
					}
				}
			}
		});

		// Handle indexing requests from file watcher (runs independently)
		loop {
			tokio::select! {
				Some(_) = index_rx.recv() => {
					debug!("Processing index request");

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

					// Perform direct indexing with timeout protection
					let indexing_result = tokio::time::timeout(
						Duration::from_millis(MCP_INDEX_TIMEOUT_MS),
						perform_indexing(&self.store, &self.config, &self.working_directory, self.no_git)
					).await;

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

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

					// Always reset the indexing flag, even on error/timeout
					self.indexing_in_progress.store(false, Ordering::SeqCst);
				}

				// Check if HTTP server is still running
				_ = &mut server_handle => {
					warn!("HTTP server task completed unexpectedly");
					break;
				}
			}
		}

		// Cleanup: abort background tasks
		if let Some(handle) = self.watcher_handle.take() {
			handle.abort();
		}
		if let Some(handle) = self.index_handle.take() {
			handle.abort();
		}
		server_handle.abort();

		debug!("MCP HTTP Server stopped");

		Ok(())
	}

	async fn start_watcher(&mut self) -> Result<()> {
		let (file_tx, file_rx) = mpsc::channel(MCP_MAX_PENDING_EVENTS);
		let (index_tx, index_rx) = mpsc::channel(10);
		let working_dir = self.working_directory.clone();
		let debug = self.debug;

		// Start file watcher in background
		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);
			}
		});

		// Start improved debouncing handler that properly accumulates events
		let indexing_in_progress = self.indexing_in_progress.clone();
		let debug_mode = self.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 {
				// Wait for either a file event or timeout
				let timeout_duration = Duration::from_millis(MCP_DEBOUNCE_MS);

				tokio::select! {
					// New file event received
					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;
							}
						}
					}

					// Debounce timeout - check if we should trigger indexing
					_ = sleep(timeout_duration), if last_event_time.is_some() => {
						if let Some(last_time) = last_event_time {
							// Check if enough time has passed since the last event
							if last_time.elapsed() >= timeout_duration && pending_events > 0 {
								// Try to acquire indexing lock
								if indexing_in_progress
									.compare_exchange(false, true, Ordering::SeqCst, Ordering::SeqCst)
									.is_ok()
								{
									if debug_mode {
										debug!(
							pending_events = pending_events,
							"Debounce period completed, requesting reindex"
						);
									}

									// Log the debounce trigger
								log_watcher_event("debounce_trigger", None, pending_events as usize);

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

									// Reset counters
									pending_events = 0;
									last_event_time = None;
								} else if debug_mode {
									debug!("Indexing already in progress, will retry after current indexing completes");
									// Don't reset counters, will retry later
								}
							}
						}
					}
				}
			}
		});

		// Store the index receiver for handling in the main loop
		self.index_rx = Some(index_rx);
		self.watcher_handle = Some(watcher_handle);
		self.index_handle = Some(index_handle);
		Ok(())
	}

	/// Start background indexing task - separate from MCP request handling
	async fn start_background_indexing(&mut self) -> Result<()> {
		// Get the index receiver for handling indexing requests
		let mut index_rx = self.index_rx.take().unwrap();
		let store = self.store.clone();
		let config = self.config.clone();
		let working_directory = self.working_directory.clone();
		let no_git = self.no_git;
		let indexing_in_progress = self.indexing_in_progress.clone();

		// Start background indexing task
		let indexing_handle = tokio::spawn(async move {
			loop {
				// Wait for indexing requests from file watcher
				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;

						// Perform direct indexing with timeout protection
						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");
								// LSP update removed from background task to avoid Send issues
								// LSP updates can be handled separately if needed
							}
							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, even on error/timeout
						indexing_in_progress.store(false, Ordering::SeqCst);
					}
					None => {
						debug!("Background indexing channel closed, stopping indexing task");
						break;
					}
				}
			}
		});

		// Store the indexing handle for cleanup
		self.indexing_handle = Some(indexing_handle);
		Ok(())
	}

	/// Send a JSON-RPC notification (no id — server-to-client push, no response expected).
	async fn send_notification(
		&self,
		writer: &mut tokio::io::Stdout,
		method: &str,
		params: serde_json::Value,
	) -> Result<()> {
		let notification = json!({
			"jsonrpc": "2.0",
			"method": method,
			"params": params,
		});
		let json = serde_json::to_string(&notification)?;
		tokio::time::timeout(Duration::from_millis(MCP_IO_TIMEOUT_MS), async {
			writer.write_all(json.as_bytes()).await?;
			writer.write_all(b"\n").await?;
			writer.flush().await
		})
		.await
		.map_err(|_| anyhow::anyhow!("Notification send timeout"))??;
		Ok(())
	}

	/// Safe request handling with comprehensive error recovery
	async fn handle_request_safe(&mut self, line: &str) -> Result<Option<JsonRpcResponse>> {
		let line = line.trim();
		if line.is_empty() {
			return Ok(None);
		}

		// Ensure clean UTF-8 by using lossy conversion to handle any potential issues
		let clean_line = String::from_utf8_lossy(line.as_bytes()).to_string();
		let line = clean_line.as_str();

		// Parse request with enhanced error handling
		let parsed_request: Result<JsonRpcRequest, _> =
			panic::catch_unwind(|| serde_json::from_str(line)).unwrap_or_else(|_| {
				Err(serde_json::Error::io(std::io::Error::new(
					std::io::ErrorKind::InvalidData,
					"JSON parsing panicked",
				)))
			});

		let request: JsonRpcRequest = match parsed_request {
			Ok(req) => {
				// Log the request with proper method and ID
				log_mcp_request(&req.method, req.params.as_ref(), req.id.as_ref());
				req
			}
			Err(e) => {
				log_critical_error("Request parsing", &e);
				return Ok(Some(JsonRpcResponse {
					jsonrpc: "2.0".to_string(),
					id: None,
					result: None,
					error: Some(JsonRpcError {
						code: -32700,
						message: format!("Parse error: {}", e),
						data: None,
					}),
				}));
			}
		};

		let start_time = std::time::Instant::now();
		let request_id = request.id.clone();
		let request_id_for_error = request_id.clone(); // Clone for error handling
		let request_method = request.method.clone(); // Clone for error handling

		// Execute request with comprehensive panic recovery (timeout control left to external MCP client)
		let response = match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
			// Create a new async runtime for the panic-safe execution
			// Note: This is a workaround since we can't easily catch panics in async code
			tokio::task::block_in_place(|| {
				tokio::runtime::Handle::current().block_on(async {
					// Execute request without internal timeout - let external MCP client control timeouts
					match request.method.as_str() {
						"initialize" => self.handle_initialize(&request).await,
						"tools/list" => self.handle_tools_list(&request).await,
						"tools/call" => self.handle_tools_call(&request).await,
						"ping" => self.handle_ping(&request).await,
						_ => JsonRpcResponse {
							jsonrpc: "2.0".to_string(),
							id: request.id,
							result: None,
							error: Some(JsonRpcError {
								code: -32601,
								message: "Method not found".to_string(),
								data: Some(json!({
									"method": request.method,
									"available_methods": ["initialize", "tools/list", "tools/call", "ping"]
								})),
							}),
						},
					}
				})
			})
		})) {
			Ok(response) => response,
			Err(_) => {
				log_critical_anyhow_error(
					"Request handler panicked",
					&anyhow::anyhow!("Method '{}' caused a panic", request_method),
				);
				JsonRpcResponse {
					jsonrpc: "2.0".to_string(),
					id: request_id_for_error,
					result: None,
					error: Some(JsonRpcError {
						code: -32603,
						message: "Internal server error (panic recovered)".to_string(),
						data: Some(json!({"method": request_method})),
					}),
				}
			}
		};

		// Log the response with timing
		let duration_ms = start_time.elapsed().as_millis() as u64;
		log_mcp_response(
			&request_method,
			response.error.is_none(),
			request_id.as_ref(),
			Some(duration_ms),
		);

		// Notifications (no id) must not receive a response per JSON-RPC/MCP behavior
		if request_id.is_none() {
			return Ok(None);
		}

		Ok(Some(response))
	}

	/// Helper method to detect broken pipe errors
	fn is_broken_pipe_error(&self, error: &std::io::Error) -> bool {
		use std::io::ErrorKind;
		matches!(
			error.kind(),
			ErrorKind::BrokenPipe
				| ErrorKind::ConnectionAborted
				| ErrorKind::ConnectionReset
				| ErrorKind::UnexpectedEof
		)
	}

	/// Safe response sending with error handling and size limits
	async fn send_response(
		&self,
		writer: &mut tokio::io::Stdout,
		response: &JsonRpcResponse,
	) -> Result<()> {
		// Serialize response with panic recovery and size checking
		let response_json = match panic::catch_unwind(|| serde_json::to_string(response)) {
			Ok(Ok(json)) => {
				// Check response size to prevent memory issues
				if json.len() > MCP_MAX_REQUEST_SIZE {
					log_critical_anyhow_error(
						"Response too large",
						&anyhow::anyhow!(
							"Response size {} exceeds limit {}",
							json.len(),
							MCP_MAX_REQUEST_SIZE
						),
					);
					// Create a minimal error response instead
					r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"Response too large"}}"#.to_string()
				} else {
					json
				}
			}
			Ok(Err(e)) => {
				log_critical_error("Response serialization failed", &e);
				// Create a minimal error response
				r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"Response serialization failed"}}"#.to_string()
			}
			Err(_) => {
				log_critical_anyhow_error(
					"Response serialization panicked",
					&anyhow::anyhow!("JSON serialization panicked"),
				);
				r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32603,"message":"Response serialization panicked"}}"#.to_string()
			}
		};

		// Send with timeout to prevent hanging on broken pipes
		tokio::time::timeout(Duration::from_millis(MCP_IO_TIMEOUT_MS), async {
			writer.write_all(response_json.as_bytes()).await?;
			writer.write_all(b"\n").await?;
			writer.flush().await
		})
		.await
		.map_err(|_| anyhow::anyhow!("Response send timeout"))??;

		Ok(())
	}

	/// Helper method to send error responses
	async fn send_error_response(
		&self,
		writer: &mut tokio::io::Stdout,
		id: Option<&serde_json::Value>,
		code: i32,
		message: &str,
		data: Option<serde_json::Value>,
	) -> Result<()> {
		let error_response = JsonRpcResponse {
			jsonrpc: "2.0".to_string(),
			id: id.cloned(),
			result: None,
			error: Some(JsonRpcError {
				code,
				message: message.to_string(),
				data,
			}),
		};

		self.send_response(writer, &error_response).await
	}

	async fn handle_initialize(&self, request: &JsonRpcRequest) -> JsonRpcResponse {
		// Build instructions with indexer warning if applicable
		let mut instructions = "This server provides modular AI tools: semantic code search and GraphRAG (if available). Use semantic_search for code/documentation searches and graphrag (if enabled) for relationship queries.".to_string();

		if !self.indexer_enabled {
			instructions.push_str("\n\nWARNING: Indexer is disabled because you're not in a git repository and the --no-git flag was not set. Use --no-git to enable indexing outside git repos.");
		}

		JsonRpcResponse {
			jsonrpc: "2.0".to_string(),
			id: request.id.clone(),
			result: Some(json!({
				"protocolVersion": "2024-11-05",
				"capabilities": {
					"tools": {
						"listChanged": false
					}
				},
				"serverInfo": {
					"name": "octocode-mcp",
					"version": "0.1.0",
					"description": "Semantic code search server with vector embeddings and optional GraphRAG support"
				},
				"instructions": instructions
			})),
			error: None,
		}
	}

	async fn handle_tools_list(&self, request: &JsonRpcRequest) -> JsonRpcResponse {
		let mut tools = vec![
			SemanticCodeProvider::get_tool_definition(),
			SemanticCodeProvider::get_view_signatures_tool_definition(),
		];

		// Add GraphRAG tools if available
		if self.graphrag.is_some() {
			tools.push(GraphRagProvider::get_tool_definition());
		}

		// Add LSP tools if LSP provider is configured (always show tools when --with-lsp is used)
		if self.lsp.is_some() {
			tools.extend(crate::mcp::lsp::LspProvider::get_tool_definitions());
		}

		JsonRpcResponse {
			jsonrpc: "2.0".to_string(),
			id: request.id.clone(),
			result: Some(json!({
				"tools": tools
			})),
			error: None,
		}
	}

	async fn handle_tools_call(&mut self, request: &JsonRpcRequest) -> JsonRpcResponse {
		let params = match &request.params {
			Some(params) => params,
			None => {
				return JsonRpcResponse {
					jsonrpc: "2.0".to_string(),
					id: request.id.clone(),
					result: None,
					error: Some(JsonRpcError {
						code: -32602,
						message: "Invalid params: missing parameters object".to_string(),
						data: Some(json!({
							"details": "Tool calls require a 'params' object with 'name' and 'arguments' fields"
						})),
					}),
				};
			}
		};

		let tool_name = match params.get("name").and_then(|v| v.as_str()) {
			Some(name) => name,
			None => {
				return JsonRpcResponse {
					jsonrpc: "2.0".to_string(),
					id: request.id.clone(),
					result: None,
					error: Some(JsonRpcError {
						code: -32602,
						message: "Invalid params: missing tool name".to_string(),
						data: Some(json!({
							"details": "Required field 'name' must be provided with the tool name to call"
						})),
					}),
				};
			}
		};

		let default_args = json!({});
		let arguments = params.get("arguments").unwrap_or(&default_args);

		// Validate arguments size to prevent memory exhaustion
		if let Ok(args_str) = serde_json::to_string(arguments) {
			if args_str.len() > MCP_MAX_REQUEST_SIZE {
				return JsonRpcResponse {
					jsonrpc: "2.0".to_string(),
					id: request.id.clone(),
					result: None,
					error: Some(JsonRpcError {
						code: -32602,
						message: "Tool arguments too large".to_string(),
						data: Some(json!({
							"max_size": MCP_MAX_REQUEST_SIZE,
							"actual_size": args_str.len()
						})),
					}),
				};
			}
		}

		let result = match tool_name {
			"semantic_search" => self.semantic_code.execute_search(arguments).await,
			"view_signatures" => self.semantic_code.execute_view_signatures(arguments).await,
			"graphrag" => match &self.graphrag {
				Some(provider) => provider.execute(arguments).await,
				None => Err(McpError::method_not_found("GraphRAG is not enabled in the current configuration. Please enable GraphRAG in octocode.toml to use relationship-aware search.", "graphrag")),
			},
			// LSP tools
			"lsp_goto_definition" => match &self.lsp {
				Some(provider) => {
					let mut lsp_guard = provider.lock().await;
					lsp_guard.execute_goto_definition(arguments).await
				},
				None => Err(McpError::method_not_found("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.", "lsp_goto_definition")),
			},
			"lsp_hover" => match &self.lsp {
				Some(provider) => {
					let mut lsp_guard = provider.lock().await;
					lsp_guard.execute_hover(arguments).await
				},
				None => Err(McpError::method_not_found("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.", "lsp_hover")),
			},
			"lsp_find_references" => match &self.lsp {
				Some(provider) => {
					let mut lsp_guard = provider.lock().await;
					lsp_guard.execute_find_references(arguments).await
				},
				None => Err(McpError::method_not_found("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.", "lsp_find_references")),
			},
			"lsp_document_symbols" => match &self.lsp {
				Some(provider) => {
					let mut lsp_guard = provider.lock().await;
					lsp_guard.execute_document_symbols(arguments).await
				},
				None => Err(McpError::method_not_found("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.", "lsp_document_symbols")),
			},
			"lsp_workspace_symbols" => match &self.lsp {
				Some(provider) => {
					let mut lsp_guard = provider.lock().await;
					lsp_guard.execute_workspace_symbols(arguments).await
				},
				None => Err(McpError::method_not_found("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.", "lsp_workspace_symbols")),
			},
			"lsp_completion" => match &self.lsp {
				Some(provider) => {
					let mut lsp_guard = provider.lock().await;
					lsp_guard.execute_completion(arguments).await
				},
				None => Err(McpError::method_not_found("LSP server is not available. Start MCP server with --with-lsp=\"<command>\" to enable LSP features.", "lsp_completion")),
			},
			_ => {
			let available_tools = format!("semantic_search, view_signatures{}{}",
				if self.graphrag.is_some() { ", graphrag" } else { "" },
				if self.lsp.is_some() { ", lsp_goto_definition, lsp_hover, lsp_find_references, lsp_document_symbols, lsp_workspace_symbols, lsp_completion" } else { "" }
			);
				Err(McpError::method_not_found(format!("Unknown tool '{}'. Available tools: {}", tool_name, available_tools), tool_name))
			}
		};

		match result {
			Ok(content) => JsonRpcResponse {
				jsonrpc: "2.0".to_string(),
				id: request.id.clone(),
				result: Some(json!({
					"content": [{
						"type": "text",
						"text": content
					}]
				})),
				error: None,
			},
			Err(e) => {
				// Try to parse MCP-compliant error first
				let error_message = e.to_string();
				if let Some(mcp_error) = parse_mcp_error(&error_message) {
					JsonRpcResponse {
						jsonrpc: "2.0".to_string(),
						id: request.id.clone(),
						result: None,
						error: Some(mcp_error),
					}
				} else {
					// Handle McpError directly
					JsonRpcResponse {
						jsonrpc: "2.0".to_string(),
						id: request.id.clone(),
						result: None,
						error: Some(e.into_jsonrpc()),
					}
				}
			}
		}
	}

	async fn handle_ping(&self, request: &JsonRpcRequest) -> JsonRpcResponse {
		JsonRpcResponse {
			jsonrpc: "2.0".to_string(),
			id: request.id.clone(),
			result: Some(json!({})),
			error: None,
		}
	}

	/// Update LSP server with recently changed files
	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");

		// Use existing file walker that respects .gitignore and .noindex
		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,
			};

			// Skip directories, only process files
			if !entry.file_type().is_some_and(|ft| ft.is_file()) {
				continue;
			}

			// Only process files that have a detected language (code files)
			if detect_language(entry.path()).is_some() {
				let relative_path = PathUtils::to_relative_string(entry.path(), working_directory);

				// Try to update the file in LSP
				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(())
	}
}

impl Drop for McpServer {
	fn drop(&mut self) {
		// Abort all background tasks so they don't outlive the server in any exit path
		// (panic, early return via ?, or graceful shutdown). Tokio tasks are NOT OS processes
		// so they can't truly escape the runtime, but aborting here ensures clean cancellation
		// and releases resources (file watchers, DB connections) immediately.
		if let Some(handle) = self.watcher_handle.take() {
			handle.abort();
		}
		if let Some(handle) = self.index_handle.take() {
			handle.abort();
		}
		if let Some(handle) = self.indexing_handle.take() {
			handle.abort();
		}
	}
}

// Helper functions
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);

	// Acquire indexing lock before starting
	let mut lock = IndexLock::new(working_directory)?;
	lock.acquire()?;
	debug!("MCP server: acquired indexing lock");

	// Create shared state for indexing (same as watch command)
	let state = state::create_shared_state();
	state.write().current_directory = working_directory.to_path_buf();

	// Get git root for optimization (same as watch command)
	let git_repo_root = if !no_git {
		indexer::git::find_git_root(working_directory)
	} else {
		None
	};

	// Perform the indexing directly (same as watch command in quiet mode)
	let indexing_result = indexer::index_files_with_quiet(
		store,
		state.clone(),
		config,
		git_repo_root.as_deref(),
		true,
	)
	.await;

	// Release the lock
	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_error("Direct indexing", e.as_ref());
			Err(e)
		}
	}
}