do_memory_mcp/lib.rs
1#![allow(clippy::useless_attribute)]
2#![allow(clippy::excessive_nesting)]
3#![allow(clippy::missing_errors_doc)]
4#![allow(clippy::ifs_same_cond)]
5
6//! # Memory MCP (Model Context Protocol) Integration
7//!
8//! This crate provides MCP server integration for the self-learning memory system,
9//! enabling secure code execution and memory queries through standardized tool interfaces.
10//!
11//! ## Features
12//!
13//! - **MCP Server**: Standard MCP server implementation with tool definitions
14//! - **Secure Sandbox**: TypeScript/JavaScript code execution with comprehensive security
15//! - **Memory Integration**: Query episodic memory and analyze patterns
16//! - **Progressive Disclosure**: Tools are prioritized based on usage patterns
17//! - **Execution Monitoring**: Detailed statistics and logging
18//!
19//! ## Security
20//!
21//! The sandbox implements defense-in-depth security:
22//!
23//! 1. **Input Validation**: All code is scanned for malicious patterns
24//! 2. **Process Isolation**: Code runs in separate Node.js processes
25//! 3. **Resource Limits**: CPU and memory usage are constrained
26//! 4. **Timeout Enforcement**: Long-running code is terminated
27//! 5. **Access Controls**: Network and filesystem access denied by default
28//! 6. **Malicious Code Detection**: Common attack patterns are blocked
29//!
30//! ## Example
31//!
32//! ```no_run
33//! use do_memory_core::SelfLearningMemory;
34//! use do_memory_mcp::server::MemoryMCPServer;
35//! use do_memory_mcp::types::{SandboxConfig, ExecutionContext};
36//! use serde_json::json;
37//! use std::sync::Arc;
38//!
39//! #[tokio::main]
40//! async fn main() -> anyhow::Result<()> {
41//! // Create memory and server with restrictive sandbox
42//! let memory = Arc::new(SelfLearningMemory::new());
43//! let server = MemoryMCPServer::new(SandboxConfig::restrictive(), memory).await?;
44//!
45//! // List available tools
46//! let tools = server.list_tools().await;
47//! for tool in tools {
48//! println!("Tool: {} - {}", tool.name, tool.description);
49//! }
50//!
51//! // Execute code securely
52//! let code = r#"
53//! const result = {
54//! sum: 1 + 1,
55//! message: "Hello from sandbox"
56//! };
57//! return result;
58//! "#;
59//!
60//! let context = ExecutionContext::new(
61//! "Calculate sum".to_string(),
62//! json!({"a": 1, "b": 1}),
63//! );
64//!
65//! let result = server.execute_agent_code(code.to_string(), context).await?;
66//! println!("Result: {:?}", result);
67//!
68//! // Get execution statistics
69//! let stats = server.get_stats().await;
70//! println!(
71//! "Executed {} times, success rate: {:.1}%",
72//! stats.total_executions,
73//! stats.success_rate()
74//! );
75//!
76//! Ok(())
77//! }
78//! ```
79//!
80//! ## Architecture
81//!
82//! ```text
83//! ┌─────────────────────────────────────────────────────────┐
84//! │ MCP Server │
85//! │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
86//! │ │ Query Memory │ │Execute Code │ │Analyze │ │
87//! │ │ │ │ │ │Patterns │ │
88//! │ └──────────────┘ └──────────────┘ └──────────────┘ │
89//! └───────────────────────┬─────────────────────────────────┘
90//! │
91//! ┌──────────────┴──────────────┐
92//! ▼ ▼
93//! ┌─────────────────┐ ┌──────────────────┐
94//! │ Code Sandbox │ │ Memory System │
95//! │ - Validation │ │ - Episodes │
96//! │ - Isolation │ │ - Patterns │
97//! │ - Timeout │ │ - Heuristics │
98//! │ - Limits │ │ │
99//! └─────────────────┘ └──────────────────┘
100//! ```
101
102pub mod batch;
103pub mod cache;
104pub mod error;
105#[cfg(feature = "javy-backend")]
106pub mod javy_compiler;
107pub mod jsonrpc;
108pub mod mcp;
109pub mod monitoring;
110pub mod patterns;
111pub mod protocol;
112pub mod sandbox;
113pub mod server;
114pub mod types;
115#[cfg(feature = "wasmtime-backend")]
116pub mod unified_sandbox;
117#[cfg(feature = "wasm-rquickjs")]
118pub mod wasm_sandbox;
119#[cfg(feature = "wasmtime-backend")]
120pub mod wasmtime_sandbox;
121
122// Re-export commonly used types
123pub use batch::{
124 BatchExecutor, BatchMode, BatchOperation, BatchRequest, BatchResponse, BatchStats,
125 DependencyGraph, OperationError, OperationResult,
126};
127pub use cache::{CacheConfig, CacheStats, QueryCache};
128pub use error::{Error, Result};
129pub use sandbox::CodeSandbox;
130pub use server::MemoryMCPServer;
131pub use server::audit::{AuditConfig, AuditDestination, AuditLogEntry, AuditLogLevel, AuditLogger};
132pub use types::{
133 ErrorType, ExecutionContext, ExecutionResult, ExecutionStats, ResourceLimits, SandboxConfig,
134 SecurityViolationType, Tool,
135};
136
137// Re-export security modules
138pub use sandbox::{FileSystemRestrictions, IsolationConfig, NetworkRestrictions};
139
140// Re-export new WASM modules
141#[cfg(feature = "javy-backend")]
142pub use javy_compiler::{JavyCompiler, JavyConfig, JavyMetrics};
143#[cfg(feature = "wasmtime-backend")]
144pub use unified_sandbox::{BackendHealth, SandboxBackend, UnifiedMetrics, UnifiedSandbox};
145#[cfg(feature = "wasm-rquickjs")]
146pub use wasm_sandbox::{WasmConfig, WasmMetrics, WasmSandbox};
147#[cfg(feature = "wasmtime-backend")]
148pub use wasmtime_sandbox::{WasmtimeConfig, WasmtimeMetrics, WasmtimeSandbox};