icarus 0.5.8

Build MCP (Model Context Protocol) servers that run as Internet Computer canisters
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
# Stable Storage Patterns

Guide to using stable storage effectively in Icarus MCP servers.

## Overview

Stable storage is the key to persistent MCP servers on ICP. Data stored in stable memory:
- Survives canister upgrades
- Persists indefinitely
- Provides up to 64GB of storage
- Offers zero-copy access for efficiency

## Basic Concepts

### Memory Management

The Internet Computer provides 64GB of stable memory per canister. Icarus SDK manages this memory through virtual memory pages:

```rust
use ic_stable_structures::memory_manager::{MemoryManager, MemoryId};
use ic_stable_structures::{DefaultMemoryImpl, StableBTreeMap};

type Memory = VirtualMemory<DefaultMemoryImpl>;
```

### Storage Types

#### StableBTreeMap
Best for key-value storage with efficient lookups.

```rust
stable_storage! {
    USERS: StableBTreeMap<String, User, Memory> = memory_id!(0);
}

// Usage
USERS.with(|users| {
    users.borrow_mut().insert("user123".to_string(), user);
});
```

#### StableVec
Best for append-only data like logs or events.

```rust
stable_storage! {
    LOGS: StableVec<LogEntry, Memory> = memory_id!(1);
}

// Usage
LOGS.with(|logs| {
    logs.borrow_mut().push(&log_entry).unwrap();
});
```

#### StableCell
Best for single values like configuration.

```rust
stable_storage! {
    CONFIG: StableCell<AppConfig, Memory> = memory_id!(2);
}

// Usage
CONFIG.with(|config| {
    config.borrow_mut().set(new_config).unwrap();
});
```

## Common Patterns

### Pattern 1: User Data Storage

```rust
#[derive(Debug, Clone, Serialize, Deserialize, CandidType, IcarusStorable)]
pub struct User {
    pub id: String,
    pub username: String,
    pub email: String,
    pub created_at: u64,
    pub metadata: HashMap<String, String>,
}

stable_storage! {
    USERS: StableBTreeMap<String, User, Memory> = memory_id!(0);
    USER_COUNT: u64 = 0;
}

#[icarus_module]
mod user_tools {
    #[update]
    #[icarus_tool("Create a new user")]
    pub fn create_user(username: String, email: String) -> Result<String, String> {
        // Validate inputs
        if username.is_empty() || email.is_empty() {
            return Err("Username and email are required".to_string());
        }
        
        // Generate ID
        let id = USER_COUNT.with(|count| {
            let current = *count.borrow();
            *count.borrow_mut() = current + 1;
            format!("user_{}", current + 1)
        });
        
        let user = User {
            id: id.clone(),
            username,
            email,
            created_at: ic_cdk::api::time(),
            metadata: HashMap::new(),
        };
        
        USERS.with(|users| {
            users.borrow_mut().insert(id.clone(), user);
        });
        
        Ok(id)
    }
}
```

### Pattern 2: Event Logging

```rust
#[derive(Debug, Clone, Serialize, Deserialize, CandidType, IcarusStorable)]
pub struct Event {
    pub id: u64,
    pub timestamp: u64,
    pub event_type: String,
    pub data: serde_json::Value,
}

stable_storage! {
    EVENTS: StableVec<Event, Memory> = memory_id!(0);
    EVENT_COUNTER: u64 = 0;
}

#[icarus_module]
mod event_tools {
    #[update]
    #[icarus_tool("Log an event")]
    pub fn log_event(event_type: String, data: serde_json::Value) -> Result<u64, String> {
        let id = EVENT_COUNTER.with(|counter| {
            let current = *counter.borrow();
            *counter.borrow_mut() = current + 1;
            current + 1
        });
        
        let event = Event {
            id,
            timestamp: ic_cdk::api::time(),
            event_type,
            data,
        };
        
        EVENTS.with(|events| {
            events.borrow_mut().push(&event)
                .map_err(|_| "Failed to store event".to_string())?;
            Ok(id)
        })
    }
    
    #[query]
    #[icarus_tool("Get recent events")]
    pub fn get_recent_events(limit: Option<usize>) -> Vec<Event> {
        let limit = limit.unwrap_or(10);
        
        EVENTS.with(|events| {
            let events = events.borrow();
            let total = events.len();
            let start = total.saturating_sub(limit);
            
            (start..total)
                .filter_map(|i| events.get(i))
                .collect()
        })
    }
}
```

### Pattern 3: Configuration Management

```rust
#[derive(Debug, Clone, Serialize, Deserialize, CandidType, IcarusStorable)]
pub struct Config {
    pub app_name: String,
    pub version: String,
    pub features: HashMap<String, bool>,
    pub limits: HashMap<String, u64>,
}

stable_storage! {
    CONFIG: StableCell<Config, Memory> = memory_id!(0);
}

#[icarus_module]
mod config_tools {
    #[update]
    #[icarus_tool("Update configuration")]
    pub fn update_config(updates: ConfigUpdate) -> Result<(), String> {
        CONFIG.with(|config| {
            let mut current = config.borrow().get().clone();
            
            if let Some(name) = updates.app_name {
                current.app_name = name;
            }
            
            if let Some(features) = updates.features {
                current.features.extend(features);
            }
            
            if let Some(limits) = updates.limits {
                current.limits.extend(limits);
            }
            
            config.borrow_mut().set(current)
                .map_err(|_| "Failed to update config".to_string())
        })
    }
}
```

### Pattern 4: Indexed Data

```rust
stable_storage! {
    DOCUMENTS: StableBTreeMap<String, Document, Memory> = memory_id!(0);
    TAGS_INDEX: StableBTreeMap<String, Vec<String>, Memory> = memory_id!(1);
    AUTHOR_INDEX: StableBTreeMap<Principal, Vec<String>, Memory> = memory_id!(2);
}

#[icarus_module]
mod document_tools {
    #[update]
    #[icarus_tool("Create document with indexing")]
    pub fn create_document(
        title: String,
        content: String,
        tags: Vec<String>
    ) -> Result<String, String> {
        let author = ic_cdk::caller();
        let id = generate_id();
        
        let doc = Document {
            id: id.clone(),
            title,
            content,
            author,
            tags: tags.clone(),
            created_at: ic_cdk::api::time(),
        };
        
        // Store document
        DOCUMENTS.with(|docs| {
            docs.borrow_mut().insert(id.clone(), doc);
        });
        
        // Update tag index
        for tag in tags {
            TAGS_INDEX.with(|index| {
                let mut index = index.borrow_mut();
                let mut doc_ids = index.get(&tag).unwrap_or_default();
                doc_ids.push(id.clone());
                index.insert(tag, doc_ids);
            });
        }
        
        // Update author index
        AUTHOR_INDEX.with(|index| {
            let mut index = index.borrow_mut();
            let mut doc_ids = index.get(&author).unwrap_or_default();
            doc_ids.push(id.clone());
            index.insert(author, doc_ids);
        });
        
        Ok(id)
    }
}
```

## Advanced Patterns

### Memory-Efficient Large Data

For large data that doesn't need frequent access:

```rust
#[derive(IcarusStorable)]
#[icarus_storable(unbounded)]
pub struct LargeData {
    pub chunks: Vec<Vec<u8>>,
    pub metadata: DataMetadata,
}

stable_storage! {
    LARGE_DATA: StableBTreeMap<String, LargeData, Memory> = memory_id!(0);
}
```

### Versioned Storage

For data that needs migration support:

```rust
#[derive(Debug, Clone, Serialize, Deserialize, CandidType)]
pub enum StoredData {
    V1(DataV1),
    V2(DataV2),
}

impl IcarusStorable for StoredData {
    // Custom implementation for versioning
}
```

### Transactional Updates

Ensure consistency with multiple updates:

```rust
#[update]
#[icarus_tool("Transfer ownership atomically")]
pub fn transfer_ownership(
    item_id: String,
    from: Principal,
    to: Principal
) -> Result<(), String> {
    // Read current state
    let item = ITEMS.with(|items| {
        items.borrow().get(&item_id)
    }).ok_or("Item not found")?;
    
    if item.owner != from {
        return Err("Not the owner".to_string());
    }
    
    // Prepare updates
    let mut updated_item = item.clone();
    updated_item.owner = to;
    
    // Apply all changes atomically
    ITEMS.with(|items| {
        items.borrow_mut().insert(item_id, updated_item);
    });
    
    // Update indices
    update_ownership_index(from, to, item_id)?;
    
    Ok(())
}
```

## Best Practices

### 1. Memory Planning

Plan your memory usage upfront:
```rust
// Reserve memory IDs logically
const USER_DATA: MemoryId = MemoryId::new(0);
const USER_INDEX: MemoryId = MemoryId::new(1);
const TEMP_DATA: MemoryId = MemoryId::new(10);
const LOGS: MemoryId = MemoryId::new(20);
```

### 2. Key Design

Use efficient key structures:
```rust
// Good: Compact, sortable keys
format!("user:{}:{}", timestamp, user_id)

// Bad: Long, unstructured keys
format!("user_data_for_{}_created_at_{}", user_name, date_string)
```

### 3. Batch Operations

Minimize storage access:
```rust
#[update]
#[icarus_tool("Batch update users")]
pub fn batch_update(updates: Vec<UserUpdate>) -> Result<(), String> {
    USERS.with(|users| {
        let mut users = users.borrow_mut();
        for update in updates {
            if let Some(mut user) = users.get(&update.id) {
                apply_update(&mut user, update);
                users.insert(update.id, user);
            }
        }
        Ok(())
    })
}
```

### 4. Size Management

Monitor and manage data size:
```rust
#[query]
#[icarus_tool("Get storage statistics")]
pub fn get_storage_stats() -> StorageStats {
    StorageStats {
        user_count: USERS.with(|u| u.borrow().len()),
        event_count: EVENTS.with(|e| e.borrow().len()),
        total_size_estimate: estimate_total_size(),
    }
}
```

## Troubleshooting

### Common Issues

1. **"Memory ID already in use"**
   - Ensure each `memory_id!` is unique
   - Check for duplicate declarations

2. **"Failed to deserialize"**
   - Data structure changed incompatibly
   - Implement migration strategy

3. **"Out of memory"**
   - Monitor memory usage
   - Implement data pruning
   - Consider multi-canister architecture

### Debugging Tools

```rust
#[query]
#[icarus_tool("Debug storage info")]
pub fn debug_storage() -> serde_json::Value {
    json!({
        "users": USERS.with(|u| u.borrow().len()),
        "memory_usage": get_memory_usage(),
        "heap_size": core::mem::size_of::<User>() * USERS.with(|u| u.borrow().len()),
    })
}
```

## Migration Strategies

When data structures change:

1. **Add versioning to your types**
2. **Create migration functions**
3. **Test migrations thoroughly**
4. **Keep old versions readable**

Example migration:
```rust
#[update]
#[icarus_tool("Migrate data to v2")]
pub fn migrate_to_v2() -> Result<(), String> {
    let old_data = OLD_STORAGE.with(|s| s.borrow().clone());
    
    for (key, old_value) in old_data {
        let new_value = migrate_value(old_value)?;
        NEW_STORAGE.with(|s| {
            s.borrow_mut().insert(key, new_value);
        });
    }
    
    Ok(())
}
```