OXYGENHUB

Coverage / crates/spectra-mcp/src/client.rs 83.5%

71 of 85 lines run, 22 of 64 functions · run #8 on main · run missed

1
//! A client for the daemon over its Unix socket (spec §8.5), signing every
2
//! request with the caller's key: the shims and the CLI use it, and so do
3
//! the tests.
4
5
use anyhow::{Context, Result};
6
use http_body_util::{BodyExt, Full};
7
use hyper::body::Bytes;
8
use spectra_core::keys::KeyPair;
9
use spectra_core::proof::Proof;
10
use std::path::{Path, PathBuf};
11
12
/// A response, its body read whole.
13
#[derive(Debug)]
14
pub struct Response {
15
    pub status: u16,
16
    pub headers: Vec<(String, String)>,
17
    pub body: Vec<u8>,
18
}
19
20
impl Response {
216×
    pub fn json(&self) -> Result<serde_json::Value> {
226×
        serde_json::from_slice(&self.body).with_context(|| format!("not JSON: {}", String::from_utf8_lossy(&self.body)))
236×
    }
241×
    pub fn header(&self, name: &str) -> Option<&str> {
251×
        self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
261×
    }
27
}
28
29
pub struct Client {
30
    socket: PathBuf,
31
    signer: Option<KeyPair>,
32
}
33
34
impl Client {
358×
    pub fn new(socket: &Path, signer: Option<KeyPair>) -> Client {
368×
        Client { socket: socket.to_path_buf(), signer }
378×
    }
38
39
    /// Whether a daemon answers on the socket.
4018×
    pub async fn alive(socket: &Path) -> bool {
4118×
        tokio::net::UnixStream::connect(socket).await.is_ok()
4218×
    }
43
44
    /// Send `method path` with `body` and extra headers, signed.
4515×
    pub async fn send(&self, method: &str, path: &str, headers: &[(&str, String)], body: Vec<u8>) -> Result<Response> {
4615×
        let stream = tokio::net::UnixStream::connect(&self.socket)
4715×
            .await
4815×
            .with_context(|| format!("connecting to {} (is `spectra serve` running?)", self.socket.display()))?;
4915×
        let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?;
5015×
        tokio::spawn(async move {
5115×
            let _ = conn.await;
5213×
        });
5315×
        let mut req =
5415×
            hyper::Request::builder().method(method).uri(path).header("host", "spectra").header("content-type", "application/json");
5534×
        for (k, v) in headers {
5634×
            req = req.header(*k, v);
5734×
        }
5815×
        if let Some(pair) = &self.signer {
5956×
            for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) {
6056×
                req = req.header(k, v);
6156×
            }
621×
        }
6315×
        let resp = sender.send_request(req.body(Full::new(Bytes::from(body)))?).await?;
6415×
        let status = resp.status().as_u16();
6543×
        let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect();
6615×
        let body = resp.into_body().collect().await?.to_bytes().to_vec();
6715×
        Ok(Response { status, headers, body })
6815×
    }
69
70
    /// A JSON-RPC request to `/mcp` with the protocol headers of `version`.
719×
    pub async fn mcp(&self, version: &str, request: &serde_json::Value) -> Result<Response> {
729×
        let method = request.get("method").and_then(|m| m.as_str()).unwrap_or("").to_string();
739×
        let mut headers = vec![
749×
            ("accept", "application/json, text/event-stream".to_string()),
759×
            ("mcp-protocol-version", version.to_string()),
769×
            ("mcp-method", method.clone()),
77
        ];
789×
        if let Some(name) = request.pointer("/params/name").or_else(|| request.pointer("/params/uri")).and_then(|n| n.as_str()) {
791×
            headers.push(("mcp-name", name.to_string()));
808×
        }
819×
        self.send("POST", "/mcp", &headers, serde_json::to_vec(request)?).await
829×
    }
83
}
84
85
/// The signature headers of spec §8.5 for `method_path` and `body`.
8614×
pub fn sign_headers(pair: &KeyPair, method_path: &str, body: &[u8]) -> Vec<(&'static str, String)> {
8714×
    let p = Proof::sign(pair, method_path, body);
8814×
    vec![
8914×
        ("spectra-key", p.sig.key.to_hex()),
9014×
        ("spectra-time", p.time_ms.to_string()),
9114×
        ("spectra-nonce", hex::encode(p.nonce)),
9214×
        ("spectra-signature", hex::encode(oxy_core::cbor::encode(&p.sig.to_value()))),
93
    ]
9414×
}
95
96
/// The JSON-RPC result inside a response, whether it came as JSON or as
97
/// the last `data:` of an SSE stream.
981×
pub fn rpc_result(r: &Response) -> Result<serde_json::Value> {
991×
    let is_sse = r.header("content-type").is_some_and(|c| c.starts_with("text/event-stream"));
1001×
    if !is_sse {
1011×
        return r.json();
1020×
    }
1030×
    let text = String::from_utf8_lossy(&r.body);
1040×
    let last = text
1050×
        .lines()
1060×
        .rev()
1070×
        .filter_map(|l| l.strip_prefix("data:"))
1080×
        .map(str::trim)
1090×
        .find(|l| !l.is_empty())
1100×
        .context("an SSE response with no data")?;
1110×
    Ok(serde_json::from_str(last)?)
1121×
}