ironclaw 0.22.0

Secure personal AI assistant that protects your data and expands its capabilities on the fly
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
//! Serde structs for extension registry manifests.
//!
//! Each manifest describes a single extension (tool or channel) with its source
//! location, build artifacts, authentication requirements, and tags.

use serde::{Deserialize, Serialize};

use crate::extensions::{AuthHint, ExtensionKind, ExtensionSource, RegistryEntry};

/// A single extension manifest loaded from `registry/{tools,channels,mcp-servers}/<name>.json`.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ExtensionManifest {
    /// Unique identifier (matches crate name stem, e.g. "slack").
    pub name: String,

    /// Human-readable name (e.g. "Slack").
    pub display_name: String,

    /// Whether this is a tool, channel, or MCP server.
    pub kind: ManifestKind,

    /// Semver version from Cargo.toml. Optional for MCP server manifests.
    #[serde(default)]
    pub version: Option<String>,

    /// One-line description.
    pub description: String,

    /// Search keywords beyond the name.
    #[serde(default)]
    pub keywords: Vec<String>,

    /// Source code location and build info. Absent for MCP server manifests.
    #[serde(default)]
    pub source: Option<SourceSpec>,

    /// Pre-built binary artifacts keyed by target triple.
    #[serde(default)]
    pub artifacts: std::collections::HashMap<String, ArtifactSpec>,

    /// Summary of authentication requirements.
    #[serde(default)]
    pub auth_summary: Option<AuthSummary>,

    /// Tags for filtering (e.g. "default", "messaging", "google").
    #[serde(default)]
    pub tags: Vec<String>,

    /// MCP server URL. Only present for `McpServer` manifests.
    #[serde(default)]
    pub url: Option<String>,

    /// MCP auth method: "dcr", "oauth_pre_configured:<setup_url>", or "none".
    /// Only present for `McpServer` manifests.
    #[serde(default)]
    pub auth: Option<String>,
}

/// Extension kind as declared in manifests.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ManifestKind {
    Tool,
    Channel,
    McpServer,
}

impl From<ManifestKind> for ExtensionKind {
    fn from(kind: ManifestKind) -> Self {
        match kind {
            ManifestKind::Tool => ExtensionKind::WasmTool,
            ManifestKind::Channel => ExtensionKind::WasmChannel,
            ManifestKind::McpServer => ExtensionKind::McpServer,
        }
    }
}

impl std::fmt::Display for ManifestKind {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ManifestKind::Tool => write!(f, "tool"),
            ManifestKind::Channel => write!(f, "channel"),
            ManifestKind::McpServer => write!(f, "mcp_server"),
        }
    }
}

/// Source code location for building from source.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SourceSpec {
    /// Path relative to repo root (e.g. "tools-src/slack").
    pub dir: String,

    /// Capabilities filename relative to source dir.
    pub capabilities: String,

    /// Rust crate name for `cargo component build`.
    pub crate_name: String,
}

/// A pre-built binary artifact.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ArtifactSpec {
    /// Download URL (null until release).
    /// Can point to a `.wasm` file or a `.tar.gz` bundle containing both
    /// `{name}.wasm` and `{name}.capabilities.json`.
    pub url: Option<String>,

    /// Hex SHA256 of the downloaded artifact (null until release).
    pub sha256: Option<String>,

    /// Optional separate download URL for the capabilities file.
    /// Only needed when `url` points to a bare `.wasm` file instead of a bundle.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub capabilities_url: Option<String>,
}

/// Summary of authentication requirements extracted from capabilities.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AuthSummary {
    /// Auth method: "oauth", "manual", or "none".
    #[serde(default)]
    pub method: Option<String>,

    /// Display name for the auth provider (e.g. "Google", "Slack").
    #[serde(default)]
    pub provider: Option<String>,

    /// Secret names required by this extension.
    #[serde(default)]
    pub secrets: Vec<String>,

    /// If this extension shares auth with others (e.g. all Google tools share
    /// `google_oauth_token`), this is the shared secret name.
    #[serde(default)]
    pub shared_auth: Option<String>,

    /// URL where users can set up credentials.
    #[serde(default)]
    pub setup_url: Option<String>,
}

/// Bundle definition grouping related extensions.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BundleDefinition {
    /// Human-readable name.
    pub display_name: String,

    /// Description of what this bundle contains.
    #[serde(default)]
    pub description: Option<String>,

    /// Extension references as "tools/<name>" or "channels/<name>".
    pub extensions: Vec<String>,

    /// Shared auth secret across bundle members (if any).
    #[serde(default)]
    pub shared_auth: Option<String>,
}

/// Top-level structure of `_bundles.json`.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct BundlesFile {
    pub bundles: std::collections::HashMap<String, BundleDefinition>,
}

impl ExtensionManifest {
    /// Convert this manifest into a [`RegistryEntry`] for use with the in-chat
    /// extension discovery system.
    ///
    /// Returns `None` for MCP server manifests missing a `url` field.
    pub fn to_registry_entry(&self) -> Option<RegistryEntry> {
        if self.kind == ManifestKind::McpServer {
            return self.to_mcp_registry_entry();
        }

        Some(self.to_wasm_registry_entry())
    }

    /// Build a [`RegistryEntry`] for an MCP server manifest.
    fn to_mcp_registry_entry(&self) -> Option<RegistryEntry> {
        let url = match &self.url {
            Some(u) => u.clone(),
            None => {
                tracing::warn!(
                    "MCP server manifest '{}' is missing 'url' field, skipping",
                    self.name
                );
                return None;
            }
        };
        let auth_hint = match self.auth.as_deref() {
            Some("dcr") | None => AuthHint::Dcr,
            Some("none") => AuthHint::None,
            Some(other) if other.starts_with("oauth_pre_configured:") => {
                AuthHint::OAuthPreConfigured {
                    setup_url: other
                        .strip_prefix("oauth_pre_configured:")
                        .unwrap_or("")
                        .to_string(),
                }
            }
            _ => AuthHint::Dcr,
        };

        Some(RegistryEntry {
            name: self.name.clone(),
            display_name: self.display_name.clone(),
            kind: ExtensionKind::McpServer,
            description: self.description.clone(),
            keywords: self.keywords.clone(),
            source: ExtensionSource::McpUrl { url },
            fallback_source: None,
            auth_hint,
            version: self.version.clone(),
        })
    }

    /// Build a [`RegistryEntry`] for a WASM tool or channel manifest.
    fn to_wasm_registry_entry(&self) -> RegistryEntry {
        let source_spec = self.source.as_ref();

        let buildable = source_spec.map(|s| ExtensionSource::WasmBuildable {
            source_dir: s.dir.clone(),
            build_dir: Some(s.dir.clone()),
            crate_name: Some(s.crate_name.clone()),
        });

        // Prefer pre-built artifact download when a URL is available,
        // with build-from-source as fallback in case the download fails (e.g., 404).
        let (source, fallback_source) = if let Some(artifact) = self.artifacts.get("wasm32-wasip2")
        {
            if let Some(ref url) = artifact.url {
                (
                    ExtensionSource::WasmDownload {
                        wasm_url: url.clone(),
                        capabilities_url: artifact.capabilities_url.clone(),
                    },
                    buildable.map(Box::new),
                )
            } else if let Some(b) = buildable {
                (b, None)
            } else {
                // No source spec and no download URL — use a placeholder
                (
                    ExtensionSource::WasmBuildable {
                        source_dir: String::new(),
                        build_dir: None,
                        crate_name: None,
                    },
                    None,
                )
            }
        } else if let Some(b) = buildable {
            (b, None)
        } else {
            (
                ExtensionSource::WasmBuildable {
                    source_dir: String::new(),
                    build_dir: None,
                    crate_name: None,
                },
                None,
            )
        };

        let auth_hint = match self.auth_summary.as_ref().and_then(|a| a.method.as_deref()) {
            Some("oauth") => AuthHint::CapabilitiesAuth,
            Some("manual") => AuthHint::CapabilitiesAuth,
            Some("none") | None => AuthHint::None,
            Some(_) => AuthHint::CapabilitiesAuth,
        };

        RegistryEntry {
            name: self.name.clone(),
            display_name: self.display_name.clone(),
            kind: self.kind.into(),
            description: self.description.clone(),
            keywords: self.keywords.clone(),
            source,
            fallback_source,
            auth_hint,
            version: self.version.clone(),
        }
    }
}

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

    #[test]
    fn test_parse_tool_manifest() {
        let json = r#"{
            "name": "slack",
            "display_name": "Slack",
            "kind": "tool",
            "version": "0.1.0",
            "description": "Post messages via Slack API",
            "keywords": ["messaging"],
            "source": {
                "dir": "tools-src/slack",
                "capabilities": "slack-tool.capabilities.json",
                "crate_name": "slack-tool"
            },
            "artifacts": {
                "wasm32-wasip2": { "url": null, "sha256": null }
            },
            "auth_summary": {
                "method": "oauth",
                "provider": "Slack",
                "secrets": ["slack_bot_token"],
                "shared_auth": null,
                "setup_url": "https://api.slack.com/apps"
            },
            "tags": ["default", "messaging"]
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        assert_eq!(manifest.name, "slack");
        assert_eq!(manifest.kind, ManifestKind::Tool);
        assert_eq!(manifest.version.as_deref(), Some("0.1.0"));
        assert!(manifest.tags.contains(&"default".to_string()));

        let entry = manifest.to_registry_entry().unwrap();
        assert_eq!(entry.kind, ExtensionKind::WasmTool);
    }

    #[test]
    fn test_parse_channel_manifest() {
        let json = r#"{
            "name": "telegram",
            "display_name": "Telegram",
            "kind": "channel",
            "version": "0.1.0",
            "description": "Telegram Bot API channel",
            "source": {
                "dir": "channels-src/telegram",
                "capabilities": "telegram.capabilities.json",
                "crate_name": "telegram-channel"
            },
            "tags": ["messaging"]
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        assert_eq!(manifest.kind, ManifestKind::Channel);
        assert!(manifest.auth_summary.is_none());
        assert!(manifest.artifacts.is_empty());

        let entry = manifest.to_registry_entry().unwrap();
        assert_eq!(entry.kind, ExtensionKind::WasmChannel);
    }

    #[test]
    fn test_parse_bundles() {
        let json = r#"{
            "bundles": {
                "google": {
                    "display_name": "Google Suite",
                    "description": "All Google tools",
                    "extensions": ["tools/gmail", "tools/google-calendar"],
                    "shared_auth": "google_oauth_token"
                },
                "default": {
                    "display_name": "Recommended Set",
                    "extensions": ["tools/github", "tools/slack"]
                }
            }
        }"#;

        let bundles: BundlesFile = serde_json::from_str(json).expect("parse bundles");
        assert_eq!(bundles.bundles.len(), 2);
        assert_eq!(
            bundles.bundles["google"].shared_auth.as_deref(),
            Some("google_oauth_token")
        );
        assert!(bundles.bundles["default"].shared_auth.is_none());
    }

    #[test]
    fn test_manifest_kind_display() {
        assert_eq!(ManifestKind::Tool.to_string(), "tool");
        assert_eq!(ManifestKind::Channel.to_string(), "channel");
        assert_eq!(ManifestKind::McpServer.to_string(), "mcp_server");
    }

    /// When a manifest has a download URL in artifacts, to_registry_entry()
    /// should set WasmDownload as primary source and WasmBuildable as fallback.
    #[test]
    fn test_manifest_with_download_url_has_buildable_fallback() {
        let json = r#"{
            "name": "gmail",
            "display_name": "Gmail",
            "kind": "tool",
            "version": "0.1.0",
            "description": "Gmail tool",
            "keywords": ["email"],
            "source": {
                "dir": "tools-src/gmail",
                "capabilities": "gmail-tool.capabilities.json",
                "crate_name": "gmail-tool"
            },
            "artifacts": {
                "wasm32-wasip2": {
                    "url": "https://github.com/nearai/ironclaw/releases/latest/download/gmail-wasm32-wasip2.tar.gz",
                    "sha256": null
                }
            },
            "tags": ["default"]
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        let entry = manifest.to_registry_entry().unwrap();

        // Primary source should be WasmDownload
        assert!(
            matches!(&entry.source, ExtensionSource::WasmDownload { .. }),
            "Primary source should be WasmDownload, got {:?}",
            entry.source
        );

        // Fallback should be WasmBuildable with the source dir info
        let fallback = entry
            .fallback_source
            .as_ref()
            .expect("Should have fallback_source when download URL is set");
        match fallback.as_ref() {
            ExtensionSource::WasmBuildable {
                build_dir,
                crate_name,
                ..
            } => {
                assert_eq!(build_dir.as_deref(), Some("tools-src/gmail"));
                assert_eq!(crate_name.as_deref(), Some("gmail-tool"));
            }
            other => panic!("Fallback should be WasmBuildable, got {:?}", other),
        }
    }

    /// When a manifest has null URL in artifacts, the primary source should be
    /// WasmBuildable with no fallback.
    #[test]
    fn test_manifest_with_null_url_no_fallback() {
        let json = r#"{
            "name": "slack",
            "display_name": "Slack",
            "kind": "tool",
            "version": "0.1.0",
            "description": "Slack tool",
            "keywords": [],
            "source": {
                "dir": "tools-src/slack",
                "capabilities": "slack-tool.capabilities.json",
                "crate_name": "slack-tool"
            },
            "artifacts": {
                "wasm32-wasip2": { "url": null, "sha256": null }
            },
            "tags": []
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        let entry = manifest.to_registry_entry().unwrap();

        assert!(
            matches!(&entry.source, ExtensionSource::WasmBuildable { .. }),
            "Should use WasmBuildable when URL is null"
        );
        assert!(
            entry.fallback_source.is_none(),
            "Should have no fallback when already using WasmBuildable"
        );
    }

    /// When a manifest has no artifacts section, should use WasmBuildable with no fallback.
    #[test]
    fn test_manifest_no_artifacts_no_fallback() {
        let json = r#"{
            "name": "custom",
            "display_name": "Custom",
            "kind": "tool",
            "version": "0.1.0",
            "description": "Custom tool",
            "keywords": [],
            "source": {
                "dir": "tools-src/custom",
                "capabilities": "custom.capabilities.json",
                "crate_name": "custom-tool"
            },
            "tags": []
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        let entry = manifest.to_registry_entry().unwrap();

        assert!(
            matches!(&entry.source, ExtensionSource::WasmBuildable { .. }),
            "Should use WasmBuildable when no artifacts"
        );
        assert!(
            entry.fallback_source.is_none(),
            "Should have no fallback when already using WasmBuildable"
        );
    }

    #[test]
    fn test_parse_mcp_server_manifest() {
        let json = r#"{
            "name": "notion",
            "display_name": "Notion",
            "kind": "mcp_server",
            "description": "Connect to Notion for reading and writing pages, databases, and comments",
            "keywords": ["notes", "wiki", "docs", "pages", "database"],
            "url": "https://mcp.notion.com/mcp",
            "auth": "dcr"
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        assert_eq!(manifest.name, "notion");
        assert_eq!(manifest.kind, ManifestKind::McpServer);
        assert!(manifest.version.is_none());
        assert!(manifest.source.is_none());
        assert_eq!(manifest.url.as_deref(), Some("https://mcp.notion.com/mcp"));
        assert_eq!(manifest.auth.as_deref(), Some("dcr"));

        let entry = manifest.to_registry_entry().unwrap();
        assert_eq!(entry.kind, ExtensionKind::McpServer);
        assert!(
            matches!(&entry.source, ExtensionSource::McpUrl { url } if url == "https://mcp.notion.com/mcp")
        );
        assert!(matches!(&entry.auth_hint, AuthHint::Dcr));
        assert!(entry.fallback_source.is_none());
    }

    #[test]
    fn test_mcp_server_oauth_pre_configured() {
        let json = r#"{
            "name": "custom-mcp",
            "display_name": "Custom MCP",
            "kind": "mcp_server",
            "description": "Custom MCP server",
            "keywords": [],
            "url": "https://mcp.example.com",
            "auth": "oauth_pre_configured:https://example.com/setup"
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        let entry = manifest.to_registry_entry().unwrap();

        assert!(matches!(
            &entry.auth_hint,
            AuthHint::OAuthPreConfigured { setup_url } if setup_url == "https://example.com/setup"
        ));
    }

    #[test]
    fn test_mcp_server_auth_none() {
        let json = r#"{
            "name": "local-mcp",
            "display_name": "Local MCP",
            "kind": "mcp_server",
            "description": "Local MCP server",
            "keywords": [],
            "url": "http://localhost:8080/mcp",
            "auth": "none"
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        let entry = manifest.to_registry_entry().unwrap();

        assert!(matches!(&entry.auth_hint, AuthHint::None));
    }

    #[test]
    fn test_mcp_server_missing_url_returns_none() {
        let json = r#"{
            "name": "broken-mcp",
            "display_name": "Broken MCP",
            "kind": "mcp_server",
            "description": "MCP server with no URL",
            "keywords": []
        }"#;

        let manifest: ExtensionManifest = serde_json::from_str(json).expect("parse manifest");
        assert!(
            manifest.to_registry_entry().is_none(),
            "MCP manifest without url should return None"
        );
    }
}