lore-cli 0.1.13

Capture AI coding sessions and link them to git commits
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
//! MCP server implementation for Lore.
//!
//! Runs an MCP server on stdio transport, exposing Lore tools to
//! AI coding assistants like Claude Code.

use anyhow::Result;
use rmcp::{
    handler::server::{router::tool::ToolRouter, wrapper::Parameters},
    model::{
        CallToolResult, Content, ErrorCode, ErrorData as McpError, Implementation, ProtocolVersion,
        ServerCapabilities, ServerInfo,
    },
    tool, tool_handler, tool_router,
    transport::stdio,
    ServerHandler, ServiceExt,
};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::borrow::Cow;

use crate::storage::models::{Message, SearchOptions, Session};
use crate::storage::Database;

// ============== Tool Parameter Types ==============

/// Parameters for the lore_search tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct SearchParams {
    /// The search query text.
    #[schemars(description = "Text to search for in session messages")]
    pub query: String,

    /// Maximum number of results to return.
    #[schemars(description = "Maximum number of results (default: 10)")]
    pub limit: Option<usize>,

    /// Filter by repository path prefix.
    #[schemars(description = "Filter by repository path prefix")]
    pub repo: Option<String>,

    /// Filter by AI tool name (e.g., claude-code, aider).
    #[schemars(description = "Filter by AI tool name (e.g., claude-code, aider)")]
    pub tool: Option<String>,

    /// Filter to sessions after this date (ISO 8601 or relative like 7d, 2w, 1m).
    #[schemars(description = "Filter to sessions after this date (ISO 8601 or 7d, 2w, 1m)")]
    pub since: Option<String>,
}

/// Parameters for the lore_get_session tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetSessionParams {
    /// Session ID (full UUID or prefix).
    #[schemars(description = "Session ID (full UUID or short prefix like abc123)")]
    pub session_id: String,

    /// Whether to include full message content.
    #[schemars(description = "Include full message content (default: true)")]
    pub include_messages: Option<bool>,
}

/// Parameters for the lore_list_sessions tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct ListSessionsParams {
    /// Maximum number of sessions to return.
    #[schemars(description = "Maximum number of sessions (default: 10)")]
    pub limit: Option<usize>,

    /// Filter by repository path prefix.
    #[schemars(description = "Filter by repository path prefix")]
    pub repo: Option<String>,
}

/// Parameters for the lore_get_context tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetContextParams {
    /// Repository path to get context for.
    #[schemars(description = "Repository path (defaults to current directory)")]
    pub repo: Option<String>,

    /// Whether to show detailed info for the most recent session only.
    #[schemars(description = "Show detailed info for the most recent session only")]
    pub last: Option<bool>,
}

/// Parameters for the lore_get_linked_sessions tool.
#[derive(Debug, Deserialize, JsonSchema)]
pub struct GetLinkedSessionsParams {
    /// Git commit SHA (full or prefix).
    #[schemars(description = "Git commit SHA (full or short prefix)")]
    pub commit_sha: String,
}

// ============== Result Types ==============

/// A session in search results.
#[derive(Debug, Serialize)]
pub struct SessionInfo {
    pub id: String,
    pub id_short: String,
    pub tool: String,
    pub started_at: String,
    pub message_count: i32,
    pub working_directory: String,
    pub git_branch: Option<String>,
}

/// A search match result.
#[derive(Debug, Serialize)]
pub struct SearchMatch {
    pub session: SessionInfo,
    pub message_id: String,
    pub role: String,
    pub snippet: String,
    pub timestamp: String,
}

/// Search results response.
#[derive(Debug, Serialize)]
pub struct SearchResponse {
    pub query: String,
    pub total_matches: usize,
    pub matches: Vec<SearchMatch>,
}

/// A message for session transcript.
#[derive(Debug, Serialize)]
pub struct MessageInfo {
    pub index: i32,
    pub role: String,
    pub content: String,
    pub timestamp: String,
}

/// Full session details response.
#[derive(Debug, Serialize)]
pub struct SessionDetailsResponse {
    pub session: SessionInfo,
    pub linked_commits: Vec<String>,
    pub messages: Option<Vec<MessageInfo>>,
    pub summary: Option<String>,
    pub tags: Vec<String>,
}

/// Context response for a repository.
#[derive(Debug, Serialize)]
pub struct ContextResponse {
    pub working_directory: String,
    pub sessions: Vec<SessionInfo>,
    pub recent_messages: Option<Vec<MessageInfo>>,
}

/// Linked sessions response.
#[derive(Debug, Serialize)]
pub struct LinkedSessionsResponse {
    pub commit_sha: String,
    pub sessions: Vec<SessionInfo>,
}

// ============== Server Implementation ==============

/// The Lore MCP server.
///
/// Provides tools for querying Lore session data via MCP.
#[derive(Debug, Clone)]
pub struct LoreServer {
    tool_router: ToolRouter<LoreServer>,
}

impl LoreServer {
    /// Creates a new LoreServer.
    pub fn new() -> Self {
        Self {
            tool_router: Self::tool_router(),
        }
    }
}

impl Default for LoreServer {
    fn default() -> Self {
        Self::new()
    }
}

/// Creates an McpError from an error message.
fn mcp_error(message: &str) -> McpError {
    McpError {
        code: ErrorCode(-32603),
        message: Cow::from(message.to_string()),
        data: None,
    }
}

#[tool_router]
impl LoreServer {
    /// Search Lore sessions by query text with optional filters.
    ///
    /// Searches message content using full-text search. Supports filtering
    /// by repository, tool, and date range.
    #[tool(description = "Search Lore session messages for text content")]
    async fn lore_search(
        &self,
        params: Parameters<SearchParams>,
    ) -> Result<CallToolResult, McpError> {
        let params = params.0;
        let result = search_impl(params);
        match result {
            Ok(response) => {
                let json = serde_json::to_string_pretty(&response)
                    .unwrap_or_else(|e| format!("Error serializing response: {e}"));
                Ok(CallToolResult::success(vec![Content::text(json)]))
            }
            Err(e) => Err(mcp_error(&format!("Search failed: {e}"))),
        }
    }

    /// Get full details of a Lore session by ID.
    ///
    /// Returns session metadata, linked commits, and optionally the full
    /// message transcript.
    #[tool(description = "Get full details of a Lore session by ID")]
    async fn lore_get_session(
        &self,
        params: Parameters<GetSessionParams>,
    ) -> Result<CallToolResult, McpError> {
        let params = params.0;
        let result = get_session_impl(params);
        match result {
            Ok(response) => {
                let json = serde_json::to_string_pretty(&response)
                    .unwrap_or_else(|e| format!("Error serializing response: {e}"));
                Ok(CallToolResult::success(vec![Content::text(json)]))
            }
            Err(e) => Err(mcp_error(&format!("Get session failed: {e}"))),
        }
    }

    /// List recent Lore sessions.
    ///
    /// Returns a list of recent sessions, optionally filtered by repository.
    #[tool(description = "List recent Lore sessions")]
    async fn lore_list_sessions(
        &self,
        params: Parameters<ListSessionsParams>,
    ) -> Result<CallToolResult, McpError> {
        let params = params.0;
        let result = list_sessions_impl(params);
        match result {
            Ok(sessions) => {
                let json = serde_json::to_string_pretty(&sessions)
                    .unwrap_or_else(|e| format!("Error serializing response: {e}"));
                Ok(CallToolResult::success(vec![Content::text(json)]))
            }
            Err(e) => Err(mcp_error(&format!("List sessions failed: {e}"))),
        }
    }

    /// Get recent session context for a repository.
    ///
    /// Provides a summary of recent sessions for quick orientation.
    #[tool(description = "Get recent session context for a repository")]
    async fn lore_get_context(
        &self,
        params: Parameters<GetContextParams>,
    ) -> Result<CallToolResult, McpError> {
        let params = params.0;
        let result = get_context_impl(params);
        match result {
            Ok(response) => {
                let json = serde_json::to_string_pretty(&response)
                    .unwrap_or_else(|e| format!("Error serializing response: {e}"));
                Ok(CallToolResult::success(vec![Content::text(json)]))
            }
            Err(e) => Err(mcp_error(&format!("Get context failed: {e}"))),
        }
    }

    /// Get sessions linked to a git commit.
    ///
    /// Returns all sessions that have been linked to the specified commit.
    #[tool(description = "Get Lore sessions linked to a git commit")]
    async fn lore_get_linked_sessions(
        &self,
        params: Parameters<GetLinkedSessionsParams>,
    ) -> Result<CallToolResult, McpError> {
        let params = params.0;
        let result = get_linked_sessions_impl(params);
        match result {
            Ok(response) => {
                let json = serde_json::to_string_pretty(&response)
                    .unwrap_or_else(|e| format!("Error serializing response: {e}"));
                Ok(CallToolResult::success(vec![Content::text(json)]))
            }
            Err(e) => Err(mcp_error(&format!("Get linked sessions failed: {e}"))),
        }
    }
}

#[tool_handler]
impl ServerHandler for LoreServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::V_2024_11_05,
            capabilities: ServerCapabilities::builder().enable_tools().build(),
            server_info: Implementation::from_build_env(),
            instructions: Some(
                "Lore is a reasoning history system for code. It captures AI coding sessions \
                 and links them to git commits. Use these tools to search session history, \
                 view session transcripts, and find sessions linked to commits."
                    .to_string(),
            ),
        }
    }
}

// ============== Implementation Functions ==============

/// Parses a date string (ISO 8601 or relative like 7d, 2w, 1m) into a DateTime.
fn parse_date(date_str: &str) -> anyhow::Result<chrono::DateTime<chrono::Utc>> {
    use chrono::{Duration, Utc};

    let date_str = date_str.trim().to_lowercase();

    // Try relative format first (e.g., "7d", "2w", "1m")
    if date_str.ends_with('d') {
        let days: i64 = date_str[..date_str.len() - 1].parse()?;
        return Ok(Utc::now() - Duration::days(days));
    }

    if date_str.ends_with('w') {
        let weeks: i64 = date_str[..date_str.len() - 1].parse()?;
        return Ok(Utc::now() - Duration::weeks(weeks));
    }

    if date_str.ends_with('m') {
        let months: i64 = date_str[..date_str.len() - 1].parse()?;
        return Ok(Utc::now() - Duration::days(months * 30));
    }

    // Try ISO 8601 format
    if let Ok(dt) = chrono::DateTime::parse_from_rfc3339(&date_str) {
        return Ok(dt.with_timezone(&Utc));
    }

    // Try date-only format
    if let Ok(date) = chrono::NaiveDate::parse_from_str(&date_str, "%Y-%m-%d") {
        let datetime = date
            .and_hms_opt(0, 0, 0)
            .ok_or_else(|| anyhow::anyhow!("Invalid date"))?;
        return Ok(datetime.and_utc());
    }

    anyhow::bail!("Invalid date format: {date_str}")
}

/// Converts a Session to SessionInfo.
fn session_to_info(session: &Session) -> SessionInfo {
    SessionInfo {
        id: session.id.to_string(),
        id_short: session.id.to_string()[..8].to_string(),
        tool: session.tool.clone(),
        started_at: session.started_at.to_rfc3339(),
        message_count: session.message_count,
        working_directory: session.working_directory.clone(),
        git_branch: session.git_branch.clone(),
    }
}

/// Converts a Message to MessageInfo.
fn message_to_info(message: &Message) -> MessageInfo {
    MessageInfo {
        index: message.index,
        role: message.role.to_string(),
        content: message.content.text(),
        timestamp: message.timestamp.to_rfc3339(),
    }
}

/// Implementation of the search tool.
fn search_impl(params: SearchParams) -> anyhow::Result<SearchResponse> {
    let db = Database::open_default()?;

    // Build search index if needed
    if db.search_index_needs_rebuild()? {
        db.rebuild_search_index()?;
    }

    let since = params.since.as_ref().map(|s| parse_date(s)).transpose()?;

    let options = SearchOptions {
        query: params.query.clone(),
        limit: params.limit.unwrap_or(10),
        repo: params.repo,
        tool: params.tool,
        since,
        ..Default::default()
    };

    let results = db.search_with_options(&options)?;

    let matches: Vec<SearchMatch> = results
        .into_iter()
        .map(|r| SearchMatch {
            session: SessionInfo {
                id: r.session_id.to_string(),
                id_short: r.session_id.to_string()[..8].to_string(),
                tool: r.tool,
                started_at: r
                    .session_started_at
                    .map(|dt| dt.to_rfc3339())
                    .unwrap_or_default(),
                message_count: r.session_message_count,
                working_directory: r.working_directory,
                git_branch: r.git_branch,
            },
            message_id: r.message_id.to_string(),
            role: r.role.to_string(),
            snippet: r.snippet,
            timestamp: r.timestamp.to_rfc3339(),
        })
        .collect();

    let total = matches.len();

    Ok(SearchResponse {
        query: params.query,
        total_matches: total,
        matches,
    })
}

/// Implementation of the get_session tool.
fn get_session_impl(params: GetSessionParams) -> anyhow::Result<SessionDetailsResponse> {
    let db = Database::open_default()?;

    // Try to find session by ID prefix
    let session_id = resolve_session_id(&db, &params.session_id)?;
    let session = db
        .get_session(&session_id)?
        .ok_or_else(|| anyhow::anyhow!("Session not found: {}", params.session_id))?;

    // Get linked commits
    let links = db.get_links_by_session(&session_id)?;
    let linked_commits: Vec<String> = links.iter().filter_map(|l| l.commit_sha.clone()).collect();

    // Get messages if requested
    let messages = if params.include_messages.unwrap_or(true) {
        let msgs = db.get_messages(&session_id)?;
        Some(msgs.iter().map(message_to_info).collect())
    } else {
        None
    };

    // Get summary and tags
    let summary = db.get_summary(&session_id)?.map(|s| s.content);
    let tags: Vec<String> = db
        .get_tags(&session_id)?
        .into_iter()
        .map(|t| t.label)
        .collect();

    Ok(SessionDetailsResponse {
        session: session_to_info(&session),
        linked_commits,
        messages,
        summary,
        tags,
    })
}

/// Implementation of the list_sessions tool.
fn list_sessions_impl(params: ListSessionsParams) -> anyhow::Result<Vec<SessionInfo>> {
    let db = Database::open_default()?;

    let limit = params.limit.unwrap_or(10);
    let sessions = db.list_sessions(limit, params.repo.as_deref())?;

    Ok(sessions.iter().map(session_to_info).collect())
}

/// Implementation of the get_context tool.
fn get_context_impl(params: GetContextParams) -> anyhow::Result<ContextResponse> {
    let db = Database::open_default()?;

    let working_dir = params.repo.unwrap_or_else(|| {
        std::env::current_dir()
            .map(|p| p.to_string_lossy().to_string())
            .unwrap_or_default()
    });

    let limit = if params.last.unwrap_or(false) { 1 } else { 5 };
    let sessions = db.list_sessions(limit, Some(&working_dir))?;

    let session_infos: Vec<SessionInfo> = sessions.iter().map(session_to_info).collect();

    // Get recent messages for --last mode
    let recent_messages = if params.last.unwrap_or(false) && !sessions.is_empty() {
        let messages = db.get_messages(&sessions[0].id)?;
        let start = messages.len().saturating_sub(3);
        Some(messages[start..].iter().map(message_to_info).collect())
    } else {
        None
    };

    Ok(ContextResponse {
        working_directory: working_dir,
        sessions: session_infos,
        recent_messages,
    })
}

/// Implementation of the get_linked_sessions tool.
fn get_linked_sessions_impl(
    params: GetLinkedSessionsParams,
) -> anyhow::Result<LinkedSessionsResponse> {
    let db = Database::open_default()?;

    let links = db.get_links_by_commit(&params.commit_sha)?;

    let mut sessions = Vec::new();
    for link in links {
        if let Some(session) = db.get_session(&link.session_id)? {
            sessions.push(session_to_info(&session));
        }
    }

    Ok(LinkedSessionsResponse {
        commit_sha: params.commit_sha,
        sessions,
    })
}

/// Resolves a session ID prefix to a full UUID.
fn resolve_session_id(db: &Database, id_prefix: &str) -> anyhow::Result<uuid::Uuid> {
    // Use the efficient database method that searches all sessions
    match db.find_session_by_id_prefix(id_prefix)? {
        Some(session) => Ok(session.id),
        None => anyhow::bail!("No session found with ID prefix: {id_prefix}"),
    }
}

/// Runs the MCP server on stdio transport.
///
/// This is a blocking call that processes MCP requests until the client
/// disconnects or an error occurs.
pub async fn run_server() -> Result<()> {
    let service = LoreServer::new().serve(stdio()).await?;
    service.waiting().await?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_parse_date_days() {
        let result = parse_date("7d").expect("Should parse 7d");
        let expected = chrono::Utc::now() - chrono::Duration::days(7);
        assert!((result - expected).num_seconds().abs() < 2);
    }

    #[test]
    fn test_parse_date_weeks() {
        let result = parse_date("2w").expect("Should parse 2w");
        let expected = chrono::Utc::now() - chrono::Duration::weeks(2);
        assert!((result - expected).num_seconds().abs() < 2);
    }

    #[test]
    fn test_parse_date_months() {
        let result = parse_date("1m").expect("Should parse 1m");
        let expected = chrono::Utc::now() - chrono::Duration::days(30);
        assert!((result - expected).num_seconds().abs() < 2);
    }

    #[test]
    fn test_parse_date_iso() {
        let result = parse_date("2024-01-15").expect("Should parse date");
        assert_eq!(result.format("%Y-%m-%d").to_string(), "2024-01-15");
    }

    #[test]
    fn test_parse_date_invalid() {
        assert!(parse_date("invalid").is_err());
        assert!(parse_date("abc123").is_err());
    }

    #[test]
    fn test_session_to_info() {
        use chrono::Utc;
        use uuid::Uuid;

        let session = Session {
            id: Uuid::new_v4(),
            tool: "claude-code".to_string(),
            tool_version: Some("2.0.0".to_string()),
            started_at: Utc::now(),
            ended_at: None,
            model: Some("claude-3-opus".to_string()),
            working_directory: "/home/user/project".to_string(),
            git_branch: Some("main".to_string()),
            source_path: None,
            message_count: 10,
            machine_id: None,
        };

        let info = session_to_info(&session);
        assert_eq!(info.tool, "claude-code");
        assert_eq!(info.message_count, 10);
        assert_eq!(info.working_directory, "/home/user/project");
        assert_eq!(info.git_branch, Some("main".to_string()));
        assert_eq!(info.id_short.len(), 8);
    }

    #[test]
    fn test_message_to_info() {
        use crate::storage::models::{MessageContent, MessageRole};
        use chrono::Utc;
        use uuid::Uuid;

        let message = Message {
            id: Uuid::new_v4(),
            session_id: Uuid::new_v4(),
            parent_id: None,
            index: 0,
            timestamp: Utc::now(),
            role: MessageRole::User,
            content: MessageContent::Text("Hello, world!".to_string()),
            model: None,
            git_branch: None,
            cwd: None,
        };

        let info = message_to_info(&message);
        assert_eq!(info.index, 0);
        assert_eq!(info.role, "user");
        assert_eq!(info.content, "Hello, world!");
    }
}