-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathcodegraph.rs
More file actions
2454 lines (2177 loc) · 83.6 KB
/
Copy pathcodegraph.rs
File metadata and controls
2454 lines (2177 loc) · 83.6 KB
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
use anyhow::{Context, Result};
use atty::Stream;
use chrono::Utc;
use clap::{Parser, Subcommand};
use codegraph_mcp::{
EmbeddingThroughputConfig, IndexerConfig, ProcessManager, ProjectIndexer, RepositoryEstimate,
RepositoryEstimator,
};
use codegraph_mcp_core::debug_logger::DebugLogger;
#[cfg(feature = "daemon")]
use codegraph_mcp_daemon::{DaemonManager, PidFile, WatchConfig, WatchDaemon};
use codegraph_mcp_server::CodeGraphMCPServer;
use colored::Colorize;
use indicatif::{MultiProgress, ProgressBar, ProgressStyle};
use rmcp::ServiceExt;
use std::fs::File;
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tracing::info;
use tracing_subscriber::{
filter::EnvFilter, fmt::writer::BoxMakeWriter, layer::SubscriberExt, Registry,
};
const DEFAULT_JINA_BATCH_SIZE: usize = 2000;
const DEFAULT_JINA_BATCH_MINUTES: f64 = 9.0;
const DEFAULT_LOCAL_EMBEDDINGS_PER_WORKER_PER_MINUTE: f64 = 3600.0;
#[derive(Parser)]
#[command(
name = "codegraph",
version,
author,
about = "CodeGraph CLI - MCP server management and project indexing",
long_about = "CodeGraph provides a unified interface for managing MCP servers and indexing projects with the codegraph system."
)]
#[command(propagate_version = true)]
struct Cli {
#[command(subcommand)]
command: Commands,
#[arg(short, long, global = true, help = "Enable verbose logging")]
verbose: bool,
#[arg(
long,
global = true,
help = "Capture index logs to a file under .codegraph/logs"
)]
debug: bool,
#[arg(long, global = true, help = "Configuration file path")]
config: Option<PathBuf>,
}
#[derive(Subcommand)]
enum Commands {
#[command(about = "Start MCP server with specified transport")]
Start {
#[command(subcommand)]
transport: TransportType,
#[arg(short, long, help = "Server configuration file")]
config: Option<PathBuf>,
#[arg(long, help = "Run server in background")]
daemon: bool,
#[arg(long, help = "PID file location for daemon mode")]
pid_file: Option<PathBuf>,
},
#[command(about = "Run SurrealDB connectivity/schema canary (debug)")]
DbCheck {
#[arg(long, help = "Namespace to use (overrides env)")]
namespace: Option<String>,
#[arg(long, help = "Database to use (overrides env)")]
database: Option<String>,
},
#[command(about = "Stop running MCP server")]
Stop {
#[arg(long, help = "PID file location")]
pid_file: Option<PathBuf>,
#[arg(short, long, help = "Force stop without graceful shutdown")]
force: bool,
},
#[command(about = "Check status of MCP server")]
Status {
#[arg(long, help = "PID file location")]
pid_file: Option<PathBuf>,
#[arg(short, long, help = "Show detailed status information")]
detailed: bool,
},
#[command(
about = "Index a project or directory",
long_about = "Index a project with dual-mode support:\n\
• Local Mode (FAISS): Set CODEGRAPH_EMBEDDING_PROVIDER=local or ollama\n\
• Local Mode (SurrealDB HNSW + Ollama Embeddings + LMStudio Rerank): Set CODEGRAPH_EMBEDDING_PROVIDER=ollama and Set CODEGRAPH_RERANKING_PROVIDER=lmstudio\n\
• Cloud Mode (SurrealDB HNSW + Jina reranking): Set CODEGRAPH_EMBEDDING_PROVIDER=jina\n\
\n\
Some flags are mode-specific (see individual flag help for details)."
)]
Index {
#[arg(help = "Path to project directory")]
path: PathBuf,
#[arg(short, long, help = "Languages to index", value_delimiter = ',')]
languages: Option<Vec<String>>,
#[arg(long, help = "Exclude patterns (gitignore format)")]
exclude: Vec<String>,
#[arg(long, help = "Include only these patterns")]
include: Vec<String>,
#[arg(short, long, help = "Recursively index subdirectories")]
recursive: bool,
#[arg(long, help = "Force reindex even if already indexed")]
force: bool,
#[arg(long, help = "Watch for changes and auto-reindex")]
watch: bool,
#[arg(
long,
help = "Number of parallel workers (applies to both local and cloud modes)",
default_value = "4"
)]
workers: usize,
#[arg(
long,
help = "Embedding batch size (both modes; cloud mode uses API batching, local uses local processing batches)",
default_value = "100"
)]
batch_size: usize,
#[arg(
long,
help = "[Cloud mode only] Maximum concurrent API requests for parallel embedding generation (ignored in local mode)",
default_value = "10"
)]
max_concurrent: usize,
#[arg(
long,
help = "[Local mode only] Embedding device: cpu | metal | cuda:<id> (ignored in cloud mode)"
)]
device: Option<String>,
#[arg(
long,
help = "[Local mode only] Max sequence length for embeddings (ignored in cloud mode)",
default_value = "512"
)]
max_seq_len: usize,
#[arg(
long,
help = "Symbol embedding batch size (overrides generic batch size for precomputing symbols)",
value_parser = clap::value_parser!(usize)
)]
symbol_batch_size: Option<usize>,
#[arg(
long,
help = "Symbol embedding max concurrency (overrides generic max-concurrent)",
value_parser = clap::value_parser!(usize)
)]
symbol_max_concurrent: Option<usize>,
#[arg(long, value_enum, help = "Indexing tier: fast | balanced | full")]
index_tier: Option<IndexTier>,
},
#[command(
about = "Estimate indexing cost (node/edge counts + embedding ETA) without writing to SurrealDB"
)]
Estimate {
#[arg(help = "Path to project directory")]
path: PathBuf,
#[arg(short, long, help = "Languages to scan", value_delimiter = ',')]
languages: Option<Vec<String>>,
#[arg(long, help = "Exclude patterns (gitignore format)")]
exclude: Vec<String>,
#[arg(long, help = "Include only these patterns")]
include: Vec<String>,
#[arg(short, long, help = "Recursively walk subdirectories")]
recursive: bool,
#[arg(
long,
help = "Worker concurrency to assume for parsing/local embeddings",
default_value = "4"
)]
workers: usize,
#[arg(
long,
help = "Parser batch size baseline (affects local estimate heuristics)",
default_value = "100"
)]
batch_size: usize,
#[arg(
long,
help = "Override Jina batch size (defaults to 2000 based on current limits)"
)]
jina_batch_size: Option<usize>,
#[arg(
long,
help = "Override minutes per Jina batch (defaults to 9 based on observed throughput)"
)]
jina_batch_minutes: Option<f64>,
#[arg(
long,
help = "Override local embedding throughput (embeddings per minute)"
)]
local_throughput: Option<f64>,
#[arg(long, value_enum, help = "Indexing tier: fast | balanced | full")]
index_tier: Option<IndexTier>,
#[arg(short, long, help = "Output format", default_value = "human")]
format: StatsFormat,
},
#[command(about = "Manage MCP server configuration")]
Config {
#[command(subcommand)]
action: ConfigAction,
},
#[cfg(feature = "daemon")]
#[command(about = "Manage watch daemon for automatic re-indexing on file changes")]
Daemon {
#[command(subcommand)]
action: DaemonAction,
},
}
#[cfg(feature = "daemon")]
#[derive(Subcommand)]
enum DaemonAction {
#[command(about = "Start watch daemon for a project")]
Start {
#[arg(help = "Path to project directory", default_value = ".")]
path: PathBuf,
#[arg(long, help = "Run in foreground (default: daemonize)")]
foreground: bool,
#[arg(short, long, help = "Languages to watch", value_delimiter = ',')]
languages: Option<Vec<String>>,
#[arg(long, help = "Exclude patterns")]
exclude: Vec<String>,
#[arg(long, help = "Include patterns")]
include: Vec<String>,
},
#[command(about = "Stop running watch daemon")]
Stop {
#[arg(help = "Path to project directory", default_value = ".")]
path: PathBuf,
},
#[command(about = "Show watch daemon status")]
Status {
#[arg(help = "Path to project directory", default_value = ".")]
path: PathBuf,
#[arg(long, help = "Output as JSON")]
json: bool,
},
}
#[derive(Subcommand)]
enum TransportType {
#[command(about = "Start with STDIO transport (default)")]
Stdio {
#[arg(long, help = "Buffer size for STDIO", default_value = "8192")]
buffer_size: usize,
/// Enable automatic file watching and re-indexing (daemon mode)
#[arg(
long = "watch",
help = "Enable automatic file watching and re-indexing",
env = "CODEGRAPH_DAEMON_AUTO_START"
)]
enable_daemon: bool,
/// Path to watch for file changes (defaults to current directory)
#[arg(
long = "watch-path",
help = "Path to watch for file changes (defaults to current directory)",
env = "CODEGRAPH_DAEMON_WATCH_PATH"
)]
watch_path: Option<PathBuf>,
/// Explicitly disable daemon even if config enables it
#[arg(
long = "no-watch",
help = "Explicitly disable daemon even if config enables it"
)]
disable_daemon: bool,
},
#[command(about = "Start with HTTP streaming transport")]
Http {
#[arg(short, long, help = "Host to bind to", default_value = "127.0.0.1")]
host: String,
#[arg(short, long, help = "Port to bind to", default_value = "3000")]
port: u16,
#[arg(long, help = "Enable TLS/HTTPS")]
tls: bool,
#[arg(long, help = "TLS certificate file")]
cert: Option<PathBuf>,
#[arg(long, help = "TLS key file")]
key: Option<PathBuf>,
#[arg(long, help = "Enable CORS")]
cors: bool,
/// Enable automatic file watching and re-indexing (daemon mode)
#[arg(
long = "watch",
help = "Enable automatic file watching and re-indexing",
env = "CODEGRAPH_DAEMON_AUTO_START"
)]
enable_daemon: bool,
/// Path to watch for file changes (defaults to current directory)
#[arg(
long = "watch-path",
help = "Path to watch for file changes (defaults to current directory)",
env = "CODEGRAPH_DAEMON_WATCH_PATH"
)]
watch_path: Option<PathBuf>,
/// Explicitly disable daemon even if config enables it
#[arg(
long = "no-watch",
help = "Explicitly disable daemon even if config enables it"
)]
disable_daemon: bool,
},
#[command(about = "Start with both STDIO and HTTP transports")]
Dual {
#[arg(short, long, help = "HTTP host", default_value = "127.0.0.1")]
host: String,
#[arg(short, long, help = "HTTP port", default_value = "3000")]
port: u16,
#[arg(long, help = "STDIO buffer size", default_value = "8192")]
buffer_size: usize,
/// Enable automatic file watching and re-indexing (daemon mode)
#[arg(
long = "watch",
help = "Enable automatic file watching and re-indexing",
env = "CODEGRAPH_DAEMON_AUTO_START"
)]
enable_daemon: bool,
/// Path to watch for file changes (defaults to current directory)
#[arg(
long = "watch-path",
help = "Path to watch for file changes (defaults to current directory)",
env = "CODEGRAPH_DAEMON_WATCH_PATH"
)]
watch_path: Option<PathBuf>,
/// Explicitly disable daemon even if config enables it
#[arg(
long = "no-watch",
help = "Explicitly disable daemon even if config enables it"
)]
disable_daemon: bool,
},
}
#[derive(Subcommand)]
enum ConfigAction {
#[command(
about = "Initialize global configuration",
long_about = "Create global configuration files at ~/.codegraph/:\n\
• config.toml - Structured configuration\n\
• .env - Environment variables (recommended for API keys)\n\
\n\
Configuration hierarchy (highest to lowest priority):\n\
1. Environment variables\n\
2. Local .env (current directory)\n\
3. Global ~/.codegraph.env\n\
4. Local .codegraph.toml (current directory)\n\
5. Global ~/.codegraph/config.toml\n\
6. Built-in defaults"
)]
Init {
#[arg(short, long, help = "Overwrite existing files")]
force: bool,
},
#[command(about = "Show current configuration")]
Show {
#[arg(long, help = "Show as JSON")]
json: bool,
},
#[command(about = "Set configuration value")]
Set {
#[arg(help = "Configuration key")]
key: String,
#[arg(help = "Configuration value")]
value: String,
},
#[command(about = "Get configuration value")]
Get {
#[arg(help = "Configuration key")]
key: String,
},
#[command(about = "Reset configuration to defaults")]
Reset {
#[arg(short, long, help = "Skip confirmation")]
yes: bool,
},
#[command(about = "Validate configuration")]
Validate,
#[command(about = "Run SurrealDB connectivity/schema canary (debug)")]
DbCheck {
#[arg(long, help = "Namespace to use (overrides env)")]
namespace: Option<String>,
#[arg(long, help = "Database to use (overrides env)")]
database: Option<String>,
},
#[command(about = "Show orchestrator-agent configuration metadata")]
AgentStatus {
#[arg(long, help = "Show as JSON")]
json: bool,
},
}
#[derive(clap::ValueEnum, Clone, Debug)]
enum StatsFormat {
Table,
Json,
Yaml,
Human,
}
#[derive(clap::ValueEnum, Clone, Debug)]
enum IndexTier {
Fast,
Balanced,
Full,
}
impl From<IndexTier> for codegraph_core::config_manager::IndexingTier {
fn from(value: IndexTier) -> Self {
match value {
IndexTier::Fast => codegraph_core::config_manager::IndexingTier::Fast,
IndexTier::Balanced => codegraph_core::config_manager::IndexingTier::Balanced,
IndexTier::Full => codegraph_core::config_manager::IndexingTier::Full,
}
}
}
#[tokio::main]
async fn main() -> Result<()> {
// Load .env file if present
dotenv::dotenv().ok();
// Initialize debug logger (enabled with CODEGRAPH_DEBUG=1)
DebugLogger::init();
let cli = Cli::parse();
// Load configuration once at startup
use codegraph_core::config_manager::ConfigManager;
let config_mgr = ConfigManager::load().context("Failed to load configuration")?;
let config = config_mgr.config();
// TODO: Override with CLI config path if provided
if let Some(_config_path) = &cli.config {
// Future: merge CLI-specified config file
}
match cli.command {
Commands::Start {
transport,
config,
daemon,
pid_file,
} => {
handle_start(transport, config, daemon, pid_file).await?;
}
Commands::Stop { pid_file, force } => {
handle_stop(pid_file, force).await?;
}
Commands::Status { pid_file, detailed } => {
handle_status(pid_file, detailed).await?;
}
Commands::Index {
path,
languages,
exclude,
include,
recursive,
force,
watch,
workers,
batch_size,
max_concurrent,
device,
max_seq_len,
symbol_batch_size,
symbol_max_concurrent,
index_tier,
} => {
handle_index(
config,
path,
languages,
exclude,
include,
recursive,
force,
watch,
workers,
batch_size,
max_concurrent,
device,
max_seq_len,
symbol_batch_size,
symbol_max_concurrent,
index_tier,
cli.debug,
)
.await?;
}
Commands::Estimate {
path,
languages,
exclude,
include,
recursive,
workers,
batch_size,
jina_batch_size,
jina_batch_minutes,
local_throughput,
index_tier,
format,
} => {
handle_estimate(
config,
path,
languages,
exclude,
include,
recursive,
workers,
batch_size,
jina_batch_size,
jina_batch_minutes,
local_throughput,
index_tier,
format,
)
.await?;
}
Commands::Config { action } => {
handle_config(action).await?;
}
Commands::DbCheck {
namespace,
database,
} => {
handle_db_check(namespace, database).await?;
}
#[cfg(feature = "daemon")]
Commands::Daemon { action } => {
handle_daemon(action).await?;
}
}
Ok(())
}
async fn handle_start(
transport: TransportType,
config: Option<PathBuf>,
daemon: bool,
pid_file: Option<PathBuf>,
) -> Result<()> {
let manager = ProcessManager::new();
match transport {
TransportType::Stdio {
buffer_size: _buffer_size,
enable_daemon,
watch_path,
disable_daemon,
} => {
// Configure logging to file for stdio transport (stdout/stderr are used for MCP protocol)
// Logs will be written to .codegraph/logs/mcp-server.log
let log_dir = std::env::current_dir()
.unwrap_or_else(|_| std::path::PathBuf::from("."))
.join(".codegraph")
.join("logs");
std::fs::create_dir_all(&log_dir).ok();
// Use tracing_appender for non-blocking file writes
let file_appender = tracing_appender::rolling::never(&log_dir, "mcp-server.log");
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
let subscriber = tracing_subscriber::fmt()
.with_writer(non_blocking)
.with_max_level(tracing_subscriber::filter::LevelFilter::INFO)
.with_ansi(false)
.with_target(false)
.with_line_number(true)
.finish();
tracing::subscriber::set_global_default(subscriber).ok();
// Keep the guard alive for the duration of the server
std::mem::forget(_guard);
// Start background daemon if enabled
#[cfg(feature = "daemon")]
let mut daemon_manager: Option<DaemonManager> = None;
#[cfg(feature = "daemon")]
{
use codegraph_core::config_manager::ConfigManager;
// Load configuration
if let Ok(config_mgr) = ConfigManager::load() {
let global_config = config_mgr.config().clone();
// Determine if daemon should start:
// Priority: --no-watch > --watch > config.daemon.auto_start_with_mcp
let should_start_daemon = if disable_daemon {
false
} else if enable_daemon {
true
} else {
global_config.daemon.auto_start_with_mcp
};
if should_start_daemon {
let project_root = watch_path
.or_else(|| global_config.daemon.project_path.clone())
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
let project_root =
std::fs::canonicalize(&project_root).unwrap_or(project_root);
// Create daemon config with auto_start forced on
let daemon_config = codegraph_core::config_manager::DaemonConfig {
auto_start_with_mcp: true,
project_path: Some(project_root.clone()),
..global_config.daemon.clone()
};
let mut dm =
DaemonManager::new(daemon_config, global_config, project_root.clone());
match dm.start_background().await {
Ok(()) => {
if atty::is(Stream::Stderr) {
eprintln!(
"{}",
format!("🔄 Daemon watching: {}", project_root.display())
.cyan()
);
}
daemon_manager = Some(dm);
}
Err(e) => {
// Log error but continue - MCP server should still work
if atty::is(Stream::Stderr) {
eprintln!(
"{}",
format!(
"⚠️ Daemon failed to start: {} (MCP server continuing)",
e
)
.yellow()
);
}
tracing::warn!("Daemon startup failed: {}", e);
}
}
}
}
}
if atty::is(Stream::Stderr) {
eprintln!(
"{}",
"Starting CodeGraph MCP Server with 100% Official SDK..."
.green()
.bold()
);
}
// Create and initialize the revolutionary CodeGraph server with official SDK
let server = CodeGraphMCPServer::new();
if atty::is(Stream::Stderr) {
eprintln!(
"✅ Revolutionary CodeGraph MCP server ready with 100% protocol compliance"
);
}
// Use official rmcp STDIO transport for perfect compliance
let service: rmcp::service::RunningService<rmcp::RoleServer, CodeGraphMCPServer> =
server.serve(rmcp::transport::stdio()).await.map_err(|e| {
if atty::is(Stream::Stderr) {
eprintln!("❌ Failed to start official MCP server: {}", e);
}
anyhow::anyhow!("MCP server startup failed: {}", e)
})?;
if atty::is(Stream::Stderr) {
eprintln!("🚀 Official MCP server started with revolutionary capabilities");
}
// Wait for the server to complete
service
.waiting()
.await
.map_err(|e| anyhow::anyhow!("Server error: {}", e))?;
// Clean up daemon on exit
#[cfg(feature = "daemon")]
if let Some(mut dm) = daemon_manager {
if let Err(e) = dm.stop().await {
tracing::warn!("Daemon cleanup error: {}", e);
}
}
}
TransportType::Http {
host,
port,
tls,
cert,
key,
cors: _,
enable_daemon,
watch_path,
disable_daemon,
} => {
#[cfg(not(feature = "server-http"))]
let _ = (
host,
port,
tls,
cert,
key,
enable_daemon,
watch_path,
disable_daemon,
);
#[cfg(not(feature = "server-http"))]
{
eprintln!("🚧 HTTP transport requires the 'server-http' feature");
eprintln!();
eprintln!("💡 Rebuild with HTTP support:");
eprintln!(" cargo build --release --features server-http");
eprintln!();
eprintln!("💡 Or use STDIO transport:");
eprintln!(" codegraph start stdio");
return Err(anyhow::anyhow!(
"HTTP transport not enabled - rebuild with 'server-http' feature"
));
}
#[cfg(feature = "server-http")]
{
use axum::Router;
use rmcp::transport::streamable_http_server::{
session::local::LocalSessionManager, StreamableHttpServerConfig,
StreamableHttpService,
};
use std::sync::Arc;
use std::time::Duration;
// Start background daemon if enabled
#[cfg(feature = "daemon")]
let mut daemon_manager: Option<DaemonManager> = None;
#[cfg(feature = "daemon")]
{
use codegraph_core::config_manager::ConfigManager;
if let Ok(config_mgr) = ConfigManager::load() {
let global_config = config_mgr.config().clone();
let should_start_daemon = if disable_daemon {
false
} else if enable_daemon {
true
} else {
global_config.daemon.auto_start_with_mcp
};
if should_start_daemon {
let project_root = watch_path
.or_else(|| global_config.daemon.project_path.clone())
.unwrap_or_else(|| std::env::current_dir().unwrap_or_default());
let project_root =
std::fs::canonicalize(&project_root).unwrap_or(project_root);
let daemon_config = codegraph_core::config_manager::DaemonConfig {
auto_start_with_mcp: true,
project_path: Some(project_root.clone()),
..global_config.daemon.clone()
};
let mut dm = DaemonManager::new(
daemon_config,
global_config,
project_root.clone(),
);
match dm.start_background().await {
Ok(()) => {
eprintln!(
"{}",
format!("🔄 Daemon watching: {}", project_root.display())
.cyan()
);
daemon_manager = Some(dm);
}
Err(e) => {
eprintln!(
"{}",
format!(
"⚠️ Daemon failed to start: {} (HTTP server continuing)",
e
)
.yellow()
);
tracing::warn!("Daemon startup failed: {}", e);
}
}
}
}
}
if atty::is(Stream::Stderr) {
eprintln!(
"{}",
"Starting CodeGraph MCP Server with HTTP transport..."
.green()
.bold()
);
}
// Handle TLS configuration
if tls {
if cert.is_none() || key.is_none() {
return Err(anyhow::anyhow!(
"TLS enabled but certificate or key not provided. Use --cert and --key"
));
}
eprintln!("⚠️ TLS configuration detected but not yet implemented");
eprintln!(" Server will start without TLS");
}
// Create session manager for stateful HTTP connections
let session_manager = Arc::new(LocalSessionManager::default());
// Service factory - creates new CodeGraphMCPServer for each session
let service_factory = || {
let server = CodeGraphMCPServer::new();
// Note: initialize_qwen() is async, but service factory must be sync
// Qwen initialization will happen on first use
Ok(server)
};
// Configure HTTP server with SSE streaming
let config = StreamableHttpServerConfig {
sse_keep_alive: Some(Duration::from_secs(15)), // Send keep-alive every 15s
stateful_mode: true, // Enable session management + SSE
cancellation_token: tokio_util::sync::CancellationToken::new(),
};
if atty::is(Stream::Stderr) {
eprintln!("📡 Configuring StreamableHTTP with SSE keep-alive (15s)");
}
// Create StreamableHttpService (implements tower::Service)
let http_service =
StreamableHttpService::new(service_factory, session_manager, config);
// Create Axum router
let app = Router::new().fallback_service(http_service);
// Bind to address
let addr = format!("{}:{}", host, port);
let listener = tokio::net::TcpListener::bind(&addr)
.await
.map_err(|e| anyhow::anyhow!("Failed to bind to {}: {}", addr, e))?;
if atty::is(Stream::Stderr) {
eprintln!("✅ CodeGraph MCP HTTP server ready");
eprintln!("🚀 Listening on http://{}", addr);
eprintln!();
eprintln!("📋 HTTP Endpoints:");
eprintln!(" POST /mcp - Initialize session");
eprintln!(" GET /mcp - Open SSE stream (with Mcp-Session-Id header)");
eprintln!(" POST /mcp - Send request (with Mcp-Session-Id header)");
eprintln!(" DELETE /mcp - Close session");
eprintln!();
eprintln!("💡 Progress notifications stream via Server-Sent Events");
}
// Serve with Axum
axum::serve(listener, app)
.await
.map_err(|e| anyhow::anyhow!("HTTP server error: {}", e))?;
// Clean up daemon on exit
#[cfg(feature = "daemon")]
if let Some(mut dm) = daemon_manager {
if let Err(e) = dm.stop().await {
tracing::warn!("Daemon cleanup error: {}", e);
}
}
}
}
TransportType::Dual {
host,
port,
buffer_size,
enable_daemon: _,
watch_path: _,
disable_daemon: _,
} => {
// Note: Dual transport doesn't support daemon integration yet
// The daemon fields are accepted but not used
info!("Starting with dual transport (STDIO + HTTP)");
let (stdio_pid, http_pid) = manager
.start_dual_transport(
host.clone(),
port,
buffer_size,
config,
daemon,
pid_file.clone(),
)
.await?;
if atty::is(Stream::Stdout) {
println!("✓ MCP server started with dual transport");
println!(" STDIO: buffer size {} (PID: {})", buffer_size, stdio_pid);
println!(" HTTP: http://{}:{} (PID: {})", host, port, http_pid);
}
}
}
if daemon {
if atty::is(Stream::Stdout) {
println!("Running in daemon mode");
if let Some(ref pid_file) = pid_file {
println!("PID file: {:?}", pid_file);
}
}
}