molo-core 0.4.0

Core protocol types and traits for molo
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
//! Tool: external capabilities an agent can invoke.
//!
//! This file is where Tool is defined: the [`Tool`] trait defines the
//! interface agents use to execute tools, [`ToolSchema`] describes the
//! definition exposed to the model, [`ToolError`] describes why a call
//! fails; it contains no concrete tools — those are implemented by agent
//! applications (see `examples/tool_agent.rs`).
//!
//! Companion component:
//! - [`SharedState`] — a container for cross-tool shared state, injected
//!   via [`ToolContext`] on [`Tool::call`].

pub use shared_state::SharedState;

use crate::effect::{DisplayOutput, EffectRequest, RiskLevel};
use crate::run::{Artifact, RunContext, RunMetadata};
use serde::{Deserialize, Serialize};
use std::fmt;
use std::time::Duration;

/// Namespace assigned to a tool by the host application or extension layer.
///
/// The provider-facing tool name is still a single unique string. The
/// namespace is host-facing metadata used for extension unload, policy,
/// audit, and debugging.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ToolNamespace {
    /// Namespace kind.
    pub kind: ToolNamespaceKind,
    /// Stable host-assigned namespace id.
    pub id: String,
}

impl ToolNamespace {
    /// Constructs a namespace from a kind and stable id.
    pub fn new(kind: ToolNamespaceKind, id: impl Into<String>) -> Self {
        Self {
            kind,
            id: id.into(),
        }
    }

    /// Namespace for local application tools registered without extension
    /// source metadata.
    pub fn local() -> Self {
        Self::new(ToolNamespaceKind::Local, "local")
    }

    /// Namespace for tools discovered from one MCP server.
    pub fn mcp_server(id: impl Into<String>) -> Self {
        Self::new(ToolNamespaceKind::McpServer, id)
    }

    /// Namespace for tools exposed by one skill layer.
    pub fn skill_layer(id: impl Into<String>) -> Self {
        Self::new(ToolNamespaceKind::SkillLayer, id)
    }
}

impl fmt::Display for ToolNamespace {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}:{}", self.kind, self.id)
    }
}

/// Kind of tool namespace.
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ToolNamespaceKind {
    /// Local application-owned tools.
    Local,
    /// Tools discovered from an MCP server.
    McpServer,
    /// Tools exposed by an Agent Skills layer.
    SkillLayer,
    /// Tools exposed by a sub-agent.
    SubAgent,
    /// Application-specific namespace kind.
    Custom(String),
}

/// Trust level assigned to a tool source.
///
/// This value is a policy input only. It does not grant permission and must
/// not be used to bypass harness governance.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ToolTrustLevel {
    /// Host-owned trusted code.
    Trusted,
    /// Project-local source selected by the host.
    Project,
    /// User-installed extension source.
    UserInstalled,
    /// External process or service.
    External,
    /// Untrusted source.
    Untrusted,
}

/// Host-facing metadata describing where a provider-visible tool came from.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolSource {
    /// Source namespace.
    pub namespace: ToolNamespace,
    /// Raw source name before provider-facing disambiguation.
    pub raw_name: String,
    /// Provider-facing display name registered in `ToolRegistry`.
    pub display_name: String,
    /// Source trust level.
    pub trust: ToolTrustLevel,
    /// Host/application metadata.
    pub metadata: RunMetadata,
}

impl ToolSource {
    /// Constructs source metadata with external trust by default.
    pub fn new(
        namespace: ToolNamespace,
        raw_name: impl Into<String>,
        display_name: impl Into<String>,
    ) -> Self {
        Self {
            namespace,
            raw_name: raw_name.into(),
            display_name: display_name.into(),
            trust: ToolTrustLevel::External,
            metadata: RunMetadata::new(),
        }
    }

    /// Constructs source metadata for a local application tool.
    pub fn local(name: impl Into<String>) -> Self {
        let name = name.into();
        Self {
            namespace: ToolNamespace::local(),
            raw_name: name.clone(),
            display_name: name,
            trust: ToolTrustLevel::Trusted,
            metadata: RunMetadata::new(),
        }
    }

    /// Sets the trust level.
    pub fn with_trust(mut self, trust: ToolTrustLevel) -> Self {
        self.trust = trust;
        self
    }

    /// Sets source metadata.
    pub fn with_metadata(mut self, metadata: RunMetadata) -> Self {
        self.metadata = metadata;
        self
    }
}

/// The definition of a tool.
///
/// The model decides whether to call the tool and how to generate arguments
/// from `name` / `description` / `parameters`; Provider implementations map
/// those three fields to the vendor's wire format. [`ToolPolicy`] and
/// [`ToolSchema::metadata`] are framework-facing metadata and are not sent to
/// providers unless a provider adapter explicitly supports such annotations.
///
/// # Example
///
/// ```
/// # extern crate molo_core as molo;
/// use molo::tool::ToolSchema;
/// use serde_json::json;
///
/// let schema = ToolSchema::new(
///     "get_weather",
///     "Get the weather for a given city",
///     json!({
///         "type": "object",
///         "properties": {
///             "city": { "type": "string", "description": "City name" }
///         },
///         "required": ["city"]
///     }),
/// );
///
/// assert_eq!(schema.name, "get_weather");
/// ```
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolSchema {
    /// Tool name (the basis on which the model selects a tool).
    pub name: String,
    /// Tool description (the basis on which the model understands the
    /// tool's purpose).
    pub description: String,
    /// JSON Schema for the arguments, preferably generated from a serde
    /// struct with `schemars::schema_for!`.
    pub parameters: serde_json::Value,
    /// Framework-facing policy declaration.
    pub policy: ToolPolicy,
    /// Framework/application metadata.
    pub metadata: RunMetadata,
}

impl ToolSchema {
    /// Constructs a tool schema with default policy and no metadata.
    pub fn new(
        name: impl Into<String>,
        description: impl Into<String>,
        parameters: serde_json::Value,
    ) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            parameters,
            policy: ToolPolicy::default(),
            metadata: RunMetadata::new(),
        }
    }

    /// Sets framework-facing policy metadata.
    pub fn with_policy(mut self, policy: ToolPolicy) -> Self {
        self.policy = policy;
        self
    }

    /// Sets framework/application metadata.
    pub fn with_metadata(mut self, metadata: RunMetadata) -> Self {
        self.metadata = metadata;
        self
    }
}

/// Tool policy metadata declared by the tool author.
///
/// This is an input to registry events and harness policy; it is not an
/// authorization decision.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToolPolicy {
    /// Declared side-effect level.
    pub side_effects: SideEffectLevel,
    /// Default risk declaration.
    pub risk: RiskLevel,
    /// Whether the tool author recommends confirmation before execution.
    pub requires_confirmation: bool,
    /// Suggested timeout for tool/effect execution.
    pub timeout: Option<Duration>,
    /// Default memory policy for this tool's model-visible output.
    pub memory_policy: ToolMemoryPolicy,
}

impl Default for ToolPolicy {
    fn default() -> Self {
        Self {
            side_effects: SideEffectLevel::Pure,
            risk: RiskLevel::Low,
            requires_confirmation: false,
            timeout: None,
            memory_policy: ToolMemoryPolicy::Normal,
        }
    }
}

/// Declared side-effect level for a tool.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum SideEffectLevel {
    /// Pure computation.
    Pure,
    /// Reads host/application state but does not write it.
    ReadOnly,
    /// Writes host/application state.
    Write,
    /// Interacts with an external system.
    External,
}

/// Memory handling policy for model-visible tool/effect output.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ToolMemoryPolicy {
    /// Record normally.
    #[default]
    Normal,
    /// Record as protected memory when supported by the memory implementation.
    Protected,
}

impl ToolMemoryPolicy {
    /// Whether the output should be recorded as protected memory.
    pub fn is_protected(self) -> bool {
        matches!(self, Self::Protected)
    }
}

/// Model-visible output produced by a tool.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct ToolOutput {
    /// Text visible to the model through [`Message::ToolResult`](crate::Message::ToolResult).
    pub content: String,
    /// Optional host/UI display output.
    pub display: Option<DisplayOutput>,
    /// Artifact handles produced by the tool.
    pub artifacts: Vec<Artifact>,
    /// Memory policy for the model-visible content.
    pub memory_policy: ToolMemoryPolicy,
    /// Framework/application metadata.
    pub metadata: RunMetadata,
}

impl ToolOutput {
    /// Constructs plain text model-visible output.
    pub fn text(content: impl Into<String>) -> Self {
        Self {
            content: content.into(),
            display: None,
            artifacts: Vec::new(),
            memory_policy: ToolMemoryPolicy::Normal,
            metadata: RunMetadata::new(),
        }
    }

    /// Sets host/UI display output.
    pub fn with_display(mut self, display: DisplayOutput) -> Self {
        self.display = Some(display);
        self
    }

    /// Sets artifact handles.
    pub fn with_artifacts(mut self, artifacts: Vec<Artifact>) -> Self {
        self.artifacts = artifacts;
        self
    }

    /// Sets memory policy.
    pub fn with_memory_policy(mut self, policy: ToolMemoryPolicy) -> Self {
        self.memory_policy = policy;
        self
    }

    /// Sets framework/application metadata.
    pub fn with_metadata(mut self, metadata: RunMetadata) -> Self {
        self.metadata = metadata;
        self
    }
}

impl From<String> for ToolOutput {
    fn from(content: String) -> Self {
        Self::text(content)
    }
}

impl From<&str> for ToolOutput {
    fn from(content: &str) -> Self {
        Self::text(content)
    }
}

/// Result of a tool call.
///
/// Pure or low-risk work can return [`ToolResult::Output`]. Side-effecting
/// tools should return [`ToolResult::Effect`], allowing an outer harness to
/// govern and execute the requested side effect.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub enum ToolResult {
    /// Immediate model-visible output.
    Output(ToolOutput),
    /// Side-effect request for an outer harness.
    Effect(EffectRequest),
}

impl ToolResult {
    /// Returns model-visible text for immediate output results.
    ///
    /// Effect results return `None` because the side effect has not executed.
    pub fn output_content(&self) -> Option<&str> {
        match self {
            Self::Output(output) => Some(&output.content),
            Self::Effect(_) => None,
        }
    }

    /// Returns model-visible text, or an empty string for effect requests
    /// that have not executed yet.
    pub fn content_or_empty(&self) -> &str {
        self.output_content().unwrap_or("")
    }
}

impl std::fmt::Display for ToolResult {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Output(output) => f.write_str(&output.content),
            Self::Effect(request) => {
                write!(
                    f,
                    "effect request: {} ({})",
                    request.description, request.id
                )
            }
        }
    }
}

impl From<ToolOutput> for ToolResult {
    fn from(output: ToolOutput) -> Self {
        Self::Output(output)
    }
}

impl From<String> for ToolResult {
    fn from(content: String) -> Self {
        Self::Output(ToolOutput::text(content))
    }
}

impl From<&str> for ToolResult {
    fn from(content: &str) -> Self {
        Self::Output(ToolOutput::text(content))
    }
}

impl PartialEq<str> for ToolResult {
    fn eq(&self, other: &str) -> bool {
        self.output_content() == Some(other)
    }
}

impl PartialEq<&str> for ToolResult {
    fn eq(&self, other: &&str) -> bool {
        self == *other
    }
}

impl PartialEq<ToolResult> for str {
    fn eq(&self, other: &ToolResult) -> bool {
        other == self
    }
}

impl PartialEq<ToolResult> for &str {
    fn eq(&self, other: &ToolResult) -> bool {
        other == *self
    }
}

impl PartialEq<String> for ToolResult {
    fn eq(&self, other: &String) -> bool {
        self == other.as_str()
    }
}

impl PartialEq<ToolResult> for String {
    fn eq(&self, other: &ToolResult) -> bool {
        other == self
    }
}

/// Context passed to a tool call.
#[derive(Debug, Clone, Copy)]
pub struct ToolContext<'a> {
    /// Run execution context.
    pub run: &'a RunContext,
    /// Shared cross-tool state.
    pub state: &'a SharedState,
    /// Source model tool-call id.
    pub tool_call_id: &'a str,
    /// Tool name used for this call.
    pub tool_name: &'a str,
}

impl<'a> ToolContext<'a> {
    /// Constructs tool-call context.
    pub fn new(
        run: &'a RunContext,
        state: &'a SharedState,
        tool_call_id: &'a str,
        tool_name: &'a str,
    ) -> Self {
        Self {
            run,
            state,
            tool_call_id,
            tool_name,
        }
    }
}

/// A tool an agent can invoke.
///
/// A tool has two perspectives:
/// - [`Tool::schema`] — the model perspective — tells the model what the
///   tool is and what its arguments look like;
/// - [`Tool::call`] — parses model-provided arguments into an immediate
///   [`ToolOutput`] or an [`EffectRequest`] to be executed by an outer
///   harness.
///
/// Implementations must be `Send + Sync`: the agent loop may execute tools
/// concurrently on any thread. Tools that need to flow / share custom
/// content across tools read and write [`ToolContext::state`];
/// tools that do not can ignore it (`_state`).
///
/// # Example
///
/// ```
/// # extern crate molo_core as molo;
/// use molo::tool::{Tool, ToolContext, ToolError, ToolOutput, ToolResult, ToolSchema};
/// use serde_json::json;
///
/// // A demo tool: returns a fixed time.
/// struct TimeTool;
///
/// #[molo::async_trait]
/// impl Tool for TimeTool {
///     fn schema(&self) -> ToolSchema {
///         ToolSchema::new(
///             "time",
///             "Return the current time",
///             json!({ "type": "object", "properties": {} }),
///         )
///     }
///
///     async fn call(
///         &self,
///         _arguments: serde_json::Value,
///         _context: ToolContext<'_>,
///     ) -> Result<ToolResult, ToolError> {
///         Ok(ToolOutput::text("12:00").into())
///     }
/// }
///
/// let tool = TimeTool;
/// assert_eq!(tool.schema().name, "time");
/// ```
#[async_trait::async_trait]
pub trait Tool: Send + Sync {
    /// Model perspective: this tool's definition.
    fn schema(&self) -> ToolSchema;

    /// Execution perspective: run this tool.
    ///
    /// `arguments` is the model-generated arguments JSON parsed by the
    /// registry. `context` carries the run context, source tool-call id/name,
    /// and the agent's shared state.
    async fn call(
        &self,
        arguments: serde_json::Value,
        context: ToolContext<'_>,
    ) -> Result<ToolResult, ToolError>;
}

/// Reasons a tool call fails.
///
/// `#[non_exhaustive]` ensures future error categories are not breaking
/// changes; external crates should match with a wildcard arm to stay
/// compatible with variants added in later versions.
///
/// # Example
///
/// ```
/// # extern crate molo_core as molo;
/// use molo::tool::ToolError;
///
/// let err = ToolError::InvalidArguments("missing field city".into());
/// assert_eq!(err.to_string(), "invalid arguments: missing field city");
/// ```
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ToolError {
    /// The model-provided arguments do not match the tool's arguments schema.
    #[error("invalid arguments: {0}")]
    InvalidArguments(String),
    /// The tool failed while executing.
    ///
    /// The Display text carries no "tool " prefix: the error type name
    /// already conveys the domain, avoiding a doubled prefix like
    /// "tool error: tool ..." after being wrapped by registry execution
    /// errors.
    #[error("execution failed: {0}")]
    Execution(String),
}

impl From<serde_json::Error> for ToolError {
    fn from(err: serde_json::Error) -> Self {
        ToolError::InvalidArguments(err.to_string())
    }
}

mod shared_state;