Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ tracing-subscriber = "0.3"
walkdir = "2"
glob = "0.3"
futures-util = "0.3"
subtle = "2"
sha2 = "0.10"
rayon = "1.10"
pulldown-cmark = "0.12"
Expand Down
12 changes: 12 additions & 0 deletions src/cli/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,18 @@ pub enum CLICommand {
#[arg(long)]
watch: bool,
},
/// Start MCP server with HTTP transport (for remote clients)
McpHttp {
/// Port to listen on (default: 9699)
#[arg(long)]
port: Option<u16>,
/// Bearer token for authentication (optional)
#[arg(long)]
auth: Option<String>,
/// Enable auto-indexing with file watcher
#[arg(long)]
watch: bool,
},
/// Calculate impact radius
Impact {
/// File to analyze
Expand Down
43 changes: 43 additions & 0 deletions src/config/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,13 @@ use serde::{Deserialize, Serialize};
use std::path::PathBuf;

#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ProjectConfig {
pub project: ProjectSettings,
pub indexer: IndexerConfig,
pub mcp: McpConfig,
pub documentation: DocConfig,
pub database: DatabaseConfig,
pub microservice: Option<MicroserviceExtractorConfig>,
}

Expand Down Expand Up @@ -61,6 +63,46 @@ pub struct McpConfig {
pub auto_index_on_db_write: bool,
}

/// Database configuration for LeanKG
/// SQLite (CozoDB embedded) is the default, PostgreSQL can be used for
/// multi-client HTTP server deployments
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DatabaseConfig {
/// Database backend: "sqlite" or "postgres"
#[serde(default = "default_backend")]
pub backend: String,
/// For SQLite: path to .leankg directory
/// For PostgreSQL: connection string (e.g., "postgres://user:pass@localhost:5432/leankg")
pub path: Option<String>,
/// PostgreSQL connection pool size (only for postgres backend)
/// Reserved for future PostgreSQL support - currently unused
#[serde(default = "default_pool_size")]
pub pool_size: u32,
/// Enable SSL for PostgreSQL connections
/// Reserved for future PostgreSQL support - currently unused
#[serde(default)]
pub ssl_enabled: bool,
}

fn default_backend() -> String {
"sqlite".to_string()
}

fn default_pool_size() -> u32 {
10
}

impl Default for DatabaseConfig {
fn default() -> Self {
Self {
backend: default_backend(),
path: None,
pool_size: default_pool_size(),
ssl_enabled: false,
}
}
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DocConfig {
pub output: PathBuf,
Expand Down Expand Up @@ -105,6 +147,7 @@ impl Default for ProjectConfig {
output: PathBuf::from("./docs"),
templates: vec!["agents".to_string(), "claude".to_string()],
},
database: DatabaseConfig::default(),
microservice: None,
}
}
Expand Down
49 changes: 49 additions & 0 deletions src/db/schema.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use cozo::{Db, SqliteStorage};
use std::path::Path;

use crate::config::project::DatabaseConfig;

pub type CozoDb = Db<SqliteStorage>;

pub fn init_db(db_path: &Path) -> Result<CozoDb, Box<dyn std::error::Error>> {
Expand Down Expand Up @@ -34,6 +36,53 @@ pub fn init_db(db_path: &Path) -> Result<CozoDb, Box<dyn std::error::Error>> {
Ok(db)
}

/// Initialize database with configuration-based backend selection
/// Currently only supports SQLite. PostgreSQL support will be added when cozo adds it.
/// The config struct is prepared for future use.
pub fn init_db_with_config(config: &DatabaseConfig) -> Result<CozoDb, Box<dyn std::error::Error>> {
match config.backend.as_str() {
"postgres" | "postgresql" => {
Err("PostgreSQL support requires cozo version with PG storage. Currently only SQLite is supported.".into())
}
_ => {
// Default to SQLite if path is provided, otherwise use default location
if let Some(path) = &config.path {
init_sqlite_at_path(path)
} else {
// Use default path in current directory
init_sqlite_default()
}
}
}
}

fn init_sqlite_at_path(path_str: &str) -> Result<CozoDb, Box<dyn std::error::Error>> {
let db = cozo::new_cozo_sqlite(path_str.to_string())?;

// Set memory limits for SQLite (CozoDB backend)
let pragmas = [
"PRAGMA cache_size = -64000",
"PRAGMA mmap_size = 268435456",
"PRAGMA temp_store = MEMORY",
"PRAGMA synchronous = NORMAL",
"PRAGMA journal_mode = WAL",
"PRAGMA wal_autocheckpoint = 100",
];
for pragma in pragmas {
if let Err(e) = db.run_script(pragma, Default::default()) {
tracing::debug!("Pragma '{}' failed (may not be supported): {}", pragma, e);
}
}

init_schema(&db)?;

Ok(db)
}

fn init_sqlite_default() -> Result<CozoDb, Box<dyn std::error::Error>> {
init_sqlite_at_path(".leankg/leankg.db")
}

fn init_schema(db: &CozoDb) -> Result<(), Box<dyn std::error::Error>> {
let check_relations = r#"::relations"#;
let relations_result = db.run_script(check_relations, Default::default())?;
Expand Down
35 changes: 35 additions & 0 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,41 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
eprintln!("MCP stdio server error: {}", e);
}
}
cli::CLICommand::McpHttp { port, auth, watch } => {
let project_path = find_project_root()?;
let db_path = project_path.join(".leankg");
let port = port.unwrap_or_else(|| {
std::env::var("MCP_HTTP_PORT")
.ok()
.and_then(|p| p.parse().ok())
.unwrap_or(9699)
});
let auth_token = auth.or_else(|| std::env::var("MCP_HTTP_AUTH").ok());

tokio::fs::create_dir_all(&db_path).await.ok();

let mcp_server = if watch {
mcp::MCPServer::new_with_watch(db_path.clone(), project_path.clone())
} else {
mcp::MCPServer::new(db_path.clone())
};

println!("╔═══════════════════════════════════════════════════════════════╗");
println!("║ LeanKG MCP HTTP Server (Remote Mode) ║");
println!("╚═══════════════════════════════════════════════════════════════╝");
println!();
println!("🚀 Starting MCP HTTP server on http://localhost:{}", port);
if auth_token.is_some() {
println!("🔒 Authentication: enabled");
} else {
println!("🔓 Authentication: disabled (not recommended for production)");
}
println!();

if let Err(e) = mcp_server.serve_http(port, auth_token).await {
eprintln!("MCP HTTP server error: {}", e);
}
}
cli::CLICommand::Impact { file, depth } => {
let project_path = find_project_root()?;
let db_path = project_path.join(".leankg");
Expand Down
Loading
Loading