Skip to main content

systemprompt_models/a2a/
task_metadata.rs

1//! Lifecycle and accounting metadata for A2A tasks.
2//!
3//! [`TaskMetadata`] distinguishes the two [`TaskType`] flavours (MCP tool
4//! execution versus agent message), tracks timing and token usage, and carries
5//! an open-ended `extensions` map flattened into the serialized form. The
6//! `new_validated_*` constructors enforce the required-field contract before a
7//! task is recorded.
8//!
9//! Copyright (c) systemprompt.io — Business Source License 1.1.
10//! See <https://systemprompt.io> for licensing details.
11
12use chrono::Utc;
13use serde::{Deserialize, Serialize};
14use systemprompt_traits::validation::{
15    MetadataValidation, Validate, ValidationError, ValidationResult,
16};
17
18use crate::execution::ExecutionStep;
19
20pub mod agent_names {
21    pub const SYSTEM: &str = "system";
22}
23
24#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq, Hash)]
25#[serde(rename_all = "snake_case")]
26pub enum TaskType {
27    McpExecution,
28    AgentMessage,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
32pub struct TaskMetadata {
33    pub task_type: TaskType,
34    pub agent_name: String,
35    pub created_at: String,
36    #[serde(skip_serializing_if = "Option::is_none")]
37    pub updated_at: Option<String>,
38    #[serde(skip_serializing_if = "Option::is_none")]
39    pub started_at: Option<String>,
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub completed_at: Option<String>,
42    #[serde(skip_serializing_if = "Option::is_none")]
43    pub execution_time_ms: Option<i64>,
44    #[serde(skip_serializing_if = "Option::is_none")]
45    pub tool_name: Option<String>,
46    #[serde(skip_serializing_if = "Option::is_none")]
47    pub mcp_server_name: Option<String>,
48    #[serde(skip_serializing_if = "Option::is_none")]
49    pub input_tokens: Option<u32>,
50    #[serde(skip_serializing_if = "Option::is_none")]
51    pub output_tokens: Option<u32>,
52    #[serde(skip_serializing_if = "Option::is_none")]
53    pub model: Option<String>,
54    #[serde(rename = "executionSteps", skip_serializing_if = "Option::is_none")]
55    pub execution_steps: Option<Vec<ExecutionStep>>,
56    #[serde(flatten, default)]
57    pub extensions: serde_json::Map<String, serde_json::Value>,
58}
59
60impl TaskMetadata {
61    pub fn new_mcp_execution(
62        agent_name: String,
63        tool_name: String,
64        mcp_server_name: String,
65    ) -> Self {
66        Self {
67            task_type: TaskType::McpExecution,
68            agent_name,
69            tool_name: Some(tool_name),
70            mcp_server_name: Some(mcp_server_name),
71            created_at: Utc::now().to_rfc3339(),
72            updated_at: None,
73            started_at: None,
74            completed_at: None,
75            execution_time_ms: None,
76            input_tokens: None,
77            output_tokens: None,
78            model: None,
79            execution_steps: None,
80            extensions: serde_json::Map::new(),
81        }
82    }
83
84    pub fn new_agent_message(agent_name: String) -> Self {
85        Self {
86            task_type: TaskType::AgentMessage,
87            agent_name,
88            tool_name: None,
89            mcp_server_name: None,
90            created_at: Utc::now().to_rfc3339(),
91            updated_at: None,
92            started_at: None,
93            completed_at: None,
94            execution_time_ms: None,
95            input_tokens: None,
96            output_tokens: None,
97            model: None,
98            execution_steps: None,
99            extensions: serde_json::Map::new(),
100        }
101    }
102
103    pub const fn with_token_usage(mut self, input_tokens: u32, output_tokens: u32) -> Self {
104        self.input_tokens = Some(input_tokens);
105        self.output_tokens = Some(output_tokens);
106        self
107    }
108
109    pub fn with_model(mut self, model: impl Into<String>) -> Self {
110        self.model = Some(model.into());
111        self
112    }
113
114    pub fn with_updated_at(mut self) -> Self {
115        self.updated_at = Some(Utc::now().to_rfc3339());
116        self
117    }
118
119    pub fn with_tool_name(mut self, tool_name: impl Into<String>) -> Self {
120        self.tool_name = Some(tool_name.into());
121        self
122    }
123
124    pub fn with_execution_steps(mut self, steps: Vec<ExecutionStep>) -> Self {
125        self.execution_steps = Some(steps);
126        self
127    }
128
129    pub fn with_extension(mut self, key: String, value: serde_json::Value) -> Self {
130        self.extensions.insert(key, value);
131        self
132    }
133
134    pub fn new_validated_agent_message(agent_name: String) -> ValidationResult<Self> {
135        if agent_name.is_empty() {
136            return Err(ValidationError::new(
137                "agent_name",
138                "Cannot create TaskMetadata: agent_name is empty",
139            )
140            .with_context(format!("agent_name={agent_name:?}")));
141        }
142
143        let metadata = Self::new_agent_message(agent_name);
144        metadata.validate()?;
145        Ok(metadata)
146    }
147
148    pub fn new_validated_mcp_execution(
149        agent_name: String,
150        tool_name: String,
151        mcp_server_name: String,
152    ) -> ValidationResult<Self> {
153        if agent_name.is_empty() {
154            return Err(ValidationError::new(
155                "agent_name",
156                "Cannot create TaskMetadata: agent_name is empty",
157            )
158            .with_context(format!("agent_name={agent_name:?}")));
159        }
160
161        if tool_name.is_empty() {
162            return Err(ValidationError::new(
163                "tool_name",
164                "Cannot create TaskMetadata: tool_name is empty for MCP execution",
165            )
166            .with_context(format!("tool_name={tool_name:?}")));
167        }
168
169        let metadata = Self::new_mcp_execution(agent_name, tool_name, mcp_server_name);
170        metadata.validate()?;
171        Ok(metadata)
172    }
173}
174
175impl Validate for TaskMetadata {
176    fn validate(&self) -> ValidationResult<()> {
177        self.validate_required_fields()?;
178        Ok(())
179    }
180}
181
182impl MetadataValidation for TaskMetadata {
183    fn required_string_fields(&self) -> Vec<(&'static str, &str)> {
184        vec![
185            ("agent_name", &self.agent_name),
186            ("created_at", &self.created_at),
187        ]
188    }
189}