a2a_protocol_server/request_context.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F.
3
4//! Request context passed to the [`AgentExecutor`](crate::AgentExecutor).
5//!
6//! [`RequestContext`] bundles together the incoming message, task identifiers,
7//! and any previously stored task snapshot so that the executor has all the
8//! information it needs to process a request.
9
10use a2a_protocol_types::message::Message;
11use a2a_protocol_types::task::{Task, TaskId};
12use tokio_util::sync::CancellationToken;
13
14/// Context for a single agent execution request.
15///
16/// Built by the [`RequestHandler`](crate::RequestHandler) and passed to
17/// [`AgentExecutor::execute`](crate::AgentExecutor::execute).
18///
19/// The [`cancellation_token`](Self::cancellation_token) allows executors to
20/// observe cancellation requests and abort work cooperatively.
21#[derive(Debug, Clone)]
22pub struct RequestContext {
23 /// The incoming user message.
24 pub message: Message,
25
26 /// The task identifier for this execution.
27 pub task_id: TaskId,
28
29 /// The conversation context identifier.
30 pub context_id: String,
31
32 /// The previously stored task snapshot, if this is a continuation.
33 pub stored_task: Option<Task>,
34
35 /// Arbitrary metadata from the request.
36 pub metadata: Option<serde_json::Value>,
37
38 /// Cancellation token for cooperative task cancellation.
39 ///
40 /// Executors should check [`CancellationToken::is_cancelled`] or
41 /// `.cancelled().await` to stop work when the task is cancelled.
42 pub cancellation_token: CancellationToken,
43}
44
45impl RequestContext {
46 /// Creates a new [`RequestContext`].
47 #[must_use]
48 pub fn new(message: Message, task_id: TaskId, context_id: String) -> Self {
49 Self {
50 message,
51 task_id,
52 context_id,
53 stored_task: None,
54 metadata: None,
55 cancellation_token: CancellationToken::new(),
56 }
57 }
58
59 /// Sets the stored task snapshot for continuation requests.
60 #[must_use]
61 pub fn with_stored_task(mut self, task: Task) -> Self {
62 self.stored_task = Some(task);
63 self
64 }
65
66 /// Sets request metadata.
67 #[must_use]
68 pub fn with_metadata(mut self, metadata: serde_json::Value) -> Self {
69 self.metadata = Some(metadata);
70 self
71 }
72}