pmcp 2.2.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
//! Sequential workflow implementation
//!
//! Orchestrates multiple workflow steps in sequence with data flow validation.

use super::{
    error::WorkflowError,
    newtypes::{ArgName, BindingName},
    prompt_content::InternalPromptMessage,
    workflow_step::WorkflowStep,
};
use crate::types::PromptArgumentType;
use indexmap::IndexMap;
use smallvec::SmallVec;

/// A sequential workflow that executes steps in order
#[derive(Clone, Debug)]
pub struct SequentialWorkflow {
    /// Workflow name
    name: String,
    /// Workflow description
    description: String,
    /// Required prompt arguments
    /// `IndexMap` for deterministic iteration
    arguments: IndexMap<ArgName, ArgumentSpec>,
    /// Workflow steps in execution order
    /// `SmallVec` optimized for 2-4 steps
    steps: SmallVec<[WorkflowStep; 3]>,
    /// Instruction messages for the workflow
    /// `SmallVec` optimized for 2-3 instructions
    instructions: SmallVec<[InternalPromptMessage; 3]>,
    /// Whether this workflow should be backed by a task for durable progress tracking.
    /// When true and a task router is configured on the server, the workflow will be
    /// wrapped in a [`TaskWorkflowPromptHandler`](super::TaskWorkflowPromptHandler)
    /// that creates a task on invocation.
    task_support: bool,
}

/// Specification for a prompt argument
#[derive(Clone, Debug)]
pub struct ArgumentSpec {
    /// Argument description
    pub description: String,
    /// Whether the argument is required
    pub required: bool,
    /// Type hint for the argument (PMCP extension)
    ///
    /// When set, string arguments will be validated and converted to the
    /// appropriate type before being passed to tool calls.
    pub arg_type: Option<PromptArgumentType>,
}

impl SequentialWorkflow {
    /// Create a new sequential workflow
    ///
    /// # Example
    /// ```
    /// use pmcp::server::workflow::SequentialWorkflow;
    ///
    /// let workflow = SequentialWorkflow::new(
    ///     "content_workflow",
    ///     "Create and review content"
    /// );
    /// ```
    #[must_use]
    pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            description: description.into(),
            arguments: IndexMap::new(),
            steps: SmallVec::new(),
            instructions: SmallVec::new(),
            task_support: false,
        }
    }

    /// Add a prompt argument (chainable)
    ///
    /// This adds a string-typed argument. For numeric or boolean arguments,
    /// use [`typed_argument`](Self::typed_argument) instead.
    ///
    /// # Example
    /// ```
    /// use pmcp::server::workflow::SequentialWorkflow;
    ///
    /// let workflow = SequentialWorkflow::new("workflow", "description")
    ///     .argument("topic", "The topic to write about", true);
    /// ```
    #[must_use]
    pub fn argument(
        mut self,
        name: impl Into<ArgName>,
        description: impl Into<String>,
        required: bool,
    ) -> Self {
        self.arguments.insert(
            name.into(),
            ArgumentSpec {
                description: description.into(),
                required,
                arg_type: None, // Default to string (no type hint)
            },
        );
        self
    }

    /// Add a typed prompt argument (chainable)
    ///
    /// This adds an argument with a type hint. The type hint enables:
    /// - Validation of string arguments before processing
    /// - Automatic conversion to the correct JSON type for tool calls
    /// - Better UX in MCP clients (appropriate input widgets)
    ///
    /// # Example
    /// ```
    /// use pmcp::server::workflow::SequentialWorkflow;
    /// use pmcp::types::PromptArgumentType;
    ///
    /// let workflow = SequentialWorkflow::new("calculator", "Calculate something")
    ///     .typed_argument("x", "First number", true, PromptArgumentType::Number)
    ///     .typed_argument("y", "Second number", true, PromptArgumentType::Number)
    ///     .typed_argument("verbose", "Show steps", false, PromptArgumentType::Boolean);
    /// ```
    #[must_use]
    pub fn typed_argument(
        mut self,
        name: impl Into<ArgName>,
        description: impl Into<String>,
        required: bool,
        arg_type: PromptArgumentType,
    ) -> Self {
        self.arguments.insert(
            name.into(),
            ArgumentSpec {
                description: description.into(),
                required,
                arg_type: Some(arg_type),
            },
        );
        self
    }

    /// Add a workflow step (chainable)
    ///
    /// # Example
    /// ```
    /// use pmcp::server::workflow::{SequentialWorkflow, WorkflowStep, ToolHandle};
    ///
    /// let workflow = SequentialWorkflow::new("workflow", "description")
    ///     .step(WorkflowStep::new("step1", ToolHandle::new("create_content")));
    /// ```
    #[must_use]
    pub fn step(mut self, step: WorkflowStep) -> Self {
        self.steps.push(step);
        self
    }

    /// Add an instruction message (chainable)
    ///
    /// # Example
    /// ```
    /// use pmcp::server::workflow::{SequentialWorkflow, InternalPromptMessage};
    ///
    /// let workflow = SequentialWorkflow::new("workflow", "description")
    ///     .instruction(InternalPromptMessage::system("Process the content carefully"));
    /// ```
    #[must_use]
    pub fn instruction(mut self, message: InternalPromptMessage) -> Self {
        self.instructions.push(message);
        self
    }

    /// Enable task support for this workflow.
    ///
    /// When task support is enabled and a task router is configured on the server
    /// (via [`ServerCoreBuilder::with_task_store()`](crate::server::builder::ServerCoreBuilder::with_task_store)),
    /// invoking this workflow prompt will create a task and track step progress
    /// in task variables.
    ///
    /// If task support is enabled but no task router is configured, the builder
    /// will return an error at build time.
    ///
    /// # Example
    /// ```
    /// use pmcp::server::workflow::{SequentialWorkflow, WorkflowStep, ToolHandle};
    ///
    /// let workflow = SequentialWorkflow::new("deploy", "Deploy a service")
    ///     .step(WorkflowStep::new("validate", ToolHandle::new("validate_config")))
    ///     .step(WorkflowStep::new("deploy", ToolHandle::new("deploy_service")))
    ///     .with_task_support(true);
    ///
    /// assert!(workflow.has_task_support());
    /// ```
    #[must_use]
    pub fn with_task_support(mut self, enabled: bool) -> Self {
        self.task_support = enabled;
        self
    }

    /// Returns whether this workflow has task support enabled.
    pub fn has_task_support(&self) -> bool {
        self.task_support
    }

    /// Get workflow name
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Get workflow description
    pub fn description(&self) -> &str {
        &self.description
    }

    /// Get arguments
    pub fn arguments(&self) -> &IndexMap<ArgName, ArgumentSpec> {
        &self.arguments
    }

    /// Get steps
    pub fn steps(&self) -> &[WorkflowStep] {
        &self.steps
    }

    /// Get instructions
    pub fn instructions(&self) -> &[InternalPromptMessage] {
        &self.instructions
    }

    /// Validate the workflow
    ///
    /// Checks:
    /// - All steps reference valid bindings
    /// - No circular dependencies
    /// - All prompt arguments referenced by steps are defined
    ///
    /// # Binding behavior
    /// Steps can only be referenced by their explicit binding names set via `.bind()`.
    /// Steps without bindings cannot have their outputs referenced by later steps.
    pub fn validate(&self) -> Result<(), WorkflowError> {
        let mut available_bindings = Vec::new();

        // Validate each step in sequence
        for step in &self.steps {
            // Validate step can access required bindings
            step.validate(&available_bindings)?;

            // Add this step's binding to available bindings (if it has one)
            // Only explicit bindings can be referenced by later steps
            if let Some(binding) = step.binding() {
                available_bindings.push(binding.clone());
            }
        }

        // Validate all prompt arguments referenced in steps are defined
        for step in &self.steps {
            for (_, source) in step.arguments() {
                if let super::data_source::DataSource::PromptArg(arg_name) = source {
                    if !self.arguments.contains_key(arg_name) {
                        return Err(WorkflowError::InvalidMapping {
                            step: step.name().to_string(),
                            reason: format!("References undefined prompt argument '{}'", arg_name),
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Get all bindings that will be available after executing all steps
    pub fn output_bindings(&self) -> Vec<BindingName> {
        self.steps
            .iter()
            .filter_map(|step| step.binding().cloned())
            .collect()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::server::workflow::{dsl::*, ToolHandle};
    use serde_json::json;

    #[test]
    fn test_sequential_workflow_creation() {
        let workflow = SequentialWorkflow::new("content_workflow", "Create content");
        assert_eq!(workflow.name(), "content_workflow");
        assert_eq!(workflow.description(), "Create content");
        assert!(workflow.arguments().is_empty());
        assert!(workflow.steps().is_empty());
    }

    #[test]
    fn test_sequential_workflow_with_arguments() {
        let workflow = SequentialWorkflow::new("workflow", "description")
            .argument("topic", "The topic", true)
            .argument("style", "Writing style", false);

        assert_eq!(workflow.arguments().len(), 2);
        assert!(workflow.arguments().contains_key(&ArgName::new("topic")));
        assert!(workflow.arguments().contains_key(&ArgName::new("style")));
    }

    #[test]
    fn test_sequential_workflow_with_steps() {
        let workflow = SequentialWorkflow::new("workflow", "description")
            .step(WorkflowStep::new("step1", ToolHandle::new("create")).bind("content"))
            .step(WorkflowStep::new("step2", ToolHandle::new("review")).bind("review"));

        assert_eq!(workflow.steps().len(), 2);
    }

    #[test]
    fn test_sequential_workflow_with_instructions() {
        let workflow = SequentialWorkflow::new("workflow", "description")
            .instruction(InternalPromptMessage::system("Be concise"))
            .instruction(InternalPromptMessage::system("Be accurate"));

        assert_eq!(workflow.instructions().len(), 2);
    }

    #[test]
    fn test_sequential_workflow_validation_success() {
        let workflow = SequentialWorkflow::new("workflow", "description")
            .argument("topic", "The topic", true)
            .step(
                WorkflowStep::new("step1", ToolHandle::new("create"))
                    .arg("topic", prompt_arg("topic"))
                    .bind("content"),
            )
            .step(
                WorkflowStep::new("step2", ToolHandle::new("review"))
                    .arg("content", from_step("content"))  // Reference binding, not step name
                    .bind("review"),
            );

        assert!(workflow.validate().is_ok());
    }

    #[test]
    fn test_sequential_workflow_validation_unknown_binding() {
        let workflow = SequentialWorkflow::new("workflow", "description").step(
            WorkflowStep::new("step1", ToolHandle::new("review"))
                .arg("content", from_step("nonexistent")),
        );

        let result = workflow.validate();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            WorkflowError::UnknownBinding { .. }
        ));
    }

    #[test]
    fn test_sequential_workflow_validation_undefined_prompt_arg() {
        let workflow = SequentialWorkflow::new("workflow", "description").step(
            WorkflowStep::new("step1", ToolHandle::new("create"))
                .arg("topic", prompt_arg("undefined_arg")),
        );

        let result = workflow.validate();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            WorkflowError::InvalidMapping { .. }
        ));
    }

    #[test]
    fn test_sequential_workflow_output_bindings() {
        let workflow = SequentialWorkflow::new("workflow", "description")
            .step(WorkflowStep::new("step1", ToolHandle::new("create")).bind("content"))
            .step(WorkflowStep::new("step2", ToolHandle::new("review")).bind("review"))
            .step(
                WorkflowStep::new("step3", ToolHandle::new("format")), // No binding
            );

        let bindings = workflow.output_bindings();
        assert_eq!(bindings.len(), 2);
        assert_eq!(bindings[0].as_str(), "content");
        assert_eq!(bindings[1].as_str(), "review");
    }

    #[test]
    fn test_sequential_workflow_complete_example() {
        let workflow =
            SequentialWorkflow::new("content_creation", "Create, review, and publish content")
                .argument("topic", "The topic to write about", true)
                .argument("target_audience", "Target audience", false)
                .instruction(InternalPromptMessage::system(
                    "Create high-quality content following these steps",
                ))
                .step(
                    WorkflowStep::new("create", ToolHandle::new("create_content"))
                        .arg("topic", prompt_arg("topic"))
                        .arg("audience", prompt_arg("target_audience"))
                        .bind("draft"),
                )
                .step(
                    WorkflowStep::new("review", ToolHandle::new("review_content"))
                        .arg("content", from_step("draft"))  // Reference binding name
                        .arg("criteria", constant(json!(["grammar", "clarity", "tone"])))
                        .bind("review_result"),
                )
                .step(
                    WorkflowStep::new("publish", ToolHandle::new("publish_content"))
                        .arg("content", field("draft", "text"))  // Reference binding name
                        .arg("metadata", field("review_result", "metadata")), // Reference binding name
                );

        assert!(workflow.validate().is_ok());
        assert_eq!(workflow.arguments().len(), 2);
        assert_eq!(workflow.steps().len(), 3);
        assert_eq!(workflow.instructions().len(), 1);
    }

    #[test]
    fn test_sequential_workflow_clone() {
        let workflow = SequentialWorkflow::new("workflow", "description")
            .argument("arg", "description", true)
            .step(WorkflowStep::new("step1", ToolHandle::new("tool")));

        let cloned = workflow.clone();
        assert_eq!(cloned.name(), workflow.name());
        assert_eq!(cloned.arguments().len(), workflow.arguments().len());
    }

    #[test]
    fn test_sequential_workflow_is_send_sync() {
        fn assert_send_sync<T: Send + Sync>() {}
        assert_send_sync::<SequentialWorkflow>();
    }

    #[test]
    fn test_argument_spec_required() {
        let spec = ArgumentSpec {
            description: "Test arg".to_string(),
            required: true,
            arg_type: None,
        };
        assert!(spec.required);
    }

    #[test]
    fn test_argument_spec_optional() {
        let spec = ArgumentSpec {
            description: "Test arg".to_string(),
            required: false,
            arg_type: None,
        };
        assert!(!spec.required);
    }

    #[test]
    fn test_task_support_defaults_to_false() {
        let workflow = SequentialWorkflow::new("workflow", "description");
        assert!(!workflow.has_task_support());
    }

    #[test]
    fn test_with_task_support_enabled() {
        let workflow = SequentialWorkflow::new("workflow", "description").with_task_support(true);
        assert!(workflow.has_task_support());
    }

    #[test]
    fn test_with_task_support_disabled() {
        let workflow = SequentialWorkflow::new("workflow", "description")
            .with_task_support(true)
            .with_task_support(false);
        assert!(!workflow.has_task_support());
    }

    #[test]
    fn test_task_support_preserved_on_clone() {
        let workflow = SequentialWorkflow::new("workflow", "description").with_task_support(true);
        let cloned = workflow.clone();
        assert!(cloned.has_task_support());
    }

    #[test]
    fn test_sequential_workflow_step_without_binding_cannot_be_referenced() {
        // Step without binding cannot be referenced
        let workflow = SequentialWorkflow::new("workflow", "description")
            .step(
                WorkflowStep::new("step1", ToolHandle::new("create")), // No .bind() - output cannot be referenced
            )
            .step(
                WorkflowStep::new("step2", ToolHandle::new("review"))
                    .arg("content", from_step("step1")), // Try to reference step1
            );

        let result = workflow.validate();
        assert!(result.is_err());
        assert!(matches!(
            result.unwrap_err(),
            WorkflowError::UnknownBinding { .. }
        ));
    }
}