Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
73 commits
Select commit Hold shift + click to select a range
29484c5
fix: resolve module import paths for terraphim_tui repl-full feature
AlexMikhalev Oct 26, 2025
1869286
fix: apply clippy suggestions for modern Rust idioms
AlexMikhalev Oct 26, 2025
896e07f
fix: replace svelma components with standard Bulma HTML/CSS
AlexMikhalev Oct 26, 2025
6c82bdf
chore: remove all dead code and fix runtime panic in terraphim_tui
AlexMikhalev Oct 27, 2025
381a175
fix: restore TUI search and add suggestion navigation
AlexMikhalev Oct 27, 2025
31286c5
fix: add Ctrl modifiers to TUI keyboard shortcuts to enable text input
AlexMikhalev Oct 27, 2025
5dfc4d4
docs: add comprehensive command execution system documentation
AlexMikhalev Oct 27, 2025
2d27c06
fix: implement TuiService in REPL offline mode for real search/autoco…
AlexMikhalev Oct 27, 2025
3fc976d
fix: enable /role, /config, /graph commands in REPL offline mode
AlexMikhalev Oct 27, 2025
fe76bd8
feat: make REPL command list dynamic from markdown files
AlexMikhalev Oct 27, 2025
48f3dce
fix: resolve runtime panic in show_available_commands
AlexMikhalev Oct 27, 2025
18d8c19
fix: implement /thesaurus command for offline mode
AlexMikhalev Oct 27, 2025
0c42bd0
fix: implement /thesaurus and add comprehensive offline mode tests
AlexMikhalev Oct 27, 2025
7509411
feat: add conversation and context management to TuiService for RAG w…
AlexMikhalev Oct 28, 2025
d5681b3
docs: add RAG workflow progress tracker
AlexMikhalev Oct 28, 2025
7ab6abb
docs: add RAG workflow implementation status and next steps
AlexMikhalev Oct 28, 2025
23f3231
feat: add Context and Conversation command enums for RAG workflow
AlexMikhalev Oct 28, 2025
ff71956
feat: add session state to ReplHandler for RAG workflow
AlexMikhalev Oct 28, 2025
b0cf39d
docs: add detailed implementation guide for remaining RAG handlers
AlexMikhalev Oct 28, 2025
66e969e
feat: implement complete RAG workflow - Search → Select → Chat with p…
AlexMikhalev Oct 28, 2025
2bcdae6
fix: pre-build thesauri on startup to avoid persistence warnings
AlexMikhalev Oct 28, 2025
80b5f4c
docs: add comprehensive guide for RAG search-to-memory workflow
AlexMikhalev Oct 28, 2025
a1d0c6f
docs: add LLM configuration and end-to-end RAG demo guides
AlexMikhalev Oct 28, 2025
6633e64
feat: integrate real LLM client (OpenRouter/Ollama) for RAG chat
AlexMikhalev Oct 28, 2025
b135cf5
docs: document rust-genai integration and caching architecture
AlexMikhalev Oct 28, 2025
625d06b
test: add end-to-end RAG workflow test suite and proof
AlexMikhalev Oct 28, 2025
b3c86bb
style: apply cargo fmt formatting fixes
AlexMikhalev Oct 29, 2025
147d9c8
fix: add pragma comments for example API keys in documentation
AlexMikhalev Oct 29, 2025
365b463
feat: Add comprehensive code assistant requirements document
AlexMikhalev Oct 29, 2025
d0a6259
feat(automata): Add multi-strategy code editing with block anchor mat…
AlexMikhalev Oct 29, 2025
8445831
feat(mcp-server): add 6 file editing MCP tools with multi-strategy su…
AlexMikhalev Oct 29, 2025
1a8206b
feat(automata): add TypeScript type generation for edit functionality
AlexMikhalev Oct 29, 2025
e14066d
feat(mcp-server): add validation pipeline and knowledge-graph-based s…
AlexMikhalev Oct 29, 2025
ba82bc6
feat(multi-agent): add validated LLM client with 4-layer validation p…
AlexMikhalev Oct 29, 2025
4988ced
docs: add comprehensive test report and functional demos for Phase 1 & 2
AlexMikhalev Oct 29, 2025
cfeca46
feat(tui): integrate Phase 1 & 2 features into existing REPL
AlexMikhalev Oct 30, 2025
ef06c2f
feat(tui): add command parsing for REPL edit commands
AlexMikhalev Oct 30, 2025
d653b08
docs: update test report with Phase 3 completion
AlexMikhalev Oct 30, 2025
4a8a7f7
feat(types): add CodeSymbol types for Phase 4 knowledge graph extension
AlexMikhalev Oct 30, 2025
df06b97
feat(rolegraph): extend RoleGraph with CodeGraph for code symbol storage
AlexMikhalev Oct 30, 2025
9bfd919
feat(mcp-server): add git recovery and snapshot system for Phase 5
AlexMikhalev Oct 30, 2025
c76b03d
docs: add comprehensive session summary for Phases 1-5
AlexMikhalev Oct 30, 2025
4634331
test: add comprehensive Phase 6 integration tests and final report
AlexMikhalev Oct 30, 2025
3e96c3e
docs: add comprehensive test proof for entire implementation
AlexMikhalev Oct 30, 2025
ac52623
test: add executable end-to-end demonstration script
AlexMikhalev Oct 30, 2025
bd56053
test: add live LLM code generation test with Ollama
AlexMikhalev Oct 30, 2025
ef6b38c
fix: resolve pre-existing compilation errors with feature gates
AlexMikhalev Oct 30, 2025
2fd663f
fix: resolve 4 pre-existing test failures in terraphim_multi_agent
AlexMikhalev Oct 30, 2025
b82a1e1
feat(tui): add Ctrl-G external editor integration to REPL
AlexMikhalev Oct 31, 2025
201f5d0
docs: add final comprehensive proof with all test execution results
AlexMikhalev Oct 31, 2025
f65ddb2
Add terraphim_mcp_proxy crate for MCP server aggregation (Phase 1)
AlexMikhalev Nov 1, 2025
7d70521
Integrate MCP proxy with terraphim_config
AlexMikhalev Nov 1, 2025
2961a90
Add MCP namespace configuration examples
AlexMikhalev Nov 1, 2025
c1c2b06
Add MCP namespace integration to middleware
AlexMikhalev Nov 1, 2025
cdb5a35
feat: implement MCP endpoint management and authentication (Phase 2)
AlexMikhalev Nov 1, 2025
2555b20
feat: implement tool management, discovery, and middleware system (Ph…
AlexMikhalev Nov 1, 2025
6ce6d3a
Add Phase 4 MCP features: audit trail, namespace visibility, health e…
AlexMikhalev Nov 1, 2025
3d5a1c3
Add REST API wrapper for MCP tools execution
AlexMikhalev Nov 1, 2025
318f113
Add OpenAPI documentation for MCP tool endpoints
AlexMikhalev Nov 1, 2025
5bb0c80
fix: Add shared MCP persistence to AppState for data consistency
AlexMikhalev Nov 1, 2025
b667597
Implement TDD authentication middleware for MCP endpoints
AlexMikhalev Nov 1, 2025
35c9cfc
CRITICAL SECURITY FIX: Apply authentication to production MCP routes
AlexMikhalev Nov 2, 2025
233e732
fix: enhance LLM service with dynamic model override support
AlexMikhalev Nov 4, 2025
3f9d3f4
Fix clippy errors and pre-commit issues
AlexMikhalev Nov 5, 2025
cdf9d4d
Fix pre-commit compilation and linting errors
AlexMikhalev Nov 5, 2025
33da70e
Fix GitHub Actions workflow issues
AlexMikhalev Nov 8, 2025
437d581
Fix compilation errors: add missing mcp_namespaces field and feature …
AlexMikhalev Nov 8, 2025
0d3574f
Fix GitHub Actions workflow issues
AlexMikhalev Nov 8, 2025
9604264
Remove obsolete hook_system_tests.rs file
AlexMikhalev Nov 8, 2025
94ded86
fix: apply automatic clippy fixes and clean up unused imports
AlexMikhalev Nov 8, 2025
afb594b
feat: implement comprehensive MCP authentication system
AlexMikhalev Nov 8, 2025
637733f
fix: resolve clippy dead code warnings in tests
AlexMikhalev Nov 8, 2025
a14b394
feat: enhance MCP authentication and proxy integration
AlexMikhalev Nov 8, 2025
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
244 changes: 244 additions & 0 deletions .docs/summary-terraphim_persistence-src-mcp.rs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,244 @@
# Summary: crates/terraphim_persistence/src/mcp.rs

## Purpose
Implements persistence layer for MCP (Model Context Protocol) data using OpenDAL for multi-backend storage (Memory, File, S3, etc.). Provides async CRUD operations for namespaces, endpoints, API keys, tools, tool caching, and audit trails.

## Core Data Models

### McpNamespaceRecord
- **uuid**: Unique identifier
- **name**: Namespace display name
- **description**: Optional description
- **user_id**: Owner identifier
- **config_json**: MCP configuration as JSON string
- **created_at**: Creation timestamp
- **enabled**: Active/inactive status
- **visibility**: Public or Private (default: Private)

### McpEndpointRecord
- **uuid**: Unique identifier
- **name**: Endpoint display name
- **namespace_uuid**: Parent namespace reference
- **auth_type**: Authentication method (e.g., "bearer")
- **user_id**: Owner identifier
- **created_at**: Creation timestamp
- **enabled**: Active/inactive status

### McpApiKeyRecord
- **uuid**: Unique identifier
- **key_hash**: SHA256 hash of actual API key (never stores plaintext)
- **endpoint_uuid**: Associated endpoint
- **user_id**: Owner identifier
- **created_at**: Creation timestamp
- **expires_at**: Optional expiration timestamp
- **enabled**: Active/inactive status (can be disabled without deletion)

### McpToolRecord
- **uuid**: Unique identifier
- **namespace_uuid**: Parent namespace
- **server_name**: MCP server name (e.g., "filesystem")
- **tool_name**: Namespaced tool name (e.g., "filesystem__read_file")
- **original_name**: Original tool name from server
- **status**: Active or Inactive
- **override_name**: Optional custom display name
- **override_description**: Optional custom description
- **created_at / updated_at**: Timestamps

### ToolDiscoveryCache
- **namespace_uuid**: Namespace identifier
- **tools_json**: Cached tool list as JSON string
- **cached_at**: Cache creation time
- **expires_at**: Cache expiration time
- Purpose: Reduce repeated tool discovery API calls

### McpAuditRecord
- **uuid**: Unique identifier
- **user_id**: User who executed the action
- **endpoint_uuid**: Endpoint used
- **namespace_uuid**: Namespace context
- **tool_name**: Tool that was called
- **arguments**: Optional serialized arguments JSON
- **response**: Optional serialized response JSON
- **is_error**: Boolean flag for error responses
- **latency_ms**: Execution time in milliseconds
- **created_at**: Audit timestamp

## McpPersistence Trait

### Namespace Operations
- `save_namespace(&self, record) -> Result<()>`
- `get_namespace(&self, uuid) -> Result<Option<McpNamespaceRecord>>`
- `list_namespaces(&self, user_id) -> Result<Vec<McpNamespaceRecord>>`
- `list_namespaces_with_visibility(&self, user_id, include_public) -> Result<Vec<McpNamespaceRecord>>`
- `delete_namespace(&self, uuid) -> Result<()>`

### Endpoint Operations
- `save_endpoint(&self, record) -> Result<()>`
- `get_endpoint(&self, uuid) -> Result<Option<McpEndpointRecord>>`
- `list_endpoints(&self, user_id) -> Result<Vec<McpEndpointRecord>>`
- `delete_endpoint(&self, uuid) -> Result<()>`

### API Key Operations
- `save_api_key(&self, record) -> Result<()>`
- `get_api_key(&self, uuid) -> Result<Option<McpApiKeyRecord>>`
- **`verify_api_key(&self, key_hash) -> Result<Option<McpApiKeyRecord>>`** - Critical for authentication
- `list_api_keys(&self, user_id) -> Result<Vec<McpApiKeyRecord>>`
- `delete_api_key(&self, uuid) -> Result<()>`

### Tool Operations
- `save_tool(&self, record) -> Result<()>`
- `get_tool(&self, uuid) -> Result<Option<McpToolRecord>>`
- `list_tools(&self, namespace_uuid) -> Result<Vec<McpToolRecord>>`
- `update_tool_status(&self, uuid, status) -> Result<()>`
- `delete_tool(&self, uuid) -> Result<()>`

### Tool Cache Operations
- `save_tool_cache(&self, cache) -> Result<()>`
- `get_tool_cache(&self, namespace_uuid) -> Result<Option<ToolDiscoveryCache>>`
- `delete_tool_cache(&self, namespace_uuid) -> Result<()>`

### Audit Operations
- `save_audit(&self, record) -> Result<()>`
- `get_audit(&self, uuid) -> Result<Option<McpAuditRecord>>`
- `list_audits(&self, user_id, endpoint_uuid, limit) -> Result<Vec<McpAuditRecord>>`
- `delete_audit(&self, uuid) -> Result<()>`

## McpPersistenceImpl

### Storage Architecture
- **Backend**: OpenDAL Operator wrapped in `Arc<RwLock<Operator>>`
- **Path Structure**: Hierarchical JSON file organization
- `mcp/namespaces/{uuid}.json`
- `mcp/endpoints/{uuid}.json`
- `mcp/api_keys/{uuid}.json`
- `mcp/tools/{uuid}.json`
- `mcp/tool_cache/{namespace_uuid}.json`
- `mcp/audit/{uuid}.json`

### Key Implementation Details

#### verify_api_key (Authentication Critical)
```rust
async fn verify_api_key(&self, key_hash: &str) -> Result<Option<McpApiKeyRecord>> {
// Lists all API keys and searches for matching hash
// Validates enabled=true
// Checks expiration if expires_at is set
// Returns None if key not found, disabled, or expired
}
```
- **Performance Note**: Linear search through all keys (acceptable for small datasets)
- **Security**: Returns None for expired/disabled keys (no error indication)

#### list_audits with Sorting
```rust
async fn list_audits(...) -> Result<Vec<McpAuditRecord>> {
// Collects matching audits
// Sorts by created_at descending (newest first)
// Respects limit parameter
}
```

#### Namespace Visibility Filtering
```rust
async fn list_namespaces_with_visibility(&self, user_id, include_public) -> Result<...> {
// If include_public=true: returns user's namespaces + all public namespaces
// If include_public=false: returns only user's namespaces
// Enables multi-tenant public/private namespace sharing
}
```

### Thread Safety
- `Arc<RwLock<Operator>>` allows concurrent reads, exclusive writes
- All trait methods are `async` for non-blocking I/O
- Trait requires `Send + Sync` for multi-threaded usage

## Test Coverage (7 comprehensive tests)

1. **test_namespace_persistence** - CRUD operations for namespaces
2. **test_api_key_verification** - Authentication verification logic
3. **test_tool_management** - Tool CRUD and status updates
4. **test_tool_cache** - Cache save/retrieve/delete
5. **test_audit_trail** - Audit record management and filtering
6. **test_namespace_visibility** - Public/private namespace filtering

All tests use Memory backend for fast, isolated testing.

## Critical Design Decisions

### Why Arc<RwLock<Operator>>?
- **Arc**: Enables cloning for shared ownership across threads
- **RwLock**: Allows multiple concurrent readers, single writer
- **Operator**: OpenDAL's backend abstraction

### Why JSON Files?
- **Flexibility**: Works with any OpenDAL backend (Memory, FS, S3, Azure, etc.)
- **Human-Readable**: Easy debugging and inspection
- **Schema Evolution**: JSON allows adding fields without migration
- **Limitation**: No relational queries, linear search for some operations

### Why verify_api_key Scans All Keys?
- **Simplicity**: No secondary index needed
- **Performance Trade-off**: Acceptable for <1000 keys
- **Future Improvement**: Could add in-memory cache or use database backend

## Known Limitations

1. **No Pagination**: List operations return all matching records
2. **Linear Search**: API key verification O(n) complexity
3. **No Transactions**: Multi-step operations not atomic
4. **No Indexing**: Cannot efficiently query by fields other than UUID
5. **SQLite Incompatibility**: Hierarchical paths don't map to SQLite blob storage

## Backend Compatibility

### Tested Backends
- **Memory**: In-memory HashMap (tests, development)
- **File System**: Local directory storage (production)

### Theoretically Supported (via OpenDAL)
- AWS S3
- Azure Blob Storage
- Google Cloud Storage
- HTTP/WebDAV

### Known Issues
- **SQLite**: Blob storage model incompatible with hierarchical paths
- **RocksDB**: Previously caused locking issues (deprecated)

## File Location
`crates/terraphim_persistence/src/mcp.rs` (744 lines)

## Dependencies
- `async_trait`: Async trait definitions
- `chrono`: Timestamp handling
- `futures`: Stream utilities
- `serde`: JSON serialization
- `tokio::sync::RwLock`: Async read-write lock
- `opendal`: Multi-backend storage abstraction

## Related Files
- `terraphim_server/src/api_mcp.rs`: HTTP API handlers using this persistence
- `terraphim_server/src/mcp_auth.rs`: Authentication middleware calling verify_api_key
- `terraphim_server/src/lib.rs`: AppState with shared McpPersistenceImpl instance
- `terraphim_server/tests/mcp_auth_tests.rs`: Integration tests using this persistence

## Security Considerations
- **API Key Storage**: Only hashes stored, never plaintext
- **Expiration Enforcement**: Expired keys automatically rejected by verify_api_key
- **Enabled Status**: Allows disabling keys without deletion
- **Audit Trail**: Comprehensive logging for security monitoring
- **User Isolation**: Optional user_id filtering for multi-tenancy

## Performance Characteristics
- **Read Operations**: O(1) for get by UUID, O(n) for list/search
- **Write Operations**: O(1) for save/delete
- **verify_api_key**: O(n) linear search (could be optimized with cache)
- **list_audits**: O(n log n) due to sorting

## Future Enhancements
1. Add in-memory cache for API key verification
2. Implement pagination for list operations
3. Add secondary indexes for common queries
4. Support for database backends (PostgreSQL, MySQL)
5. Batch operations for bulk imports
6. Metrics and monitoring integration
149 changes: 149 additions & 0 deletions .docs/summary-terraphim_server-src-api_mcp.rs.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
# Summary: terraphim_server/src/api_mcp.rs

## Purpose
Implements HTTP API handlers for MCP (Model Context Protocol) management, providing CRUD operations for namespaces, endpoints, API keys, tools, and audit trails.

## API Structure

### Response Types
All responses follow consistent pattern with status, data, and error fields:
- `McpNamespaceResponse` / `McpNamespaceListResponse`
- `McpEndpointResponse` / `McpEndpointListResponse`
- `McpApiKeyResponse` - Includes plaintext `key_value` on creation (one-time only)
- `McpAuditListResponse` - Paginated audit records
- `McpHealthResponse` - System health with namespace/endpoint counts

### Request Types
- `CreateNamespaceRequest` - name, description, user_id, config_json, enabled, visibility
- `CreateEndpointRequest` - name, namespace_uuid, auth_type, user_id, enabled
- `CreateApiKeyRequest` - endpoint_uuid, user_id, expires_at, enabled

## API Endpoints

### Namespace Management
1. **list_namespaces** - `GET /metamcp/namespaces`
- Lists all namespaces, optionally filtered by user_id
- Returns: `McpNamespaceListResponse`

2. **get_namespace** - `GET /metamcp/namespaces/{uuid}`
- Retrieves single namespace by UUID
- Returns: `McpNamespaceResponse` with 404 handling

3. **create_namespace** - `POST /metamcp/namespaces`
- Creates new namespace with auto-generated UUID
- Sets `created_at` timestamp automatically
- Returns: Created namespace or error

4. **delete_namespace** - `DELETE /metamcp/namespaces/{uuid}`
- Removes namespace permanently
- Returns: `204 NO_CONTENT` or `500 INTERNAL_SERVER_ERROR`

### Endpoint Management
5. **list_endpoints** - `GET /metamcp/endpoints`
- Lists all endpoints, optionally filtered by user_id
- Returns: `McpEndpointListResponse`

6. **get_endpoint** - `GET /metamcp/endpoints/{uuid}`
- Retrieves single endpoint by UUID
- Returns: `McpEndpointResponse` with 404 handling

7. **create_endpoint** - `POST /metamcp/endpoints`
- Creates new MCP endpoint with auto-generated UUID
- Sets `created_at` timestamp automatically
- Returns: Created endpoint or error

8. **delete_endpoint** - `DELETE /metamcp/endpoints/{uuid}`
- Removes endpoint permanently
- Returns: `204 NO_CONTENT` or `500 INTERNAL_SERVER_ERROR`

### API Key Management
9. **create_api_key** - `POST /metamcp/api_keys`
- Generates API key with format: `tpai_{uuid_without_hyphens}`
- Hashes key using SHA256 before storage (only hash persisted)
- Returns: API key record AND plaintext key_value (one-time retrieval)
- Security: Key value never stored, only hash

### Audit Trail
10. **list_audits** - `GET /metamcp/audits`
- Lists up to 100 most recent audit records
- Optionally filtered by user_id or endpoint_uuid
- Sorted by created_at descending
- Returns: Audit records with total count

### Health Check
11. **get_mcp_health** - `GET /metamcp/health`
- Returns system version, timestamp, namespace/endpoint counts
- Non-blocking health check for monitoring
- Returns: `McpHealthResponse`

## Key Design Patterns

### Shared State Access
All handlers use `State(app_state): State<AppState>` extraction:
```rust
let persistence = app_state.mcp_persistence.clone();
```
- Uses `Arc<McpPersistenceImpl>` for thread-safe shared access
- Critical for authentication middleware compatibility

### UUID Generation
Auto-generates UUIDs for all resources:
```rust
uuid: uuid::Uuid::new_v4().to_string()
```

### Timestamp Management
Automatically sets `created_at` using `chrono::Utc::now()`:
```rust
created_at: chrono::Utc::now()
```

### Error Handling Strategy
- **Graceful Degradation**: Most endpoints return `Status::Error` in response body
- **HTTP Status Codes**: DELETE operations use proper status codes (204, 500)
- **Logging**: Errors logged before returning to client
- **User-Friendly Messages**: Generic error messages to avoid leaking internals

### API Key Security
Private `hash_api_key()` function in this module:
```rust
fn hash_api_key(key: &str) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(key.as_bytes());
format!("{:x}", hasher.finalize())
}
```
Note: Duplicates logic from `mcp_auth.rs` (could be refactored to shared module)

## Authentication Integration
All endpoints (except health) protected by `validate_api_key` middleware via:
```rust
.route_layer(middleware::from_fn_with_state(app_state, mcp_auth::validate_api_key))
```

## File Location
`terraphim_server/src/api_mcp.rs` (372 lines)

## Dependencies
- `axum`: HTTP framework, routing, JSON extraction/responses
- `chrono`: Timestamp management
- `serde`: Serialization/deserialization
- `sha2`: API key hashing
- `uuid`: UUID generation
- `terraphim_persistence::mcp`: Persistence trait and record types

## Related Files
- `terraphim_server/src/mcp_auth.rs`: Authentication middleware
- `terraphim_server/src/api_mcp_tools.rs`: Tool execution endpoints
- `terraphim_server/src/api_mcp_openapi.rs`: OpenAPI spec generation
- `terraphim_persistence/src/mcp.rs`: Persistence layer implementation
- `terraphim_server/src/lib.rs`: Router configuration

## Potential Improvements
1. **Deduplicate hash_api_key**: Share implementation with `mcp_auth.rs`
2. **Pagination**: Add pagination for list endpoints (currently unbounded)
3. **Batch Operations**: Support bulk create/delete for efficiency
4. **Rate Limiting**: Add per-user rate limits for creation endpoints
5. **Validation**: Add input validation (e.g., name length, config JSON schema)
6. **CORS**: Configure CORS headers for browser clients
Loading