Skip to main content

blyte_cli/mcp/
http.rs

1//! Streamable HTTP JSON-RPC 2.0 transport for remote MCP servers.
2
3use std::collections::BTreeMap;
4use std::io::{BufRead, BufReader, Read};
5use std::time::Duration;
6
7use serde_json::Value;
8
9use crate::mcp::client::McpTransport;
10use crate::mcp::protocol::{
11    JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, McpError, JSONRPC_VERSION,
12};
13
14const ACCEPT_HEADER: &str = "application/json, text/event-stream";
15const SESSION_ID_HEADER: &str = "Mcp-Session-Id";
16const MAX_ERROR_BODY_BYTES: usize = 4096;
17
18/// JSON-RPC 2.0 transport speaking MCP Streamable HTTP (`application/json` and `text/event-stream`).
19pub struct StreamableHttpTransport {
20    url: String,
21    headers: BTreeMap<String, String>,
22    bearer_token: Option<String>,
23    session_id: Option<String>,
24    agent: ureq::Agent,
25}
26
27impl StreamableHttpTransport {
28    /// Creates a new Streamable HTTP transport targeting `url`.
29    pub fn new(
30        url: impl Into<String>,
31        headers: BTreeMap<String, String>,
32        bearer_token: Option<String>,
33    ) -> Self {
34        Self {
35            url: url.into(),
36            headers,
37            bearer_token,
38            session_id: None,
39            agent: ureq::AgentBuilder::new().build(),
40        }
41    }
42
43    /// Returns the current `Mcp-Session-Id` returned by the server, if any.
44    pub fn session_id(&self) -> Option<&str> {
45        self.session_id.as_deref()
46    }
47
48    /// Replaces the bearer access token used on subsequent HTTP requests.
49    pub fn set_bearer_token(&mut self, token: Option<String>) {
50        self.bearer_token = token;
51    }
52
53    fn build_post(&self, timeout: Duration) -> ureq::Request {
54        let mut req = self.agent.post(&self.url).timeout(timeout);
55        for (k, v) in &self.headers {
56            req = req.set(k, v);
57        }
58        req = req
59            .set("Content-Type", "application/json")
60            .set("Accept", ACCEPT_HEADER);
61        if let Some(token) = &self.bearer_token {
62            req = req.set("Authorization", &format!("Bearer {token}"));
63        }
64        if let Some(sid) = &self.session_id {
65            req = req.set(SESSION_ID_HEADER, sid);
66        }
67        req
68    }
69
70    fn record_session_id(&mut self, resp: &ureq::Response) {
71        if let Some(sid) = resp
72            .header("mcp-session-id")
73            .filter(|s| !s.trim().is_empty())
74        {
75            self.session_id = Some(sid.trim().to_string());
76        }
77    }
78
79    fn send_json(
80        &mut self,
81        operation: &str,
82        body: &str,
83        timeout: Duration,
84    ) -> Result<ureq::Response, McpError> {
85        match self.build_post(timeout).send_string(body) {
86            Ok(resp) => {
87                self.record_session_id(&resp);
88                Ok(resp)
89            }
90            Err(ureq::Error::Status(401, resp)) => {
91                let www_authenticate = resp.header("www-authenticate").map(str::to_string);
92                Err(McpError::NeedsAuth {
93                    www_authenticate,
94                    status: 401,
95                })
96            }
97            Err(ureq::Error::Status(status, resp)) => {
98                let body = read_capped_body(resp, MAX_ERROR_BODY_BYTES);
99                Err(McpError::HttpStatus { status, body })
100            }
101            Err(ureq::Error::Transport(t)) => {
102                if is_timeout_transport(&t) {
103                    Err(McpError::Timeout {
104                        operation: operation.to_string(),
105                        timeout,
106                    })
107                } else {
108                    Err(McpError::Transport {
109                        message: format!("HTTP request to '{}' failed: {t}", self.url),
110                        stderr: None,
111                    })
112                }
113            }
114        }
115    }
116}
117
118impl McpTransport for StreamableHttpTransport {
119    fn send_request(
120        &mut self,
121        request_id: u64,
122        method: &str,
123        params: Option<Value>,
124        timeout: Duration,
125    ) -> Result<Value, McpError> {
126        let req = JsonRpcRequest {
127            jsonrpc: JSONRPC_VERSION,
128            id: request_id,
129            method,
130            params,
131        };
132        let encoded = serde_json::to_string(&req)
133            .map_err(|e| McpError::Protocol(format!("failed to serialize request: {e}")))?;
134        let resp = self.send_json(method, &encoded, timeout)?;
135        let content_type = resp.content_type().to_ascii_lowercase();
136        match content_type.as_str() {
137            "application/json" => {
138                let text = resp.into_string().map_err(|e| {
139                    map_body_read_error(e, method, timeout, "failed reading JSON response body")
140                })?;
141                let parsed: JsonRpcResponse = serde_json::from_str(&text).map_err(|e| {
142                    McpError::Protocol(format!("invalid JSON-RPC response body: {e}"))
143                })?;
144                if !parsed.matches_id(request_id)
145                    && !(parsed.id.is_none() && parsed.error.is_some())
146                {
147                    return Err(McpError::Protocol(format!(
148                        "JSON-RPC response id {:?} did not match request id {request_id}",
149                        parsed.id
150                    )));
151                }
152                parsed.into_result()
153            }
154            "text/event-stream" => {
155                parse_sse_response(resp.into_reader(), request_id, method, timeout)
156            }
157            other => Err(McpError::Protocol(format!(
158                "unexpected Content-Type '{other}' from MCP HTTP server"
159            ))),
160        }
161    }
162
163    fn send_notification(
164        &mut self,
165        method: &str,
166        params: Option<Value>,
167        timeout: Duration,
168    ) -> Result<(), McpError> {
169        let notif = JsonRpcNotification {
170            jsonrpc: JSONRPC_VERSION,
171            method,
172            params,
173        };
174        let encoded = serde_json::to_string(&notif)
175            .map_err(|e| McpError::Protocol(format!("failed to serialize notification: {e}")))?;
176        let resp = self.send_json(method, &encoded, timeout)?;
177        let _ = read_capped_body(resp, MAX_ERROR_BODY_BYTES);
178        Ok(())
179    }
180}
181
182fn parse_sse_response(
183    reader: impl Read,
184    request_id: u64,
185    operation: &str,
186    timeout: Duration,
187) -> Result<Value, McpError> {
188    let mut buf = BufReader::new(reader);
189    let mut line = String::new();
190    let mut data_lines: Vec<String> = Vec::new();
191
192    loop {
193        line.clear();
194        let n = buf
195            .read_line(&mut line)
196            .map_err(|e| map_body_read_error(e, operation, timeout, "failed reading SSE stream"))?;
197        if n == 0 {
198            if let Some(res) = dispatch_sse_event(&mut data_lines, request_id)? {
199                return res;
200            }
201            return Err(McpError::Protocol(format!(
202                "SSE stream ended without a JSON-RPC response for request id {request_id}"
203            )));
204        }
205
206        let trimmed = line.trim_end_matches(&['\r', '\n'][..]);
207        if trimmed.is_empty() {
208            if let Some(res) = dispatch_sse_event(&mut data_lines, request_id)? {
209                return res;
210            }
211            continue;
212        }
213        if trimmed.starts_with(':') {
214            continue;
215        }
216        if let Some(rest) = trimmed.strip_prefix("data:") {
217            let value = rest.strip_prefix(' ').unwrap_or(rest);
218            data_lines.push(value.to_string());
219        }
220    }
221}
222
223fn dispatch_sse_event(
224    data_lines: &mut Vec<String>,
225    request_id: u64,
226) -> Result<Option<Result<Value, McpError>>, McpError> {
227    if data_lines.is_empty() {
228        return Ok(None);
229    }
230    let payload = data_lines.join("\n");
231    data_lines.clear();
232    let trimmed = payload.trim();
233    if trimmed.is_empty() {
234        return Ok(None);
235    }
236
237    let raw: Value = serde_json::from_str(trimmed)
238        .map_err(|e| McpError::Protocol(format!("invalid JSON in SSE data event: {e}")))?;
239    let has_method = raw.get("method").is_some();
240    let has_result_or_error = raw.get("result").is_some() || raw.get("error").is_some();
241    if has_method && !has_result_or_error {
242        return Ok(None);
243    }
244    let resp: JsonRpcResponse = serde_json::from_value(raw).map_err(|e| {
245        McpError::Protocol(format!("malformed JSON-RPC response in SSE event: {e}"))
246    })?;
247    if resp.matches_id(request_id) || (resp.id.is_none() && resp.error.is_some()) {
248        return Ok(Some(resp.into_result()));
249    }
250    Ok(None)
251}
252
253fn read_capped_body(resp: ureq::Response, max_bytes: usize) -> String {
254    let mut reader = resp.into_reader().take(max_bytes as u64);
255    let mut buf = Vec::new();
256    let _ = reader.read_to_end(&mut buf);
257    String::from_utf8_lossy(&buf).into_owned()
258}
259
260fn is_timeout_io_error(err: &std::io::Error) -> bool {
261    matches!(
262        err.kind(),
263        std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock
264    )
265}
266
267fn map_body_read_error(
268    err: std::io::Error,
269    operation: &str,
270    timeout: Duration,
271    context: &str,
272) -> McpError {
273    if is_timeout_io_error(&err) {
274        McpError::Timeout {
275            operation: operation.to_string(),
276            timeout,
277        }
278    } else {
279        McpError::Transport {
280            message: format!("{context}: {err}"),
281            stderr: None,
282        }
283    }
284}
285
286fn is_timeout_transport(t: &ureq::Transport) -> bool {
287    if let Some(io_err) =
288        std::error::Error::source(t).and_then(|s| s.downcast_ref::<std::io::Error>())
289    {
290        if is_timeout_io_error(io_err) {
291            return true;
292        }
293    }
294    t.message()
295        .map(|m| m.to_ascii_lowercase().contains("timed out"))
296        .unwrap_or(false)
297}