Skip to main content

agent_client_protocol/
util.rs

1// Types re-exported from crate root
2
3use futures::{
4    future::BoxFuture,
5    stream::{Stream, StreamExt},
6};
7
8mod typed;
9pub use typed::{MatchDispatch, MatchDispatchFrom};
10
11/// Format only code-derived metadata at ordinary log levels.
12///
13/// Error messages, data, and even Serde parse reasons can contain private input.
14/// Do not add fields from the original error here, including purported paths
15/// extracted from its text. Full diagnostics belong in opt-in protocol tracing.
16pub(crate) fn redacted_error(code: impl Into<i32>) -> impl std::fmt::Debug {
17    struct RedactedError {
18        code: i32,
19        reason: &'static str,
20    }
21
22    impl std::fmt::Debug for RedactedError {
23        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
24            f.debug_struct("Error")
25                .field("code", &self.code)
26                .field("reason", &self.reason)
27                .finish()
28        }
29    }
30
31    let code = code.into();
32    let reason = match code {
33        -32700 => "Parse error",
34        -32600 => "Invalid request",
35        -32601 => "Method not found",
36        -32602 => "Invalid params",
37        -32603 => "Internal error",
38        _ => "Protocol or application error",
39    };
40    RedactedError { code, reason }
41}
42
43/// Replace every environment variable and header value in a diagnostic copy.
44///
45/// ACP carries credentials in `env` and `headers` fields: MCP server
46/// declarations in session setup, terminal auth methods, terminal creation,
47/// and provider configuration. Names stay visible; values never reach logs.
48/// Fields are matched by name anywhere in the value rather than by method, so
49/// unrelated payloads that happen to use these keys are redacted as well.
50fn redact_env_and_header_values(value: &mut serde_json::Value) {
51    match value {
52        serde_json::Value::Object(object) => {
53            for (key, field) in object.iter_mut() {
54                if key == "env" || key == "headers" {
55                    redact_name_value_pairs(field);
56                }
57                redact_env_and_header_values(field);
58            }
59        }
60        serde_json::Value::Array(values) => {
61            values.iter_mut().for_each(redact_env_and_header_values);
62        }
63        _ => {}
64    }
65}
66
67/// Redact `[{ "name", "value" }]` lists and `{ name: value }` maps.
68fn redact_name_value_pairs(field: &mut serde_json::Value) {
69    let redacted = || serde_json::Value::String("[REDACTED]".to_owned());
70    match field {
71        serde_json::Value::Array(entries) => {
72            for entry in entries {
73                if let Some(value) = entry.get_mut("value") {
74                    *value = redacted();
75                }
76            }
77        }
78        serde_json::Value::Object(entries) => {
79            for value in entries.values_mut() {
80                *value = redacted();
81            }
82        }
83        _ => {}
84    }
85}
86
87/// Format one wire line for protocol TRACE logs with credentials redacted.
88///
89/// Redaction happens only when the event is actually formatted. A line that is
90/// not valid JSON cannot be redacted reliably, so only its length is shown.
91pub(crate) fn redacted_json_line(line: &str) -> impl std::fmt::Display + '_ {
92    struct RedactedJsonLine<'a>(&'a str);
93
94    impl std::fmt::Display for RedactedJsonLine<'_> {
95        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
96            match serde_json::from_str::<serde_json::Value>(self.0) {
97                Ok(mut value) => {
98                    redact_env_and_header_values(&mut value);
99                    write!(f, "{value}")
100                }
101                Err(_) => write!(f, "<{} bytes of invalid JSON omitted>", self.0.len()),
102            }
103        }
104    }
105
106    RedactedJsonLine(line)
107}
108
109/// Cast from `N` to `M` by serializing/deserialization to/from JSON.
110///
111/// Use this for values the SDK or your own code produced, such as response
112/// results. Use [`json_cast_params`] for incoming request or notification params.
113///
114/// # Errors
115///
116/// Returns Parse error (`-32700`) if serialization or deserialization fails.
117/// Returned diagnostics can contain the input JSON and payload-bearing parse
118/// reasons. Treat them as sensitive, as with [`json_cast_params`].
119pub fn json_cast<N, M>(params: N) -> Result<M, crate::Error>
120where
121    N: serde::Serialize,
122    M: serde::de::DeserializeOwned,
123{
124    let json = serde_json::to_value(params).map_err(|e| {
125        crate::Error::parse_error().data(serde_json::json!({
126            "error": e.to_string(),
127            "phase": "serialization"
128        }))
129    })?;
130    let m = serde_json::from_value(json.clone()).map_err(|e| {
131        crate::Error::parse_error().data(serde_json::json!({
132            "error": e.to_string(),
133            "json": json,
134            "phase": "deserialization"
135        }))
136    })?;
137    Ok(m)
138}
139
140/// Cast incoming request/notification params into a typed payload.
141///
142/// # Errors
143///
144/// Returns Internal error (`-32603`) if `params` cannot be serialized, or
145/// Invalid params (`-32602`) if the JSON cannot be decoded as `M`.
146/// Returned diagnostics include the input JSON and may include input values in
147/// the parse reason. Treat them as sensitive; the SDK redacts errors at WARN.
148pub fn json_cast_params<N, M>(params: N) -> Result<M, crate::Error>
149where
150    N: serde::Serialize,
151    M: serde::de::DeserializeOwned,
152{
153    let json = serde_json::to_value(params).map_err(|e| {
154        crate::Error::internal_error().data(serde_json::json!({
155            "error": e.to_string(),
156            "phase": "serialization"
157        }))
158    })?;
159    let m = serde_json::from_value(json.clone()).map_err(|e| {
160        crate::Error::invalid_params().data(serde_json::json!({
161            "error": e.to_string(),
162            "json": json,
163            "phase": "deserialization"
164        }))
165    })?;
166    Ok(m)
167}
168
169/// An internal error (`-32603`) whose data is `message`.
170pub(crate) fn internal_error(message: impl ToString) -> crate::Error {
171    crate::Error::internal_error().data(message.to_string())
172}
173
174/// Rewrite the params of an `initialize` request for the protocol version
175/// `selected` that a version-agnostic forwarder, such as the conductor,
176/// selected for it.
177///
178/// The SDK's own agents negotiate the same way. A request for a newer version
179/// than `selected` was written for that newer version, so it keeps only what
180/// parses under `selected` instead of being rejected (for v1, only the shared
181/// capabilities are carried across). A request for `selected` or an older
182/// version keeps its params. In every case `protocolVersion` is set to
183/// `selected`.
184///
185/// # Errors
186///
187/// Returns `-32602` when `params` has no valid `protocolVersion`, and
188/// `-32600` when a newer request must be rewritten for a version this build
189/// of the SDK does not support.
190pub fn initialize_params_for_version(
191    params: &serde_json::Value,
192    selected: crate::schema::ProtocolVersion,
193) -> Result<serde_json::Map<String, serde_json::Value>, crate::Error> {
194    use crate::schema::ProtocolVersion;
195
196    let invalid_version = || {
197        crate::Error::invalid_params()
198            .data("initialize.protocolVersion must be a valid ACP protocol version")
199    };
200    let serde_json::Value::Object(object) = params else {
201        return Err(invalid_version());
202    };
203    let requested: ProtocolVersion = object
204        .get("protocolVersion")
205        .cloned()
206        .and_then(|version| serde_json::from_value(version).ok())
207        .ok_or_else(invalid_version)?;
208
209    let mut rewritten = if requested <= selected {
210        object.clone()
211    } else if selected == ProtocolVersion::V1 {
212        crate::jsonrpc::normalize_v1_initialize_request(params)?
213    } else {
214        #[cfg(feature = "unstable_protocol_v2")]
215        if selected == ProtocolVersion::V2 {
216            return crate::jsonrpc::normalize_newer_v2_initialize_request(object);
217        }
218        return Err(crate::Error::invalid_request().data(format!(
219            "cannot rewrite an initialize request for ACP protocol version {requested} to version {selected}",
220        )));
221    };
222    rewritten.insert(
223        "protocolVersion".into(),
224        serde_json::to_value(selected).map_err(crate::Error::into_internal_error)?,
225    );
226    Ok(rewritten)
227}
228
229/// The `-32600` error, sent with `id: null`, for a JSON-RPC batch array.
230///
231/// The SDK does not support JSON-RPC batching, and ACP protocol v2 removed
232/// it.
233pub(crate) fn batch_not_supported() -> crate::Error {
234    crate::Error::invalid_request()
235        .data("JSON-RPC batches are not supported; send each message individually")
236}
237
238pub(crate) fn instrumented_with_connection_name<F>(
239    name: String,
240    task: F,
241) -> tracing::instrument::Instrumented<F> {
242    use tracing::Instrument;
243
244    task.instrument(tracing::info_span!("connection", name = name))
245}
246
247pub(crate) async fn instrument_with_connection_name<R>(
248    name: Option<String>,
249    task: impl Future<Output = R>,
250) -> R {
251    if let Some(name) = name {
252        instrumented_with_connection_name(name.clone(), task).await
253    } else {
254        task.await
255    }
256}
257
258/// Run `background` until `foreground` completes.
259///
260/// Returns the result of `foreground`. If `background` errors before
261/// `foreground` completes, the error is propagated. If `background`
262/// completes with `Ok(())`, we continue waiting for `foreground`.
263pub fn run_until<T, E>(
264    background: impl Future<Output = Result<(), E>>,
265    foreground: impl Future<Output = Result<T, E>>,
266) -> impl Future<Output = Result<T, E>> {
267    use futures::future::{Either, select};
268    use std::pin::pin;
269
270    Box::pin(async move {
271        match select(pin!(background), pin!(foreground)).await {
272            Either::Left((bg_result, fg_future)) => {
273                // Background finished first
274                bg_result?; // propagate error, or if Ok(()), keep waiting
275                fg_future.await
276            }
277            Either::Right((fg_result, _bg_future)) => {
278                // Foreground finished first, drop background
279                fg_result
280            }
281        }
282    })
283}
284
285/// Process items from a stream concurrently.
286///
287/// For each item received from `stream`, calls `process_fn` to create a future,
288/// then runs all futures concurrently. If any future returns an error,
289/// stops processing and returns that error.
290///
291/// This is useful for patterns where you receive work items from a channel
292/// and want to process them concurrently while respecting backpressure.
293pub(crate) async fn process_stream_concurrently<T, F>(
294    stream: impl Stream<Item = T>,
295    process_fn: F,
296    process_fn_hack: impl for<'a> Fn(&'a F, T) -> BoxFuture<'a, Result<(), crate::Error>>,
297) -> Result<(), crate::Error>
298where
299    F: AsyncFn(T) -> Result<(), crate::Error>,
300{
301    use std::pin::pin;
302
303    use futures::stream::{FusedStream, FuturesUnordered};
304    use futures_concurrency::future::Race;
305
306    enum Event<T> {
307        NewItem(Option<T>),
308        FutureCompleted(Option<Result<(), crate::Error>>),
309    }
310
311    let mut stream = pin!(stream.fuse());
312    let mut futures: FuturesUnordered<_> = FuturesUnordered::new();
313
314    loop {
315        // If we have no futures to run, wait until we do.
316        if futures.is_empty() {
317            match stream.next().await {
318                Some(item) => futures.push(process_fn_hack(&process_fn, item)),
319                None => return Ok(()),
320            }
321            continue;
322        }
323
324        // If there are no more items coming in, just drain our queue and return.
325        if stream.is_terminated() {
326            while let Some(result) = futures.next().await {
327                result?;
328            }
329            return Ok(());
330        }
331
332        // Otherwise, race between getting a new item and completing a future.
333        let event = (async { Event::NewItem(stream.next().await) }, async {
334            Event::FutureCompleted(futures.next().await)
335        })
336            .race()
337            .await;
338
339        match event {
340            Event::NewItem(Some(item)) => {
341                futures.push(process_fn_hack(&process_fn, item));
342            }
343            Event::FutureCompleted(Some(result)) => {
344                result?;
345            }
346            Event::NewItem(None) | Event::FutureCompleted(None) => {
347                // Stream closed, loop will catch is_terminated
348                // No futures were pending, shouldn't happen since we checked is_empty
349            }
350        }
351    }
352}