chasm_cli/mcp/
db.rs

1// Copyright (c) 2024-2026 Nervosys LLC
2// SPDX-License-Identifier: Apache-2.0
3//! MCP Database Access - Connect to the CSM database for csm-web integration
4//!
5//! This module provides read-only access to the CSM database, enabling the MCP server
6//! to expose csm-web's chat sessions without modifying VS Code's workspace storage.
7
8#![allow(dead_code, unused_imports)]
9
10use crate::database::{ChatDatabase, Message, Session, Workspace};
11use anyhow::Result;
12use std::path::PathBuf;
13
14/// Get the default CSM database path
15pub fn get_csm_db_path() -> PathBuf {
16    dirs::data_local_dir()
17        .map(|p| p.join("csm").join("csm.db"))
18        .unwrap_or_else(|| PathBuf::from("csm.db"))
19}
20
21/// Check if the CSM database exists
22pub fn csm_db_exists() -> bool {
23    get_csm_db_path().exists()
24}
25
26/// Open the CSM database (read-only mode)
27pub fn open_csm_db() -> Result<ChatDatabase> {
28    let path = get_csm_db_path();
29    ChatDatabase::open(&path)
30}
31
32/// List all workspaces from the CSM database
33pub fn list_db_workspaces() -> Result<Vec<Workspace>> {
34    let db = open_csm_db()?;
35    db.list_workspaces()
36}
37
38/// Get a specific workspace by ID
39pub fn get_db_workspace(id: &str) -> Result<Option<Workspace>> {
40    let db = open_csm_db()?;
41    db.get_workspace(id)
42}
43
44/// List sessions from the CSM database
45pub fn list_db_sessions(
46    workspace_id: Option<&str>,
47    provider: Option<&str>,
48    limit: usize,
49) -> Result<Vec<Session>> {
50    let db = open_csm_db()?;
51    db.list_sessions(workspace_id, provider, limit)
52}
53
54/// Get a specific session by ID
55pub fn get_db_session(id: &str) -> Result<Option<Session>> {
56    let db = open_csm_db()?;
57    db.get_session(id)
58}
59
60/// Get messages for a session
61pub fn get_db_messages(session_id: &str) -> Result<Vec<Message>> {
62    let db = open_csm_db()?;
63    db.get_messages(session_id)
64}
65
66/// Count sessions by provider
67pub fn count_sessions_by_provider() -> Result<Vec<(String, i64)>> {
68    let db = open_csm_db()?;
69    db.count_sessions_by_provider()
70}
71
72/// Search sessions by title or content
73pub fn search_db_sessions(query: &str, limit: usize) -> Result<Vec<Session>> {
74    let db = open_csm_db()?;
75
76    // Get all sessions and filter by title (simple search)
77    // For full-text search, we'd use the harvest database
78    let sessions = db.list_sessions(None, None, 1000)?;
79
80    let query_lower = query.to_lowercase();
81    let filtered: Vec<Session> = sessions
82        .into_iter()
83        .filter(|s| s.title.to_lowercase().contains(&query_lower))
84        .take(limit)
85        .collect();
86
87    Ok(filtered)
88}