blyte 0.88.1

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
//! Streamable HTTP JSON-RPC 2.0 transport for remote MCP servers.

use std::collections::BTreeMap;
use std::io::{BufRead, BufReader, Read};
use std::time::Duration;

use serde_json::Value;

use crate::mcp::client::McpTransport;
use crate::mcp::protocol::{
    JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, McpError, JSONRPC_VERSION,
};

const ACCEPT_HEADER: &str = "application/json, text/event-stream";
const SESSION_ID_HEADER: &str = "Mcp-Session-Id";
const MAX_ERROR_BODY_BYTES: usize = 4096;

/// JSON-RPC 2.0 transport speaking MCP Streamable HTTP (`application/json` and `text/event-stream`).
pub struct StreamableHttpTransport {
    url: String,
    headers: BTreeMap<String, String>,
    bearer_token: Option<String>,
    session_id: Option<String>,
    agent: ureq::Agent,
}

impl StreamableHttpTransport {
    /// Creates a new Streamable HTTP transport targeting `url`.
    pub fn new(
        url: impl Into<String>,
        headers: BTreeMap<String, String>,
        bearer_token: Option<String>,
    ) -> Self {
        Self {
            url: url.into(),
            headers,
            bearer_token,
            session_id: None,
            agent: ureq::AgentBuilder::new().build(),
        }
    }

    /// Returns the current `Mcp-Session-Id` returned by the server, if any.
    pub fn session_id(&self) -> Option<&str> {
        self.session_id.as_deref()
    }

    /// Replaces the bearer access token used on subsequent HTTP requests.
    pub fn set_bearer_token(&mut self, token: Option<String>) {
        self.bearer_token = token;
    }

    fn build_post(&self, timeout: Duration) -> ureq::Request {
        let mut req = self.agent.post(&self.url).timeout(timeout);
        for (k, v) in &self.headers {
            req = req.set(k, v);
        }
        req = req
            .set("Content-Type", "application/json")
            .set("Accept", ACCEPT_HEADER);
        if let Some(token) = &self.bearer_token {
            req = req.set("Authorization", &format!("Bearer {token}"));
        }
        if let Some(sid) = &self.session_id {
            req = req.set(SESSION_ID_HEADER, sid);
        }
        req
    }

    fn record_session_id(&mut self, resp: &ureq::Response) {
        if let Some(sid) = resp
            .header("mcp-session-id")
            .filter(|s| !s.trim().is_empty())
        {
            self.session_id = Some(sid.trim().to_string());
        }
    }

    fn send_json(
        &mut self,
        operation: &str,
        body: &str,
        timeout: Duration,
    ) -> Result<ureq::Response, McpError> {
        match self.build_post(timeout).send_string(body) {
            Ok(resp) => {
                self.record_session_id(&resp);
                Ok(resp)
            }
            Err(ureq::Error::Status(401, resp)) => {
                let www_authenticate = resp.header("www-authenticate").map(str::to_string);
                Err(McpError::NeedsAuth {
                    www_authenticate,
                    status: 401,
                })
            }
            Err(ureq::Error::Status(status, resp)) => {
                let body = read_capped_body(resp, MAX_ERROR_BODY_BYTES);
                Err(McpError::HttpStatus { status, body })
            }
            Err(ureq::Error::Transport(t)) => {
                if is_timeout_transport(&t) {
                    Err(McpError::Timeout {
                        operation: operation.to_string(),
                        timeout,
                    })
                } else {
                    Err(McpError::Transport {
                        message: format!("HTTP request to '{}' failed: {t}", self.url),
                        stderr: None,
                    })
                }
            }
        }
    }
}

impl McpTransport for StreamableHttpTransport {
    fn send_request(
        &mut self,
        request_id: u64,
        method: &str,
        params: Option<Value>,
        timeout: Duration,
    ) -> Result<Value, McpError> {
        let req = JsonRpcRequest {
            jsonrpc: JSONRPC_VERSION,
            id: request_id,
            method,
            params,
        };
        let encoded = serde_json::to_string(&req)
            .map_err(|e| McpError::Protocol(format!("failed to serialize request: {e}")))?;
        let resp = self.send_json(method, &encoded, timeout)?;
        let content_type = resp.content_type().to_ascii_lowercase();
        match content_type.as_str() {
            "application/json" => {
                let text = resp.into_string().map_err(|e| {
                    map_body_read_error(e, method, timeout, "failed reading JSON response body")
                })?;
                let parsed: JsonRpcResponse = serde_json::from_str(&text).map_err(|e| {
                    McpError::Protocol(format!("invalid JSON-RPC response body: {e}"))
                })?;
                if !parsed.matches_id(request_id)
                    && !(parsed.id.is_none() && parsed.error.is_some())
                {
                    return Err(McpError::Protocol(format!(
                        "JSON-RPC response id {:?} did not match request id {request_id}",
                        parsed.id
                    )));
                }
                parsed.into_result()
            }
            "text/event-stream" => {
                parse_sse_response(resp.into_reader(), request_id, method, timeout)
            }
            other => Err(McpError::Protocol(format!(
                "unexpected Content-Type '{other}' from MCP HTTP server"
            ))),
        }
    }

    fn send_notification(
        &mut self,
        method: &str,
        params: Option<Value>,
        timeout: Duration,
    ) -> Result<(), McpError> {
        let notif = JsonRpcNotification {
            jsonrpc: JSONRPC_VERSION,
            method,
            params,
        };
        let encoded = serde_json::to_string(&notif)
            .map_err(|e| McpError::Protocol(format!("failed to serialize notification: {e}")))?;
        let resp = self.send_json(method, &encoded, timeout)?;
        let _ = read_capped_body(resp, MAX_ERROR_BODY_BYTES);
        Ok(())
    }
}

fn parse_sse_response(
    reader: impl Read,
    request_id: u64,
    operation: &str,
    timeout: Duration,
) -> Result<Value, McpError> {
    let mut buf = BufReader::new(reader);
    let mut line = String::new();
    let mut data_lines: Vec<String> = Vec::new();

    loop {
        line.clear();
        let n = buf
            .read_line(&mut line)
            .map_err(|e| map_body_read_error(e, operation, timeout, "failed reading SSE stream"))?;
        if n == 0 {
            if let Some(res) = dispatch_sse_event(&mut data_lines, request_id)? {
                return res;
            }
            return Err(McpError::Protocol(format!(
                "SSE stream ended without a JSON-RPC response for request id {request_id}"
            )));
        }

        let trimmed = line.trim_end_matches(&['\r', '\n'][..]);
        if trimmed.is_empty() {
            if let Some(res) = dispatch_sse_event(&mut data_lines, request_id)? {
                return res;
            }
            continue;
        }
        if trimmed.starts_with(':') {
            continue;
        }
        if let Some(rest) = trimmed.strip_prefix("data:") {
            let value = rest.strip_prefix(' ').unwrap_or(rest);
            data_lines.push(value.to_string());
        }
    }
}

fn dispatch_sse_event(
    data_lines: &mut Vec<String>,
    request_id: u64,
) -> Result<Option<Result<Value, McpError>>, McpError> {
    if data_lines.is_empty() {
        return Ok(None);
    }
    let payload = data_lines.join("\n");
    data_lines.clear();
    let trimmed = payload.trim();
    if trimmed.is_empty() {
        return Ok(None);
    }

    let raw: Value = serde_json::from_str(trimmed)
        .map_err(|e| McpError::Protocol(format!("invalid JSON in SSE data event: {e}")))?;
    let has_method = raw.get("method").is_some();
    let has_result_or_error = raw.get("result").is_some() || raw.get("error").is_some();
    if has_method && !has_result_or_error {
        return Ok(None);
    }
    let resp: JsonRpcResponse = serde_json::from_value(raw).map_err(|e| {
        McpError::Protocol(format!("malformed JSON-RPC response in SSE event: {e}"))
    })?;
    if resp.matches_id(request_id) || (resp.id.is_none() && resp.error.is_some()) {
        return Ok(Some(resp.into_result()));
    }
    Ok(None)
}

fn read_capped_body(resp: ureq::Response, max_bytes: usize) -> String {
    let mut reader = resp.into_reader().take(max_bytes as u64);
    let mut buf = Vec::new();
    let _ = reader.read_to_end(&mut buf);
    String::from_utf8_lossy(&buf).into_owned()
}

fn is_timeout_io_error(err: &std::io::Error) -> bool {
    matches!(
        err.kind(),
        std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock
    )
}

fn map_body_read_error(
    err: std::io::Error,
    operation: &str,
    timeout: Duration,
    context: &str,
) -> McpError {
    if is_timeout_io_error(&err) {
        McpError::Timeout {
            operation: operation.to_string(),
            timeout,
        }
    } else {
        McpError::Transport {
            message: format!("{context}: {err}"),
            stderr: None,
        }
    }
}

fn is_timeout_transport(t: &ureq::Transport) -> bool {
    if let Some(io_err) =
        std::error::Error::source(t).and_then(|s| s.downcast_ref::<std::io::Error>())
    {
        if is_timeout_io_error(io_err) {
            return true;
        }
    }
    t.message()
        .map(|m| m.to_ascii_lowercase().contains("timed out"))
        .unwrap_or(false)
}