返回 CodeWhale
wire.rs
根目录 / crates / engine / src / mcp / wire.rs
1 //! MCP wire-format helpers shared by the HTTP, SSE, streamable-HTTP, and
2 //! stdio transports: frame/response size ceilings, SSE event framing and
3 //! field parsing, and the error-text classifiers that decide whether a
4 //! failure is a stale session or a closed connection.
5 /// Hard ceiling on the SSE frame-assembly buffer. A server that never emits a
6 /// frame separator would otherwise grow it without bound (OOM DoS).
7 pub const MAX_SSE_FRAME_BYTES: usize = 8 * 1024 * 1024;
8
9 /// Hard ceiling on a single MCP HTTP response body / stdio line. A misbehaving
10 /// or malicious server could otherwise stream an unbounded body (or a
11 /// newline-free multi-GB "line") and OOM the process at transport-read time,
12 /// before any transcript-level spillover applies.
13 pub const MAX_MCP_RESPONSE_BYTES: usize = 16 * 1024 * 1024;
14
15 pub fn is_mcp_stale_session_body(body: &str) -> bool {
16 let body = body.to_ascii_lowercase();
17 body.contains("session") && (body.contains("expired") || body.contains("invalid"))
18 }
19
20 /// A transport-level refusal of the session id, raised only where the
21 /// HTTP layer turned the request away before handing it to the server's
22 /// method dispatch: a Streamable HTTP stale-session status, or a legacy SSE
23 /// POST rejected with a stale-session body. A JSON-RPC error response is
24 /// never this type: it answers the request id, so the server processed it.
25 #[derive(Debug)]
26 pub struct McpSessionRejected(pub String);
27
28 impl std::fmt::Display for McpSessionRejected {
29 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
30 f.write_str(&self.0)
31 }
32 }
33
34 impl std::error::Error for McpSessionRejected {}
35
36 #[derive(Debug)]
37 pub(super) struct McpServerReplyUnsupported(pub String);
38
39 impl std::fmt::Display for McpServerReplyUnsupported {
40 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41 f.write_str(&self.0)
42 }
43 }
44
45 impl std::error::Error for McpServerReplyUnsupported {}
46
47 pub(super) fn is_mcp_server_reply_unsupported_error(err: &anyhow::Error) -> bool {
48 err.downcast_ref::<McpServerReplyUnsupported>().is_some()
49 }
50
51 /// The transport refused the session id, so the server provably did not run
52 /// the request. This is the only failure after which a non-idempotent
53 /// `tools/call` may be replayed on a fresh connection. Typed, not matched on
54 /// text, so a tool error that merely mentions an expired session cannot
55 /// qualify.
56 pub(super) fn is_mcp_session_rejected_error(err: &anyhow::Error) -> bool {
57 err.downcast_ref::<McpSessionRejected>().is_some()
58 }
59
60 /// The connection is unusable: either the server rejected the session id,
61 /// or the transport itself is gone (dead pipe/socket) rather than merely
62 /// idle. The connection must be rebuilt, but a request already written to
63 /// a transport that then died may have run, so this alone does not make a
64 /// `tools/call` safe to replay.
65 pub(super) fn is_mcp_connection_lost_error(err: &anyhow::Error) -> bool {
66 if is_mcp_stale_session_error(err) {
67 return true;
68 }
69 let lower = format!("{err:#}").to_ascii_lowercase();
70 is_connection_closed_error_text(&lower)
71 }
72
73 pub(super) fn is_mcp_stale_session_error(err: &anyhow::Error) -> bool {
74 let err = format!("{err:#}");
75 let lower_err = err.to_ascii_lowercase();
76 err.contains("MCP Streamable HTTP session expired")
77 || err.contains("MCP session expired")
78 || err.contains("SSE transport closed")
79 // The exact bail text of a stdio transport whose child died (the
80 // EOF arm of `StdioTransport::recv`); without this arm a dead-child
81 // error missed the drop→reconnect→retry path that SSE closes get.
82 || err.contains("Stdio transport closed")
83 || (err.contains("MCP SSE POST send failed") && is_connection_closed_error_text(&lower_err))
84 || is_mcp_stale_session_body(&err)
85 }
86
87 pub(super) fn is_connection_closed_error_text(err: &str) -> bool {
88 err.contains("connection closed")
89 || err.contains("connection reset")
90 || err.contains("broken pipe")
91 || err.contains("unexpected eof")
92 || err.contains("forcibly closed")
93 }
94
95 pub(super) fn parse_sse_message_data(body: &str) -> Vec<Vec<u8>> {
96 let normalized = body.replace("\r\n", "\n");
97 let mut messages = Vec::new();
98
99 for block in normalized.split("\n\n") {
100 let mut event_type = "message";
101 let mut data = String::new();
102
103 for line in block.lines() {
104 if let Some(value) = sse_field_value(line, "event:") {
105 event_type = value;
106 } else if let Some(value) = sse_field_value(line, "data:") {
107 if !data.is_empty() {
108 data.push('\n');
109 }
110 data.push_str(value);
111 }
112 }
113
114 if event_type != "message" || data.trim().is_empty() {
115 continue;
116 }
117
118 messages.push(data.trim().as_bytes().to_vec());
119 }
120
121 messages
122 }
123
124 // Retained for tests; the SSE transport now uses the byte-oriented twin.
125 #[cfg(test)]
126 pub(super) fn find_sse_event_separator(buffer: &str) -> Option<(usize, usize)> {
127 match (buffer.find("\n\n"), buffer.find("\r\n\r\n")) {
128 (Some(lf), Some(crlf)) if crlf < lf => Some((crlf, 4)),
129 (Some(lf), _) => Some((lf, 2)),
130 (_, Some(crlf)) => Some((crlf, 4)),
131 _ => None,
132 }
133 }
134
135 /// Byte-oriented twin of `find_sse_event_separator`. Used by the SSE
136 /// transport so it can accumulate RAW bytes and decode only complete event
137 /// blocks — a multi-byte UTF-8 char split across two network reads is never
138 /// corrupted to U+FFFD (the `\n`/`\r` separators are ASCII and can never fall
139 /// inside a multi-byte sequence).
140 pub fn find_sse_event_separator_bytes(buffer: &[u8]) -> Option<(usize, usize)> {
141 let lf = buffer.windows(2).position(|w| w == b"\n\n");
142 let crlf = buffer.windows(4).position(|w| w == b"\r\n\r\n");
143 match (lf, crlf) {
144 (Some(lf), Some(crlf)) if crlf < lf => Some((crlf, 4)),
145 (Some(lf), _) => Some((lf, 2)),
146 (_, Some(crlf)) => Some((crlf, 4)),
147 _ => None,
148 }
149 }
150
151 pub fn sse_field_value<'a>(line: &'a str, field: &str) -> Option<&'a str> {
152 let value = line.strip_prefix(field)?;
153 Some(value.strip_prefix(' ').unwrap_or(value))
154 }
155
156 pub fn is_json_rpc_error_body(body_excerpt: &str) -> bool {
157 serde_json::from_str::<serde_json::Value>(body_excerpt.trim())
158 .ok()
159 .and_then(|value| value.get("error")?.get("code")?.as_i64())
160 .is_some()
161 }
162
163 pub fn is_streamable_http_incompatible_status(status: reqwest::StatusCode) -> bool {
164 matches!(
165 status,
166 reqwest::StatusCode::NOT_FOUND
167 | reqwest::StatusCode::METHOD_NOT_ALLOWED
168 | reqwest::StatusCode::NOT_ACCEPTABLE
169 | reqwest::StatusCode::UNSUPPORTED_MEDIA_TYPE
170 | reqwest::StatusCode::NOT_IMPLEMENTED
171 )
172 }
173
174 pub fn is_streamable_http_stale_session_status(
175 status: reqwest::StatusCode,
176 body_excerpt: &str,
177 ) -> bool {
178 if status == reqwest::StatusCode::NOT_FOUND {
179 return true;
180 }
181 if status != reqwest::StatusCode::BAD_REQUEST && status != reqwest::StatusCode::UNAUTHORIZED {
182 return false;
183 }
184 let body = body_excerpt.to_ascii_lowercase();
185 body.contains("session") && (body.contains("expired") || body.contains("invalid"))
186 }
187
188 /// Continue one newline-terminated line in caller-owned `out`, aborting if it
189 /// exceeds `max` bytes. Cancellation retains consumed bytes; the caller clears
190 /// the buffer only after receiving a complete frame. Returns the total bytes
191 /// accumulated; 0 means EOF.
192 pub async fn read_line_capped<R>(
193 reader: &mut R,
194 out: &mut Vec<u8>,
195 max: usize,
196 ) -> std::io::Result<usize>
197 where
198 R: tokio::io::AsyncBufRead + Unpin,
199 {
200 use tokio::io::AsyncBufReadExt;
201 loop {
202 let (chunk, consumed, done) = {
203 let available = reader.fill_buf().await?;
204 if available.is_empty() {
205 (Vec::new(), 0usize, true)
206 } else if let Some(pos) = available.iter().position(|&b| b == b'\n') {
207 (available[..=pos].to_vec(), pos + 1, true)
208 } else {
209 (available.to_vec(), available.len(), false)
210 }
211 };
212 if consumed > 0 {
213 reader.consume(consumed);
214 }
215 out.extend_from_slice(&chunk);
216 if out.len() > max {
217 return Err(std::io::Error::new(
218 std::io::ErrorKind::InvalidData,
219 format!("MCP stdio line exceeded {max} bytes"),
220 ));
221 }
222 if done {
223 break;
224 }
225 }
226 Ok(out.len())
227 }
228
229 #[cfg(test)]
230 mod read_cap_tests {
231 use super::read_line_capped;
232
233 #[tokio::test]
234 async fn cancelled_partial_read_preserves_next_frame() {
235 use futures_util::FutureExt;
236 use tokio::io::AsyncWriteExt;
237 let (mut writer, reader) = tokio::io::duplex(4096);
238 let mut reader = tokio::io::BufReader::new(reader);
239 let prefix = br#"{"jsonrpc":"2.0","id":"1","result":"#;
240 writer.write_all(prefix).await.unwrap();
241 let mut pending = Vec::new();
242 // Poll through the consumed prefix to Pending, then drop the future.
243 assert!(
244 read_line_capped(&mut reader, &mut pending, 1024)
245 .now_or_never()
246 .is_none()
247 );
248 assert_eq!(pending, prefix);
249 writer.write_all(b"null}\n").await.unwrap();
250 read_line_capped(&mut reader, &mut pending, 1024)
251 .await
252 .unwrap();
253 let first: serde_json::Value =
254 serde_json::from_slice(&std::mem::take(&mut pending)).unwrap();
255 assert_eq!(first["id"], "1");
256 writer
257 .write_all(b"{\"id\":\"2\",\"result\":true}\n")
258 .await
259 .unwrap();
260 read_line_capped(&mut reader, &mut pending, 1024)
261 .await
262 .unwrap();
263 let second: serde_json::Value = serde_json::from_slice(&pending).unwrap();
264 assert_eq!(second["id"], "2");
265 assert_eq!(second["result"], true);
266 }
267
268 #[tokio::test]
269 async fn resumed_frame_still_enforces_cap_at_newline() {
270 use futures_util::FutureExt;
271 use tokio::io::AsyncWriteExt;
272 let (mut writer, reader) = tokio::io::duplex(4096);
273 let mut reader = tokio::io::BufReader::new(reader);
274 let mut pending = Vec::new();
275 writer.write_all(b"1234").await.unwrap();
276 assert!(
277 read_line_capped(&mut reader, &mut pending, 6)
278 .now_or_never()
279 .is_none()
280 );
281 writer.write_all(b"567\n").await.unwrap();
282 assert_eq!(
283 read_line_capped(&mut reader, &mut pending, 6)
284 .await
285 .unwrap_err()
286 .kind(),
287 std::io::ErrorKind::InvalidData
288 );
289 }
290
291 #[tokio::test]
292 async fn reads_a_line_and_reports_eof() {
293 let data = b"hello\nworld\n".to_vec();
294 let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(data));
295 let mut out = Vec::new();
296 assert_eq!(
297 read_line_capped(&mut reader, &mut out, 1024).await.unwrap(),
298 6
299 );
300 assert_eq!(out, b"hello\n");
301 out.clear();
302 assert_eq!(
303 read_line_capped(&mut reader, &mut out, 1024).await.unwrap(),
304 6
305 );
306 assert_eq!(out, b"world\n");
307 out.clear();
308 // EOF.
309 assert_eq!(
310 read_line_capped(&mut reader, &mut out, 1024).await.unwrap(),
311 0
312 );
313 }
314
315 #[tokio::test]
316 async fn aborts_on_newline_free_line_over_cap() {
317 let data = vec![b'x'; 4096]; // no newline
318 let mut reader = tokio::io::BufReader::new(std::io::Cursor::new(data));
319 let mut out = Vec::new();
320 let err = read_line_capped(&mut reader, &mut out, 1024)
321 .await
322 .unwrap_err();
323 assert_eq!(err.kind(), std::io::ErrorKind::InvalidData);
324 }
325 }
326
327 pub fn resolve_sse_endpoint_url(base_url: &str, endpoint_url: &str) -> anyhow::Result<String> {
328 let base = reqwest::Url::parse(base_url)?;
329 let resolved = if endpoint_url.starts_with("http://") || endpoint_url.starts_with("https://") {
330 reqwest::Url::parse(endpoint_url)?
331 } else {
332 base.join(endpoint_url)?
333 };
334 // reqwest converts userinfo into Basic Authorization while building a
335 // request, before the request-time guard can inspect the original URL.
336 if !resolved.username().is_empty() || resolved.password().is_some() {
337 anyhow::bail!("MCP SSE endpoint must not contain URL credentials");
338 }
339 // Security: the server-supplied `endpoint` event must stay same-origin
340 // as the connect URL. The connect host is vetted by network policy
341 // once, but the endpoint host is never re-checked — so an absolute
342 // cross-origin endpoint would let a malicious MCP server redirect the
343 // client's *authenticated* POSTs (Bearer/OAuth headers attached) to an
344 // internal host (169.254.169.254, localhost admin ports, …): an SSRF /
345 // policy bypass. Relative endpoints are same-origin by construction.
346 if resolved.scheme() != base.scheme()
347 || resolved.host_str() != base.host_str()
348 || resolved.port_or_known_default() != base.port_or_known_default()
349 {
350 anyhow::bail!(
351 "MCP SSE endpoint {} is not same-origin as {} — refusing to send \
352 authenticated requests cross-origin",
353 super::mask_url_secrets(resolved.as_str()),
354 super::mask_url_secrets(base.as_str()),
355 );
356 }
357 Ok(resolved.to_string())
358 }
359
360 #[cfg(test)]
361 mod endpoint_tests {
362 use super::resolve_sse_endpoint_url;
363
364 #[test]
365 fn resolve_endpoint_accepts_relative_and_same_origin() {
366 let base = "https://mcp.example.com/v1/sse";
367 // Relative path -> same origin.
368 assert_eq!(
369 resolve_sse_endpoint_url(base, "/messages?sid=1").unwrap(),
370 "https://mcp.example.com/messages?sid=1"
371 );
372 // Absolute but same origin -> allowed.
373 assert_eq!(
374 resolve_sse_endpoint_url(base, "https://mcp.example.com/messages").unwrap(),
375 "https://mcp.example.com/messages"
376 );
377 }
378
379 #[test]
380 fn resolve_endpoint_rejects_cross_origin_ssrf() {
381 let base = "https://mcp.example.com/v1/sse";
382 // Different host (metadata endpoint) -> rejected.
383 assert!(resolve_sse_endpoint_url(base, "http://169.254.169.254/latest").is_err());
384 // Different scheme -> rejected.
385 assert!(resolve_sse_endpoint_url(base, "http://mcp.example.com/messages").is_err());
386 // Different port -> rejected.
387 assert!(resolve_sse_endpoint_url(base, "https://mcp.example.com:8443/x").is_err());
388 // Same-origin userinfo must not become an implicit Basic credential.
389 for endpoint in [
390 "https://fixture-user:fixture-password@mcp.example.com/messages",
391 "//fixture-user@mcp.example.com/messages",
392 ] {
393 let error = resolve_sse_endpoint_url(base, endpoint).unwrap_err();
394 assert!(
395 error
396 .to_string()
397 .contains("must not contain URL credentials")
398 );
399 assert!(!error.to_string().contains("fixture-user"));
400 assert!(!error.to_string().contains("fixture-password"));
401 }
402 }
403 }
404
404 lines RUST