post-cortex-mcp 0.3.1

Model Context Protocol (MCP) tool definitions for post-cortex. Pure library — embed in rmcp, custom MCP servers, or anywhere else; no rmcp / axum / tonic transport dependencies.
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
//! Session lifecycle: create, load, checkpoint, list, search, and metadata.

use crate::{MCPToolResult, get_memory_system, string_to_anyhow};
use anyhow::Result;
use arc_swap::ArcSwap;
use post_cortex_core::core::timeout_utils::with_storage_timeout;
use post_cortex_core::session::active_session::ActiveSession;
use post_cortex_memory::ConversationMemorySystem;
use post_cortex_storage::rocksdb_storage::SessionCheckpoint;
use std::sync::Arc;
use tracing::{error, info, instrument};
use uuid::Uuid;

/// Create a session checkpoint using an explicit memory system reference.
pub async fn create_session_checkpoint_with_system(
    session_id: Uuid,
    system: &ConversationMemorySystem,
) -> Result<MCPToolResult> {
    let session_arc = system
        .get_session(session_id)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to load session: {}", e))?;
    let session = session_arc.load();

    let checkpoint = create_comprehensive_checkpoint(&session).await?;

    system
        .storage_actor
        .save_checkpoint(&checkpoint)
        .await
        .map_err(string_to_anyhow)?;

    Ok(MCPToolResult::success(
        "Checkpoint created successfully".to_string(),
        Some(serde_json::json!({ "checkpoint_id": checkpoint.id.to_string() })),
    ))
}

/// Load a session from a previously saved checkpoint.
pub async fn load_session_checkpoint_with_system(
    checkpoint_id: String,
    session_id: Uuid,
    system: &ConversationMemorySystem,
) -> Result<MCPToolResult> {
    eprintln!("Loading checkpoint - step 1: Parsing checkpoint ID");
    let checkpoint_id = Uuid::parse_str(&checkpoint_id)?;

    eprintln!("Loading checkpoint - step 2: Loading checkpoint from storage");
    let checkpoint = system
        .storage_actor
        .load_checkpoint(checkpoint_id)
        .await
        .map_err(string_to_anyhow)?;

    eprintln!("Loading checkpoint - step 3: Checkpoint loaded successfully");

    eprintln!("Loading checkpoint - step 4: Creating session from checkpoint");
    let mut session = ActiveSession::new(session_id, None, None);

    eprintln!("Loading checkpoint - step 5: Restoring current state");
    session.current_state = Arc::new(checkpoint.structured_context);

    eprintln!("Loading checkpoint - step 6: Restoring incremental updates");
    session.incremental_updates = Arc::new(checkpoint.recent_updates);

    eprintln!("Loading checkpoint - step 10: Restoring code references");
    session.code_references = Arc::new(checkpoint.code_references);

    eprintln!("Loading checkpoint - step 11: Restoring change history");
    session.change_history = Arc::new(checkpoint.change_history);

    eprintln!("Loading checkpoint - step 12: Entity graph restored");

    eprintln!("Loading checkpoint - step 13: Adding session to session manager");
    system
        .session_manager
        .sessions
        .put(session_id, Arc::new(ArcSwap::new(Arc::new(session))));

    eprintln!("Loading checkpoint - step 14: Updated session manager");

    Ok(MCPToolResult::success(
        "Session loaded from checkpoint successfully".to_string(),
        None,
    ))
}

/// Create a session checkpoint using the global memory system.
pub async fn create_session_checkpoint(session_id: Uuid) -> Result<MCPToolResult> {
    let result = with_storage_timeout(async {
        let system = get_memory_system().await?;
        let session_arc = system
            .get_session(session_id)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to load session: {}", e))?;
        let session = session_arc.load();

        let checkpoint = create_comprehensive_checkpoint(&session).await?;

        system
            .storage_actor
            .save_checkpoint(&checkpoint)
            .await
            .map_err(string_to_anyhow)?;

        Ok(MCPToolResult::success(
            "Checkpoint created successfully".to_string(),
            Some(serde_json::json!({ "checkpoint_id": checkpoint.id.to_string() })),
        ))
    })
    .await;

    match result {
        Ok(success_result) => success_result,
        Err(timeout_error) => {
            error!(
                "TIMEOUT: create_session_checkpoint - session: {}, error: {}",
                session_id, timeout_error
            );
            Ok(MCPToolResult::error(format!(
                "Checkpoint creation timed out: {}",
                timeout_error
            )))
        }
    }
}

/// Load a session checkpoint using the global memory system.
pub async fn load_session_checkpoint(
    checkpoint_id: String,
    session_id: Uuid,
) -> Result<MCPToolResult> {
    let result = with_storage_timeout(async {
        let system = get_memory_system().await?;
        let checkpoint_id = Uuid::parse_str(&checkpoint_id)?;

        let checkpoint = system
            .storage_actor
            .load_checkpoint(checkpoint_id)
            .await
            .map_err(string_to_anyhow)?;

        let mut session = ActiveSession::new(session_id, None, None);
        session.current_state = Arc::new(checkpoint.structured_context);
        session.incremental_updates = Arc::new(checkpoint.recent_updates);
        session.code_references = Arc::new(checkpoint.code_references);
        session.change_history = Arc::new(checkpoint.change_history);

        system
            .session_manager
            .sessions
            .put(session_id, Arc::new(ArcSwap::new(Arc::new(session))));

        Ok(MCPToolResult::success(
            "Session loaded from checkpoint successfully".to_string(),
            None,
        ))
    })
    .await;

    match result {
        Ok(success_result) => success_result,
        Err(timeout_error) => {
            error!(
                "TIMEOUT: load_session_checkpoint - session: {}, error: {}",
                session_id, timeout_error
            );
            Ok(MCPToolResult::error(format!(
                "Checkpoint loading timed out: {}",
                timeout_error
            )))
        }
    }
}

/// Mark a specific context update as important within a session.
pub async fn mark_important(session_id: Uuid, update_id: String) -> Result<MCPToolResult> {
    let update_id = Uuid::parse_str(&update_id)?;
    let system = get_memory_system().await?;
    let session_arc = system
        .get_session(session_id)
        .await
        .map_err(|e| anyhow::anyhow!("Failed to load session: {}", e))?;

    let mut found = false;
    session_arc.rcu(|current| {
        let mut updated = (**current).clone();
        let updates = Arc::make_mut(&mut updated.incremental_updates);
        for update in updates.iter_mut() {
            if update.id == update_id {
                update.user_marked_important = true;
                found = true;
                break;
            }
        }
        Arc::new(updated)
    });

    if found {
        Ok(MCPToolResult::success(
            "Update marked as important".to_string(),
            None,
        ))
    } else {
        Ok(MCPToolResult::error("Update not found".to_string()))
    }
}

/// List all persisted sessions using a direct storage reference.
pub async fn list_sessions_with_storage(
    storage: &post_cortex_storage::rocksdb_storage::RealRocksDBStorage,
) -> Result<MCPToolResult> {
    match storage.list_sessions().await {
        Ok(session_ids) => {
            let mut sessions_info = Vec::new();

            for session_id in session_ids {
                match storage.load_session(session_id).await {
                    Ok(session) => {
                        sessions_info.push(serde_json::json!({
                            "id": session_id.to_string(),
                            "name": session.name(),
                            "description": session.description(),
                            "created_at": session.created_at().to_rfc3339(),
                            "last_updated": session.last_updated.to_rfc3339(),
                            "update_count": session.incremental_updates.len(),
                            "entity_count": session.entity_graph.entities.len()
                        }));
                    }
                    Err(_) => {
                        sessions_info.push(serde_json::json!({
                            "id": session_id.to_string(),
                            "name": null,
                            "description": null,
                            "created_at": "unknown",
                            "last_updated": "unknown",
                            "update_count": 0,
                            "entity_count": 0
                        }));
                    }
                }
            }
            Ok(MCPToolResult::success(
                format!("Found {} sessions", sessions_info.len()),
                Some(serde_json::json!({
                    "sessions": sessions_info
                })),
            ))
        }
        Err(e) => Ok(MCPToolResult::error(format!(
            "Failed to load sessions: {e}"
        ))),
    }
}

/// List all sessions via the global memory system.
pub async fn list_sessions() -> Result<MCPToolResult> {
    info!("MCP-TOOLS: list_sessions() called");
    let result = with_storage_timeout(async {
        info!("MCP-TOOLS: Getting memory system for list_sessions");
        let system = get_memory_system().await?;
        info!("MCP-TOOLS: Got memory system, listing sessions");
        let session_ids = system.list_sessions().await.map_err(string_to_anyhow)?;

        let mut sessions_info = Vec::new();
        for session_id in session_ids {
            match system.get_session(session_id).await {
                Ok(session_arc) => {
                    let session = session_arc.load();
                    sessions_info.push(serde_json::json!({
                        "id": session_id.to_string(),
                        "name": session.name(),
                        "description": session.description(),
                        "created_at": session.created_at().to_rfc3339(),
                        "last_updated": session.last_updated.to_rfc3339(),
                        "update_count": session.incremental_updates.len(),
                        "entity_count": session.entity_graph.entities.len()
                    }));
                }
                Err(_) => {
                    sessions_info.push(serde_json::json!({
                        "id": session_id.to_string(),
                        "name": null,
                        "description": null,
                        "created_at": "unknown",
                        "last_updated": "unknown",
                        "update_count": 0,
                        "entity_count": 0
                    }));
                }
            }
        }

        Ok(MCPToolResult::success(
            format!("Found {} sessions", sessions_info.len()),
            Some(serde_json::json!({
                "sessions": sessions_info
            })),
        ))
    })
    .await;

    match result {
        Ok(success_result) => success_result,
        Err(timeout_error) => {
            error!("TIMEOUT: list_sessions - error: {timeout_error}");
            Ok(MCPToolResult::error(format!(
                "Session listing timed out: {timeout_error}"
            )))
        }
    }
}

/// Load a session by ID using an explicit memory system reference.
pub async fn load_session_with_system(
    session_id: Uuid,
    system: &ConversationMemorySystem,
) -> Result<MCPToolResult> {
    match system.get_session(session_id).await {
        Ok(session_arc) => {
            let session = session_arc.load();
            Ok(MCPToolResult::success(
                "Session loaded successfully".to_string(),
                Some(serde_json::json!({
                    "session": {
                        "id": session.id().to_string(),
                        "created_at": session.created_at().to_rfc3339(),
                        "last_updated": session.last_updated.to_rfc3339(),
                        "update_count": session.incremental_updates.len(),
                        "entity_count": session.entity_graph.entities.len(),
                        "hot_context_size": session.hot_context.len(),
                        "warm_context_size": session.warm_context.len(),
                        "cold_context_size": session.cold_context.len(),
                        "code_references": session.code_references.keys().collect::<Vec<_>>(),
                        "change_history_count": session.change_history.len()
                    }
                })),
            ))
        }
        Err(e) => Ok(MCPToolResult::error(
            format!("Failed to load session: {e}",),
        )),
    }
}

/// Load a session by ID via the global memory system.
pub async fn load_session(session_id: Uuid) -> Result<MCPToolResult> {
    let result = with_storage_timeout(async {
        let system = get_memory_system().await?;
        load_session_with_system(session_id, &system).await
    })
    .await;

    match result {
        Ok(success_result) => success_result,
        Err(timeout_error) => {
            error!(
                "TIMEOUT: load_session - session: {}, error: {}",
                session_id, timeout_error
            );
            Ok(MCPToolResult::error(format!(
                "Session loading timed out: {}",
                timeout_error
            )))
        }
    }
}

/// Search sessions by name or description.
pub async fn search_sessions(query: String) -> Result<MCPToolResult> {
    let result = with_storage_timeout(async {
        let system = get_memory_system().await?;
        let session_ids = system
            .find_sessions_by_name_or_description(&query)
            .await
            .map_err(string_to_anyhow)?;

        let mut sessions = Vec::new();
        for session_id in session_ids {
            if let Ok(session_arc) = system.get_session(session_id).await {
                let session = session_arc.load();
                sessions.push(serde_json::json!({
                    "id": session_id.to_string(),
                    "name": session.name(),
                    "description": session.description()
                }));
            }
        }

        Ok(MCPToolResult::success(
            format!("Found {} sessions matching '{}'", sessions.len(), query),
            Some(serde_json::json!({
                "sessions": sessions
            })),
        ))
    })
    .await;

    match result {
        Ok(success_result) => success_result,
        Err(timeout_error) => {
            error!(
                "TIMEOUT: search_sessions - query: {}, error: {}",
                query, timeout_error
            );
            Ok(MCPToolResult::error(format!(
                "Session search timed out: {}",
                timeout_error
            )))
        }
    }
}

/// Update the name and/or description of a session.
#[instrument(skip(session_id), fields(session_id = %session_id))]
pub async fn update_session_metadata(
    session_id: Uuid,
    name: Option<String>,
    description: Option<String>,
) -> Result<MCPToolResult> {
    let result = with_storage_timeout(async {
        let system = get_memory_system().await?;
        system
            .update_session_metadata(session_id, name, description)
            .await
            .map_err(string_to_anyhow)?;

        let session_arc = system
            .get_session(session_id)
            .await
            .map_err(|e| anyhow::anyhow!("Failed to load session: {}", e))?;
        let session = session_arc.load();
        let (final_name, final_description) = session.get_metadata();

        Ok(MCPToolResult::success(
            "Session metadata updated successfully".to_string(),
            Some(serde_json::json!({
                "session_id": session_id.to_string(),
                "name": final_name,
                "description": final_description
            })),
        ))
    })
    .await;

    match result {
        Ok(success_result) => success_result,
        Err(timeout_error) => {
            error!(
                "TIMEOUT: update_session_metadata - session_id: {}, error: {}",
                session_id, timeout_error
            );
            Ok(MCPToolResult::error(format!(
                "TIMEOUT: Failed to update session metadata: {}",
                timeout_error
            )))
        }
    }
}

/// Build a comprehensive checkpoint snapshot from an active session.
async fn create_comprehensive_checkpoint(session: &ActiveSession) -> Result<SessionCheckpoint> {
    Ok(SessionCheckpoint {
        id: Uuid::new_v4(),
        session_id: session.id(),
        created_at: chrono::Utc::now(),
        structured_context: (*session.current_state).clone(),
        recent_updates: (*session.incremental_updates).clone(),
        code_references: (*session.code_references).clone(),
        change_history: (*session.change_history).clone(),
        total_updates: session.incremental_updates.len(),
        context_quality_score: 1.0,
        compression_ratio: 1.0,
    })
}