agent_client_protocol_schema/agent.rs
1//! Methods and notifications the agent handles/receives.
2//!
3//! This module defines the Agent trait and all associated types for implementing
4//! an AI coding agent that follows the Agent Client Protocol (ACP).
5
6use std::{path::PathBuf, sync::Arc};
7
8use derive_more::{Display, From};
9use schemars::JsonSchema;
10use serde::{Deserialize, Serialize};
11use serde_json::value::RawValue;
12
13use crate::ext::ExtRequest;
14use crate::{ClientCapabilities, ContentBlock, ExtNotification, ProtocolVersion, SessionId};
15
16// Initialize
17
18/// Request parameters for the initialize method.
19///
20/// Sent by the client to establish connection and negotiate capabilities.
21///
22/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
23#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
24#[schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME))]
25#[serde(rename_all = "camelCase")]
26pub struct InitializeRequest {
27 /// The latest protocol version supported by the client.
28 pub protocol_version: ProtocolVersion,
29 /// Capabilities supported by the client.
30 #[serde(default)]
31 pub client_capabilities: ClientCapabilities,
32 /// Information about the Client name and version sent to the Agent.
33 ///
34 /// Note: in future versions of the protocol, this will be required.
35 #[serde(skip_serializing_if = "Option::is_none")]
36 pub client_info: Option<Implementation>,
37 /// Extension point for implementations
38 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
39 pub meta: Option<serde_json::Value>,
40}
41
42/// Response from the initialize method.
43///
44/// Contains the negotiated protocol version and agent capabilities.
45///
46/// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
47#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
48#[schemars(extend("x-side" = "agent", "x-method" = INITIALIZE_METHOD_NAME))]
49#[serde(rename_all = "camelCase")]
50pub struct InitializeResponse {
51 /// The protocol version the client specified if supported by the agent,
52 /// or the latest protocol version supported by the agent.
53 ///
54 /// The client should disconnect, if it doesn't support this version.
55 pub protocol_version: ProtocolVersion,
56 /// Capabilities supported by the agent.
57 #[serde(default)]
58 pub agent_capabilities: AgentCapabilities,
59 /// Authentication methods supported by the agent.
60 #[serde(default)]
61 pub auth_methods: Vec<AuthMethod>,
62 /// Information about the Agent name and version sent to the Client.
63 ///
64 /// Note: in future versions of the protocol, this will be required.
65 #[serde(skip_serializing_if = "Option::is_none")]
66 pub agent_info: Option<Implementation>,
67 /// Extension point for implementations
68 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
69 pub meta: Option<serde_json::Value>,
70}
71
72/// Describes the name and version of an MCP implementation, with an optional
73/// title for UI representation.
74#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
75#[serde(rename_all = "camelCase")]
76pub struct Implementation {
77 /// Intended for programmatic or logical use, but can be used as a display
78 /// name fallback if title isn’t present.
79 name: String,
80 /// Intended for UI and end-user contexts — optimized to be human-readable
81 /// and easily understood.
82 ///
83 /// If not provided, the name should be used for display.
84 title: Option<String>,
85 /// Version of the implementation. Can be displayed to the user or used
86 /// for debugging or metrics purposes.
87 version: String,
88}
89
90// Authentication
91
92/// Request parameters for the authenticate method.
93///
94/// Specifies which authentication method to use.
95#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
96#[schemars(extend("x-side" = "agent", "x-method" = AUTHENTICATE_METHOD_NAME))]
97#[serde(rename_all = "camelCase")]
98pub struct AuthenticateRequest {
99 /// The ID of the authentication method to use.
100 /// Must be one of the methods advertised in the initialize response.
101 pub method_id: AuthMethodId,
102 /// Extension point for implementations
103 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
104 pub meta: Option<serde_json::Value>,
105}
106
107/// Response to authenticate method
108#[derive(Default, Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
109#[serde(rename_all = "camelCase")]
110#[schemars(extend("x-side" = "agent", "x-method" = AUTHENTICATE_METHOD_NAME))]
111pub struct AuthenticateResponse {
112 /// Extension point for implementations
113 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
114 pub meta: Option<serde_json::Value>,
115}
116
117/// Unique identifier for an authentication method.
118#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Hash, Display, From)]
119#[serde(transparent)]
120#[from(Arc<str>, String, &'static str)]
121pub struct AuthMethodId(pub Arc<str>);
122
123/// Describes an available authentication method.
124#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
125#[serde(rename_all = "camelCase")]
126pub struct AuthMethod {
127 /// Unique identifier for this authentication method.
128 pub id: AuthMethodId,
129 /// Human-readable name of the authentication method.
130 pub name: String,
131 /// Optional description providing more details about this authentication method.
132 pub description: Option<String>,
133 /// Extension point for implementations
134 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
135 pub meta: Option<serde_json::Value>,
136}
137
138// New session
139
140/// Request parameters for creating a new session.
141///
142/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)
143#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
144#[schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME))]
145#[serde(rename_all = "camelCase")]
146pub struct NewSessionRequest {
147 /// The working directory for this session. Must be an absolute path.
148 pub cwd: PathBuf,
149 /// List of MCP (Model Context Protocol) servers the agent should connect to.
150 pub mcp_servers: Vec<McpServer>,
151 /// Extension point for implementations
152 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
153 pub meta: Option<serde_json::Value>,
154}
155
156/// Response from creating a new session.
157///
158/// See protocol docs: [Creating a Session](https://agentclientprotocol.com/protocol/session-setup#creating-a-session)
159#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
160#[schemars(extend("x-side" = "agent", "x-method" = SESSION_NEW_METHOD_NAME))]
161#[serde(rename_all = "camelCase")]
162pub struct NewSessionResponse {
163 /// Unique identifier for the created session.
164 ///
165 /// Used in all subsequent requests for this conversation.
166 pub session_id: SessionId,
167 /// Initial mode state if supported by the Agent
168 ///
169 /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
170 #[serde(default, skip_serializing_if = "Option::is_none")]
171 pub modes: Option<SessionModeState>,
172 /// **UNSTABLE**
173 ///
174 /// This capability is not part of the spec yet, and may be removed or changed at any point.
175 ///
176 /// Initial model state if supported by the Agent
177 #[cfg(feature = "unstable")]
178 #[serde(default, skip_serializing_if = "Option::is_none")]
179 pub models: Option<SessionModelState>,
180 /// Extension point for implementations
181 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
182 pub meta: Option<serde_json::Value>,
183}
184
185// Load session
186
187/// Request parameters for loading an existing session.
188///
189/// Only available if the Agent supports the `loadSession` capability.
190///
191/// See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)
192#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
193#[schemars(extend("x-side" = "agent", "x-method" = SESSION_LOAD_METHOD_NAME))]
194#[serde(rename_all = "camelCase")]
195pub struct LoadSessionRequest {
196 /// List of MCP servers to connect to for this session.
197 pub mcp_servers: Vec<McpServer>,
198 /// The working directory for this session.
199 pub cwd: PathBuf,
200 /// The ID of the session to load.
201 pub session_id: SessionId,
202 /// Extension point for implementations
203 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
204 pub meta: Option<serde_json::Value>,
205}
206
207/// Response from loading an existing session.
208#[derive(Default, Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
209#[schemars(extend("x-side" = "agent", "x-method" = SESSION_LOAD_METHOD_NAME))]
210#[serde(rename_all = "camelCase")]
211pub struct LoadSessionResponse {
212 /// Initial mode state if supported by the Agent
213 ///
214 /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
215 #[serde(default, skip_serializing_if = "Option::is_none")]
216 pub modes: Option<SessionModeState>,
217 /// **UNSTABLE**
218 ///
219 /// This capability is not part of the spec yet, and may be removed or changed at any point.
220 ///
221 /// Initial model state if supported by the Agent
222 #[cfg(feature = "unstable")]
223 #[serde(default, skip_serializing_if = "Option::is_none")]
224 pub models: Option<SessionModelState>,
225 /// Extension point for implementations
226 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
227 pub meta: Option<serde_json::Value>,
228}
229
230// Session modes
231
232/// The set of modes and the one currently active.
233#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
234#[serde(rename_all = "camelCase")]
235pub struct SessionModeState {
236 /// The current mode the Agent is in.
237 pub current_mode_id: SessionModeId,
238 /// The set of modes that the Agent can operate in
239 pub available_modes: Vec<SessionMode>,
240 /// Extension point for implementations
241 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
242 pub meta: Option<serde_json::Value>,
243}
244
245/// A mode the agent can operate in.
246///
247/// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
248#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
249#[serde(rename_all = "camelCase")]
250pub struct SessionMode {
251 pub id: SessionModeId,
252 pub name: String,
253 #[serde(default, skip_serializing_if = "Option::is_none")]
254 pub description: Option<String>,
255 /// Extension point for implementations
256 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
257 pub meta: Option<serde_json::Value>,
258}
259
260/// Unique identifier for a Session Mode.
261#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Hash)]
262#[serde(transparent)]
263pub struct SessionModeId(pub Arc<str>);
264
265impl std::fmt::Display for SessionModeId {
266 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
267 write!(f, "{}", self.0)
268 }
269}
270
271/// Request parameters for setting a session mode.
272#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
273#[schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_MODE_METHOD_NAME))]
274#[serde(rename_all = "camelCase")]
275pub struct SetSessionModeRequest {
276 /// The ID of the session to set the mode for.
277 pub session_id: SessionId,
278 /// The ID of the mode to set.
279 pub mode_id: SessionModeId,
280 /// Extension point for implementations
281 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
282 pub meta: Option<serde_json::Value>,
283}
284
285/// Response to `session/set_mode` method.
286#[derive(Default, Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
287#[schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_MODE_METHOD_NAME))]
288#[serde(rename_all = "camelCase")]
289pub struct SetSessionModeResponse {
290 pub meta: Option<serde_json::Value>,
291}
292
293// MCP
294
295/// Configuration for connecting to an MCP (Model Context Protocol) server.
296///
297/// MCP servers provide tools and context that the agent can use when
298/// processing prompts.
299///
300/// See protocol docs: [MCP Servers](https://agentclientprotocol.com/protocol/session-setup#mcp-servers)
301#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
302#[serde(tag = "type", rename_all = "snake_case")]
303pub enum McpServer {
304 /// HTTP transport configuration
305 ///
306 /// Only available when the Agent capabilities indicate `mcp_capabilities.http` is `true`.
307 #[serde(rename_all = "camelCase")]
308 Http {
309 /// Human-readable name identifying this MCP server.
310 name: String,
311 /// URL to the MCP server.
312 url: String,
313 /// HTTP headers to set when making requests to the MCP server.
314 headers: Vec<HttpHeader>,
315 },
316 /// SSE transport configuration
317 ///
318 /// Only available when the Agent capabilities indicate `mcp_capabilities.sse` is `true`.
319 #[serde(rename_all = "camelCase")]
320 Sse {
321 /// Human-readable name identifying this MCP server.
322 name: String,
323 /// URL to the MCP server.
324 url: String,
325 /// HTTP headers to set when making requests to the MCP server.
326 headers: Vec<HttpHeader>,
327 },
328 /// Stdio transport configuration
329 ///
330 /// All Agents MUST support this transport.
331 #[serde(untagged, rename_all = "camelCase")]
332 Stdio {
333 /// Human-readable name identifying this MCP server.
334 name: String,
335 /// Path to the MCP server executable.
336 command: PathBuf,
337 /// Command-line arguments to pass to the MCP server.
338 args: Vec<String>,
339 /// Environment variables to set when launching the MCP server.
340 env: Vec<EnvVariable>,
341 },
342}
343
344/// An environment variable to set when launching an MCP server.
345#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
346#[serde(rename_all = "camelCase")]
347pub struct EnvVariable {
348 /// The name of the environment variable.
349 pub name: String,
350 /// The value to set for the environment variable.
351 pub value: String,
352 /// Extension point for implementations
353 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
354 pub meta: Option<serde_json::Value>,
355}
356
357/// An HTTP header to set when making requests to the MCP server.
358#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
359#[serde(rename_all = "camelCase")]
360pub struct HttpHeader {
361 /// The name of the HTTP header.
362 pub name: String,
363 /// The value to set for the HTTP header.
364 pub value: String,
365 /// Extension point for implementations
366 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
367 pub meta: Option<serde_json::Value>,
368}
369
370// Prompt
371
372/// Request parameters for sending a user prompt to the agent.
373///
374/// Contains the user's message and any additional context.
375///
376/// See protocol docs: [User Message](https://agentclientprotocol.com/protocol/prompt-turn#1-user-message)
377#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq)]
378#[schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME))]
379#[serde(rename_all = "camelCase")]
380pub struct PromptRequest {
381 /// The ID of the session to send this user message to
382 pub session_id: SessionId,
383 /// The blocks of content that compose the user's message.
384 ///
385 /// As a baseline, the Agent MUST support [`ContentBlock::Text`] and [`ContentBlock::ResourceLink`],
386 /// while other variants are optionally enabled via [`PromptCapabilities`].
387 ///
388 /// The Client MUST adapt its interface according to [`PromptCapabilities`].
389 ///
390 /// The client MAY include referenced pieces of context as either
391 /// [`ContentBlock::Resource`] or [`ContentBlock::ResourceLink`].
392 ///
393 /// When available, [`ContentBlock::Resource`] is preferred
394 /// as it avoids extra round-trips and allows the message to include
395 /// pieces of context from sources the agent may not have access to.
396 pub prompt: Vec<ContentBlock>,
397 /// Extension point for implementations
398 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
399 pub meta: Option<serde_json::Value>,
400}
401
402/// Response from processing a user prompt.
403///
404/// See protocol docs: [Check for Completion](https://agentclientprotocol.com/protocol/prompt-turn#4-check-for-completion)
405#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
406#[schemars(extend("x-side" = "agent", "x-method" = SESSION_PROMPT_METHOD_NAME))]
407#[serde(rename_all = "camelCase")]
408pub struct PromptResponse {
409 /// Indicates why the agent stopped processing the turn.
410 pub stop_reason: StopReason,
411 /// Extension point for implementations
412 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
413 pub meta: Option<serde_json::Value>,
414}
415
416/// Reasons why an agent stops processing a prompt turn.
417///
418/// See protocol docs: [Stop Reasons](https://agentclientprotocol.com/protocol/prompt-turn#stop-reasons)
419#[derive(Debug, Copy, Clone, Eq, PartialEq, Serialize, Deserialize, JsonSchema)]
420#[serde(rename_all = "snake_case")]
421pub enum StopReason {
422 /// The turn ended successfully.
423 EndTurn,
424 /// The turn ended because the agent reached the maximum number of tokens.
425 MaxTokens,
426 /// The turn ended because the agent reached the maximum number of allowed
427 /// agent requests between user turns.
428 MaxTurnRequests,
429 /// The turn ended because the agent refused to continue. The user prompt
430 /// and everything that comes after it won't be included in the next
431 /// prompt, so this should be reflected in the UI.
432 Refusal,
433 /// The turn was cancelled by the client via `session/cancel`.
434 ///
435 /// This stop reason MUST be returned when the client sends a `session/cancel`
436 /// notification, even if the cancellation causes exceptions in underlying operations.
437 /// Agents should catch these exceptions and return this semantically meaningful
438 /// response to confirm successful cancellation.
439 Cancelled,
440}
441
442// Model
443
444/// **UNSTABLE**
445///
446/// This capability is not part of the spec yet, and may be removed or changed at any point.
447///
448/// The set of models and the one currently active.
449#[cfg(feature = "unstable")]
450#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
451#[serde(rename_all = "camelCase")]
452pub struct SessionModelState {
453 /// The current model the Agent is in.
454 pub current_model_id: ModelId,
455 /// The set of models that the Agent can use
456 pub available_models: Vec<ModelInfo>,
457 /// Extension point for implementations
458 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
459 pub meta: Option<serde_json::Value>,
460}
461
462/// **UNSTABLE**
463///
464/// This capability is not part of the spec yet, and may be removed or changed at any point.
465///
466/// A unique identifier for a model.
467#[cfg(feature = "unstable")]
468#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq, Hash, Display, From)]
469#[serde(transparent)]
470#[from(Arc<str>, String, &'static str)]
471pub struct ModelId(pub Arc<str>);
472
473/// **UNSTABLE**
474///
475/// This capability is not part of the spec yet, and may be removed or changed at any point.
476///
477/// Information about a selectable model.
478#[cfg(feature = "unstable")]
479#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
480#[serde(rename_all = "camelCase")]
481pub struct ModelInfo {
482 /// Unique identifier for the model.
483 pub model_id: ModelId,
484 /// Human-readable name of the model.
485 pub name: String,
486 /// Optional description of the model.
487 #[serde(default, skip_serializing_if = "Option::is_none")]
488 pub description: Option<String>,
489 /// Extension point for implementations
490 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
491 pub meta: Option<serde_json::Value>,
492}
493
494/// **UNSTABLE**
495///
496/// This capability is not part of the spec yet, and may be removed or changed at any point.
497///
498/// Request parameters for setting a session model.
499#[cfg(feature = "unstable")]
500#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
501#[schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_MODEL_METHOD_NAME))]
502#[serde(rename_all = "camelCase")]
503pub struct SetSessionModelRequest {
504 /// The ID of the session to set the model for.
505 pub session_id: SessionId,
506 /// The ID of the model to set.
507 pub model_id: ModelId,
508 /// Extension point for implementations
509 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
510 pub meta: Option<serde_json::Value>,
511}
512
513/// **UNSTABLE**
514///
515/// This capability is not part of the spec yet, and may be removed or changed at any point.
516///
517/// Response to `session/set_model` method.
518#[cfg(feature = "unstable")]
519#[derive(Default, Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
520#[schemars(extend("x-side" = "agent", "x-method" = SESSION_SET_MODEL_METHOD_NAME))]
521#[serde(rename_all = "camelCase")]
522pub struct SetSessionModelResponse {
523 /// Extension point for implementations
524 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
525 pub meta: Option<serde_json::Value>,
526}
527
528// Capabilities
529
530/// Capabilities supported by the agent.
531///
532/// Advertised during initialization to inform the client about
533/// available features and content types.
534///
535/// See protocol docs: [Agent Capabilities](https://agentclientprotocol.com/protocol/initialization#agent-capabilities)
536#[derive(Default, Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
537#[serde(rename_all = "camelCase")]
538pub struct AgentCapabilities {
539 /// Whether the agent supports `session/load`.
540 #[serde(default)]
541 pub load_session: bool,
542 /// Prompt capabilities supported by the agent.
543 #[serde(default)]
544 pub prompt_capabilities: PromptCapabilities,
545 /// MCP capabilities supported by the agent.
546 #[serde(default)]
547 pub mcp_capabilities: McpCapabilities,
548 /// Extension point for implementations
549 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
550 pub meta: Option<serde_json::Value>,
551}
552
553/// Prompt capabilities supported by the agent in `session/prompt` requests.
554///
555/// Baseline agent functionality requires support for [`ContentBlock::Text`]
556/// and [`ContentBlock::ResourceLink`] in prompt requests.
557///
558/// Other variants must be explicitly opted in to.
559/// Capabilities for different types of content in prompt requests.
560///
561/// Indicates which content types beyond the baseline (text and resource links)
562/// the agent can process.
563///
564/// See protocol docs: [Prompt Capabilities](https://agentclientprotocol.com/protocol/initialization#prompt-capabilities)
565#[derive(Default, Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
566#[serde(rename_all = "camelCase")]
567pub struct PromptCapabilities {
568 /// Agent supports [`ContentBlock::Image`].
569 #[serde(default)]
570 pub image: bool,
571 /// Agent supports [`ContentBlock::Audio`].
572 #[serde(default)]
573 pub audio: bool,
574 /// Agent supports embedded context in `session/prompt` requests.
575 ///
576 /// When enabled, the Client is allowed to include [`ContentBlock::Resource`]
577 /// in prompt requests for pieces of context that are referenced in the message.
578 #[serde(default)]
579 pub embedded_context: bool,
580 /// Extension point for implementations
581 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
582 pub meta: Option<serde_json::Value>,
583}
584
585/// MCP capabilities supported by the agent
586#[derive(Default, Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
587#[serde(rename_all = "camelCase")]
588pub struct McpCapabilities {
589 /// Agent supports [`McpServer::Http`].
590 #[serde(default)]
591 pub http: bool,
592 /// Agent supports [`McpServer::Sse`].
593 #[serde(default)]
594 pub sse: bool,
595 /// Extension point for implementations
596 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
597 pub meta: Option<serde_json::Value>,
598}
599
600// Method schema
601
602/// Names of all methods that agents handle.
603///
604/// Provides a centralized definition of method names used in the protocol.
605#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
606pub struct AgentMethodNames {
607 /// Method for initializing the connection.
608 pub initialize: &'static str,
609 /// Method for authenticating with the agent.
610 pub authenticate: &'static str,
611 /// Method for creating a new session.
612 pub session_new: &'static str,
613 /// Method for loading an existing session.
614 pub session_load: &'static str,
615 /// Method for setting the mode for a session.
616 pub session_set_mode: &'static str,
617 /// Method for sending a prompt to the agent.
618 pub session_prompt: &'static str,
619 /// Notification for cancelling operations.
620 pub session_cancel: &'static str,
621 /// Method for selecting a model for a given session.
622 #[cfg(feature = "unstable")]
623 pub session_set_model: &'static str,
624}
625
626/// Constant containing all agent method names.
627pub const AGENT_METHOD_NAMES: AgentMethodNames = AgentMethodNames {
628 initialize: INITIALIZE_METHOD_NAME,
629 authenticate: AUTHENTICATE_METHOD_NAME,
630 session_new: SESSION_NEW_METHOD_NAME,
631 session_load: SESSION_LOAD_METHOD_NAME,
632 session_set_mode: SESSION_SET_MODE_METHOD_NAME,
633 session_prompt: SESSION_PROMPT_METHOD_NAME,
634 session_cancel: SESSION_CANCEL_METHOD_NAME,
635 #[cfg(feature = "unstable")]
636 session_set_model: SESSION_SET_MODEL_METHOD_NAME,
637};
638
639/// Method name for the initialize request.
640pub(crate) const INITIALIZE_METHOD_NAME: &str = "initialize";
641/// Method name for the authenticate request.
642pub(crate) const AUTHENTICATE_METHOD_NAME: &str = "authenticate";
643/// Method name for creating a new session.
644pub(crate) const SESSION_NEW_METHOD_NAME: &str = "session/new";
645/// Method name for loading an existing session.
646pub(crate) const SESSION_LOAD_METHOD_NAME: &str = "session/load";
647/// Method name for setting the mode for a session.
648pub(crate) const SESSION_SET_MODE_METHOD_NAME: &str = "session/set_mode";
649/// Method name for sending a prompt.
650pub(crate) const SESSION_PROMPT_METHOD_NAME: &str = "session/prompt";
651/// Method name for the cancel notification.
652pub(crate) const SESSION_CANCEL_METHOD_NAME: &str = "session/cancel";
653/// Method name for selecting a model for a given session.
654#[cfg(feature = "unstable")]
655pub(crate) const SESSION_SET_MODEL_METHOD_NAME: &str = "session/set_model";
656
657/// All possible requests that a client can send to an agent.
658///
659/// This enum is used internally for routing RPC requests. You typically won't need
660/// to use this directly - instead, use the methods on the [`Agent`] trait.
661///
662/// This enum encompasses all method calls from client to agent.
663#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
664#[serde(untagged)]
665#[schemars(extend("x-docs-ignore" = true))]
666pub enum ClientRequest {
667 /// Establishes the connection with a client and negotiates protocol capabilities.
668 ///
669 /// This method is called once at the beginning of the connection to:
670 /// - Negotiate the protocol version to use
671 /// - Exchange capability information between client and agent
672 /// - Determine available authentication methods
673 ///
674 /// The agent should respond with its supported protocol version and capabilities.
675 ///
676 /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
677 InitializeRequest(InitializeRequest),
678 /// Authenticates the client using the specified authentication method.
679 ///
680 /// Called when the agent requires authentication before allowing session creation.
681 /// The client provides the authentication method ID that was advertised during initialization.
682 ///
683 /// After successful authentication, the client can proceed to create sessions with
684 /// `new_session` without receiving an `auth_required` error.
685 ///
686 /// See protocol docs: [Initialization](https://agentclientprotocol.com/protocol/initialization)
687 AuthenticateRequest(AuthenticateRequest),
688 /// Creates a new conversation session with the agent.
689 ///
690 /// Sessions represent independent conversation contexts with their own history and state.
691 ///
692 /// The agent should:
693 /// - Create a new session context
694 /// - Connect to any specified MCP servers
695 /// - Return a unique session ID for future requests
696 ///
697 /// May return an `auth_required` error if the agent requires authentication.
698 ///
699 /// See protocol docs: [Session Setup](https://agentclientprotocol.com/protocol/session-setup)
700 NewSessionRequest(NewSessionRequest),
701 /// Loads an existing session to resume a previous conversation.
702 ///
703 /// This method is only available if the agent advertises the `loadSession` capability.
704 ///
705 /// The agent should:
706 /// - Restore the session context and conversation history
707 /// - Connect to the specified MCP servers
708 /// - Stream the entire conversation history back to the client via notifications
709 ///
710 /// See protocol docs: [Loading Sessions](https://agentclientprotocol.com/protocol/session-setup#loading-sessions)
711 LoadSessionRequest(LoadSessionRequest),
712 /// Sets the current mode for a session.
713 ///
714 /// Allows switching between different agent modes (e.g., "ask", "architect", "code")
715 /// that affect system prompts, tool availability, and permission behaviors.
716 ///
717 /// The mode must be one of the modes advertised in `availableModes` during session
718 /// creation or loading. Agents may also change modes autonomously and notify the
719 /// client via `current_mode_update` notifications.
720 ///
721 /// This method can be called at any time during a session, whether the Agent is
722 /// idle or actively generating a response.
723 ///
724 /// See protocol docs: [Session Modes](https://agentclientprotocol.com/protocol/session-modes)
725 SetSessionModeRequest(SetSessionModeRequest),
726 /// Processes a user prompt within a session.
727 ///
728 /// This method handles the whole lifecycle of a prompt:
729 /// - Receives user messages with optional context (files, images, etc.)
730 /// - Processes the prompt using language models
731 /// - Reports language model content and tool calls to the Clients
732 /// - Requests permission to run tools
733 /// - Executes any requested tool calls
734 /// - Returns when the turn is complete with a stop reason
735 ///
736 /// See protocol docs: [Prompt Turn](https://agentclientprotocol.com/protocol/prompt-turn)
737 PromptRequest(PromptRequest),
738 #[cfg(feature = "unstable")]
739 /// **UNSTABLE**
740 ///
741 /// This capability is not part of the spec yet, and may be removed or changed at any point.
742 ///
743 /// Select a model for a given session.
744 SetSessionModelRequest(SetSessionModelRequest),
745 /// Handles extension method requests from the client.
746 ///
747 /// Extension methods provide a way to add custom functionality while maintaining
748 /// protocol compatibility.
749 ///
750 /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)
751 ExtMethodRequest(ExtRequest),
752}
753
754/// All possible responses that an agent can send to a client.
755///
756/// This enum is used internally for routing RPC responses. You typically won't need
757/// to use this directly - the responses are handled automatically by the connection.
758///
759/// These are responses to the corresponding `ClientRequest` variants.
760#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
761#[serde(untagged)]
762#[schemars(extend("x-docs-ignore" = true))]
763pub enum AgentResponse {
764 InitializeResponse(InitializeResponse),
765 AuthenticateResponse(#[serde(default)] AuthenticateResponse),
766 NewSessionResponse(NewSessionResponse),
767 LoadSessionResponse(#[serde(default)] LoadSessionResponse),
768 SetSessionModeResponse(#[serde(default)] SetSessionModeResponse),
769 PromptResponse(PromptResponse),
770 #[cfg(feature = "unstable")]
771 SetSessionModelResponse(SetSessionModelResponse),
772 ExtMethodResponse(#[schemars(with = "serde_json::Value")] Arc<RawValue>),
773}
774
775/// All possible notifications that a client can send to an agent.
776///
777/// This enum is used internally for routing RPC notifications. You typically won't need
778/// to use this directly - use the notification methods on the [`Agent`] trait instead.
779///
780/// Notifications do not expect a response.
781#[derive(Clone, Debug, Serialize, Deserialize, JsonSchema)]
782#[serde(untagged)]
783#[schemars(extend("x-docs-ignore" = true))]
784pub enum ClientNotification {
785 /// Cancels ongoing operations for a session.
786 ///
787 /// This is a notification sent by the client to cancel an ongoing prompt turn.
788 ///
789 /// Upon receiving this notification, the Agent SHOULD:
790 /// - Stop all language model requests as soon as possible
791 /// - Abort all tool call invocations in progress
792 /// - Send any pending `session/update` notifications
793 /// - Respond to the original `session/prompt` request with `StopReason::Cancelled`
794 ///
795 /// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
796 CancelNotification(CancelNotification),
797 /// Handles extension notifications from the client.
798 ///
799 /// Extension notifications provide a way to send one-way messages for custom functionality
800 /// while maintaining protocol compatibility.
801 ///
802 /// See protocol docs: [Extensibility](https://agentclientprotocol.com/protocol/extensibility)
803 ExtNotification(ExtNotification),
804}
805
806/// Notification to cancel ongoing operations for a session.
807///
808/// See protocol docs: [Cancellation](https://agentclientprotocol.com/protocol/prompt-turn#cancellation)
809#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
810#[schemars(extend("x-side" = "agent", "x-method" = SESSION_CANCEL_METHOD_NAME))]
811#[serde(rename_all = "camelCase")]
812pub struct CancelNotification {
813 /// The ID of the session to cancel operations for.
814 pub session_id: SessionId,
815 /// Extension point for implementations
816 #[serde(skip_serializing_if = "Option::is_none", rename = "_meta")]
817 pub meta: Option<serde_json::Value>,
818}
819
820#[cfg(test)]
821mod test_serialization {
822 use super::*;
823 use serde_json::json;
824
825 #[test]
826 fn test_mcp_server_stdio_serialization() {
827 let server = McpServer::Stdio {
828 name: "test-server".to_string(),
829 command: PathBuf::from("/usr/bin/server"),
830 args: vec!["--port".to_string(), "3000".to_string()],
831 env: vec![EnvVariable {
832 name: "API_KEY".to_string(),
833 value: "secret123".to_string(),
834 meta: None,
835 }],
836 };
837
838 let json = serde_json::to_value(&server).unwrap();
839 assert_eq!(
840 json,
841 json!({
842 "name": "test-server",
843 "command": "/usr/bin/server",
844 "args": ["--port", "3000"],
845 "env": [
846 {
847 "name": "API_KEY",
848 "value": "secret123"
849 }
850 ]
851 })
852 );
853
854 let deserialized: McpServer = serde_json::from_value(json).unwrap();
855 match deserialized {
856 McpServer::Stdio {
857 name,
858 command,
859 args,
860 env,
861 } => {
862 assert_eq!(name, "test-server");
863 assert_eq!(command, PathBuf::from("/usr/bin/server"));
864 assert_eq!(args, vec!["--port", "3000"]);
865 assert_eq!(env.len(), 1);
866 assert_eq!(env[0].name, "API_KEY");
867 assert_eq!(env[0].value, "secret123");
868 }
869 _ => panic!("Expected Stdio variant"),
870 }
871 }
872
873 #[test]
874 fn test_mcp_server_http_serialization() {
875 let server = McpServer::Http {
876 name: "http-server".to_string(),
877 url: "https://api.example.com".to_string(),
878 headers: vec![
879 HttpHeader {
880 name: "Authorization".to_string(),
881 value: "Bearer token123".to_string(),
882 meta: None,
883 },
884 HttpHeader {
885 name: "Content-Type".to_string(),
886 value: "application/json".to_string(),
887 meta: None,
888 },
889 ],
890 };
891
892 let json = serde_json::to_value(&server).unwrap();
893 assert_eq!(
894 json,
895 json!({
896 "type": "http",
897 "name": "http-server",
898 "url": "https://api.example.com",
899 "headers": [
900 {
901 "name": "Authorization",
902 "value": "Bearer token123"
903 },
904 {
905 "name": "Content-Type",
906 "value": "application/json"
907 }
908 ]
909 })
910 );
911
912 let deserialized: McpServer = serde_json::from_value(json).unwrap();
913 match deserialized {
914 McpServer::Http { name, url, headers } => {
915 assert_eq!(name, "http-server");
916 assert_eq!(url, "https://api.example.com");
917 assert_eq!(headers.len(), 2);
918 assert_eq!(headers[0].name, "Authorization");
919 assert_eq!(headers[0].value, "Bearer token123");
920 assert_eq!(headers[1].name, "Content-Type");
921 assert_eq!(headers[1].value, "application/json");
922 }
923 _ => panic!("Expected Http variant"),
924 }
925 }
926
927 #[test]
928 fn test_mcp_server_sse_serialization() {
929 let server = McpServer::Sse {
930 name: "sse-server".to_string(),
931 url: "https://sse.example.com/events".to_string(),
932 headers: vec![HttpHeader {
933 name: "X-API-Key".to_string(),
934 value: "apikey456".to_string(),
935 meta: None,
936 }],
937 };
938
939 let json = serde_json::to_value(&server).unwrap();
940 assert_eq!(
941 json,
942 json!({
943 "type": "sse",
944 "name": "sse-server",
945 "url": "https://sse.example.com/events",
946 "headers": [
947 {
948 "name": "X-API-Key",
949 "value": "apikey456"
950 }
951 ]
952 })
953 );
954
955 let deserialized: McpServer = serde_json::from_value(json).unwrap();
956 match deserialized {
957 McpServer::Sse { name, url, headers } => {
958 assert_eq!(name, "sse-server");
959 assert_eq!(url, "https://sse.example.com/events");
960 assert_eq!(headers.len(), 1);
961 assert_eq!(headers[0].name, "X-API-Key");
962 assert_eq!(headers[0].value, "apikey456");
963 }
964 _ => panic!("Expected Sse variant"),
965 }
966 }
967}