prompty 2.0.0-beta.1

Prompty is an asset class and format for LLM prompts
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
// Code generated by Prompty emitter; DO NOT EDIT.

#![allow(
    unused_imports,
    dead_code,
    non_camel_case_types,
    unused_variables,
    clippy::all
)]

use super::super::context::{LoadContext, SaveContext};

use super::binding::Binding;

use super::super::connection::connection::Connection;

use super::mcp_approval_mode::McpApprovalMode;

use super::super::core::property::Property;

/// Variant-specific data for [`Tool`], discriminated by `kind`.
#[derive(Debug, Clone)]
pub enum ToolKind {
    /// `kind` = `"function"`
    Function {
        /// Parameters accepted by the function tool
        parameters: Vec<Property>,
        /// Indicates whether the function tool enforces strict validation on its parameters
        strict: Option<bool>,
    },
    /// `kind` = `"mcp"`
    Mcp {
        /// The connection configuration for the MCP tool
        connection: serde_json::Value,
        /// The server name of the MCP tool
        server_name: String,
        /// The description of the MCP tool
        server_description: Option<String>,
        /// The approval mode for the MCP tool
        approval_mode: McpApprovalMode,
        /// List of allowed operations or resources for the MCP tool
        allowed_tools: Option<Vec<String>>,
    },
    /// `kind` = `"openapi"`
    OpenApi {
        /// The connection configuration for the OpenAPI tool
        connection: serde_json::Value,
        /// The full OpenAPI specification
        specification: String,
    },
    /// `kind` = `"prompty"`
    Prompty {
        /// Path to the child .prompty file, relative to the parent
        path: String,
        /// Execution mode. Only 'single' is supported; nested agent loops are not started from PromptyTool.
        mode: String,
    },
    /// Wildcard / catch-all variant for unrecognized `kind` values.
    Custom {
        /// Connection configuration for the server tool
        connection: serde_json::Value,
        /// Configuration options for the server tool
        options: serde_json::Value,
        /// The raw `kind` string for this unknown variant.
        kind_name: String,
    },
}

impl Default for ToolKind {
    fn default() -> Self {
        ToolKind::Custom {
            connection: serde_json::Value::Null,
            options: serde_json::Value::Null,
            kind_name: String::new(),
        }
    }
}
/// Represents a tool that can be used in prompts.
#[derive(Debug, Clone, Default)]
pub struct Tool {
    /// Name of the tool. If a function tool, this is the function name, otherwise it is the type
    pub name: String,
    /// A short description of the tool for metadata purposes
    pub description: Option<String>,
    /// Tool argument bindings to input properties
    pub bindings: Vec<Binding>,
    /// Variant-specific data, discriminated by `kind`.
    pub kind: ToolKind,
}

impl Tool {
    /// Create a new Tool with default values.
    pub fn new() -> Self {
        Self::default()
    }

    /// Load Tool from a JSON string.
    pub fn from_json(json: &str, ctx: &LoadContext) -> Result<Self, serde_json::Error> {
        let value: serde_json::Value = serde_json::from_str(json)?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load Tool from a YAML string.
    pub fn from_yaml(yaml: &str, ctx: &LoadContext) -> Result<Self, serde_yaml::Error> {
        let value: serde_json::Value = serde_yaml::from_str(yaml)?;
        Ok(Self::load_from_value(&value, ctx))
    }

    /// Load Tool from a `serde_json::Value`.
    ///
    /// Calls `ctx.process_input` before field extraction.
    pub fn load_from_value(value: &serde_json::Value, ctx: &LoadContext) -> Self {
        let value = ctx.process_input(value.clone());
        let kind_str = value.get("kind").and_then(|v| v.as_str()).unwrap_or("");
        let kind = match kind_str {
            "function" => ToolKind::Function {
                parameters: value
                    .get("parameters")
                    .map(|v| Self::load_parameters(v, ctx))
                    .unwrap_or_default(),
                strict: value.get("strict").and_then(|v| v.as_bool()),
            },
            "mcp" => ToolKind::Mcp {
                connection: value
                    .get("connection")
                    .cloned()
                    .unwrap_or(serde_json::Value::Null),
                server_name: value
                    .get("serverName")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                server_description: value
                    .get("serverDescription")
                    .and_then(|v| v.as_str())
                    .map(|s| s.to_string()),
                approval_mode: value
                    .get("approvalMode")
                    .filter(|v| v.is_object() || v.is_array() || v.is_string())
                    .map(|v| McpApprovalMode::load_from_value(v, ctx))
                    .unwrap_or_default(),
                allowed_tools: value
                    .get("allowedTools")
                    .and_then(|v| v.as_array())
                    .map(|arr| {
                        arr.iter()
                            .filter_map(|v| v.as_str().map(|s| s.to_string()))
                            .collect()
                    }),
            },
            "openapi" => ToolKind::OpenApi {
                connection: value
                    .get("connection")
                    .cloned()
                    .unwrap_or(serde_json::Value::Null),
                specification: value
                    .get("specification")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
            },
            "prompty" => ToolKind::Prompty {
                path: value
                    .get("path")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
                mode: value
                    .get("mode")
                    .and_then(|v| v.as_str())
                    .unwrap_or_default()
                    .to_string(),
            },
            _ => ToolKind::Custom {
                connection: value
                    .get("connection")
                    .cloned()
                    .unwrap_or(serde_json::Value::Null),
                options: value
                    .get("options")
                    .cloned()
                    .unwrap_or(serde_json::Value::Null),
                kind_name: kind_str.to_string(),
            },
        };
        Self {
            name: value
                .get("name")
                .and_then(|v| v.as_str())
                .unwrap_or_default()
                .to_string(),
            description: value
                .get("description")
                .and_then(|v| v.as_str())
                .map(|s| s.to_string()),
            bindings: value
                .get("bindings")
                .map(|v| Self::load_bindings(v, ctx))
                .unwrap_or_default(),
            kind: kind,
        }
    }

    /// Returns the `kind` discriminator string for this instance.
    pub fn kind_str(&self) -> &str {
        match &self.kind {
            ToolKind::Function { .. } => "function",
            ToolKind::Mcp { .. } => "mcp",
            ToolKind::OpenApi { .. } => "openapi",
            ToolKind::Prompty { .. } => "prompty",
            ToolKind::Custom { kind_name, .. } => kind_name.as_str(),
        }
    }

    /// Serialize Tool to a `serde_json::Value`.
    ///
    /// Calls `ctx.process_dict` after serialization.
    pub fn to_value(&self, ctx: &SaveContext) -> serde_json::Value {
        let mut result = serde_json::Map::new();
        // Write the discriminator
        result.insert(
            "kind".to_string(),
            serde_json::Value::String(self.kind_str().to_string()),
        );
        // Write base fields
        if !self.name.is_empty() {
            result.insert(
                "name".to_string(),
                serde_json::Value::String(self.name.clone()),
            );
        }
        if let Some(ref val) = self.description {
            result.insert(
                "description".to_string(),
                serde_json::Value::String(val.clone()),
            );
        }
        if !self.bindings.is_empty() {
            result.insert(
                "bindings".to_string(),
                Self::save_bindings(&self.bindings, ctx),
            );
        }
        // Write variant-specific fields
        match &self.kind {
            ToolKind::Function {
                parameters, strict, ..
            } => {
                if !parameters.is_empty() {
                    result.insert(
                        "parameters".to_string(),
                        serde_json::Value::Array(
                            parameters.iter().map(|item| item.to_value(ctx)).collect(),
                        ),
                    );
                }
                if let Some(val) = strict {
                    result.insert("strict".to_string(), serde_json::Value::Bool(*val));
                }
            }
            ToolKind::Mcp {
                connection,
                server_name,
                server_description,
                approval_mode,
                allowed_tools,
                ..
            } => {
                if !connection.is_null() {
                    result.insert("connection".to_string(), connection.clone());
                }
                if !server_name.is_empty() {
                    result.insert(
                        "serverName".to_string(),
                        serde_json::Value::String(server_name.clone()),
                    );
                }
                if let Some(val) = server_description {
                    result.insert(
                        "serverDescription".to_string(),
                        serde_json::Value::String(val.clone()),
                    );
                }
                {
                    let nested = approval_mode.to_value(ctx);
                    if !nested.is_null() {
                        result.insert("approvalMode".to_string(), nested);
                    }
                }
                if let Some(items) = allowed_tools {
                    result.insert(
                        "allowedTools".to_string(),
                        serde_json::to_value(items).unwrap_or(serde_json::Value::Null),
                    );
                }
            }
            ToolKind::OpenApi {
                connection,
                specification,
                ..
            } => {
                if !connection.is_null() {
                    result.insert("connection".to_string(), connection.clone());
                }
                if !specification.is_empty() {
                    result.insert(
                        "specification".to_string(),
                        serde_json::Value::String(specification.clone()),
                    );
                }
            }
            ToolKind::Prompty { path, mode, .. } => {
                if !path.is_empty() {
                    result.insert("path".to_string(), serde_json::Value::String(path.clone()));
                }
                if !mode.is_empty() {
                    result.insert("mode".to_string(), serde_json::Value::String(mode.clone()));
                }
            }
            ToolKind::Custom {
                connection,
                options,
                kind_name: _,
                ..
            } => {
                if !connection.is_null() {
                    result.insert("connection".to_string(), connection.clone());
                }
                if !options.is_null() {
                    result.insert("options".to_string(), options.clone());
                }
            }
        }
        ctx.process_dict(serde_json::Value::Object(result))
    }

    /// Serialize Tool to a JSON string.
    pub fn to_json(&self, ctx: &SaveContext) -> Result<String, serde_json::Error> {
        serde_json::to_string_pretty(&self.to_value(ctx))
    }

    /// Serialize Tool to a YAML string.
    pub fn to_yaml(&self, ctx: &SaveContext) -> Result<String, serde_yaml::Error> {
        serde_yaml::to_string(&self.to_value(ctx))
    }

    /// Load a collection of Binding from a JSON value.
    /// Handles both array format `[{...}]` and dict format `{"name": {...}}`.
    fn load_bindings(data: &serde_json::Value, ctx: &LoadContext) -> Vec<Binding> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| Binding::load_from_value(v, ctx))
                .collect(),

            serde_json::Value::Object(obj) => obj
                .iter()
                .filter_map(|(name, value)| {
                    if value.is_array() {
                        return None;
                    }
                    let mut v = if value.is_object() {
                        value.clone()
                    } else {
                        serde_json::json!({ "input": value })
                    };
                    if let serde_json::Value::Object(ref mut m) = v {
                        m.entry("name".to_string())
                            .or_insert_with(|| serde_json::Value::String(name.clone()));
                    }
                    Some(Binding::load_from_value(&v, ctx))
                })
                .collect(),
            _ => Vec::new(),
        }
    }

    /// Save a collection of Binding to a JSON value.
    fn save_bindings(items: &[Binding], ctx: &SaveContext) -> serde_json::Value {
        if ctx.collection_format == "array" {
            return serde_json::Value::Array(
                items
                    .iter()
                    .map(|item| item.to_value(ctx))
                    .collect::<Vec<_>>(),
            );
        }
        // Object format: use name as key
        let mut result = serde_json::Map::new();
        for item in items {
            let mut item_data = match item.to_value(ctx) {
                serde_json::Value::Object(m) => m,
                other => {
                    let mut m = serde_json::Map::new();
                    m.insert("value".to_string(), other);
                    m
                }
            };
            if let Some(serde_json::Value::String(name)) = item_data.remove("name") {
                result.insert(name, serde_json::Value::Object(item_data));
            }
        }
        serde_json::Value::Object(result)
    }

    /// Load a collection of Property from a JSON value.
    /// Handles both array format `[{...}]`.
    fn load_parameters(data: &serde_json::Value, ctx: &LoadContext) -> Vec<Property> {
        match data {
            serde_json::Value::Array(arr) => arr
                .iter()
                .map(|v| Property::load_from_value(v, ctx))
                .collect(),

            _ => Vec::new(),
        }
    }

    /// Save a collection of Property to a JSON value.
    fn save_parameters(items: &[Property], ctx: &SaveContext) -> serde_json::Value {
        serde_json::Value::Array(
            items
                .iter()
                .map(|item| item.to_value(ctx))
                .collect::<Vec<_>>(),
        )
    }
}