OXYGENHUB

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

87 of 89 lines run, 37 of 88 functions · run #11 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 {
2124×
    pub fn json(&self) -> Result<serde_json::Value> {
2224×
        serde_json::from_slice(&self.body).with_context(|| format!("not JSON: {}", String::from_utf8_lossy(&self.body)))
2324×
    }
2423×
    pub fn header(&self, name: &str) -> Option<&str> {
2523×
        self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
2623×
    }
27
}
28
29
pub struct Client {
30
    socket: PathBuf,
31
    signer: Option<KeyPair>,
32
}
33
34
impl Client {
3514×
    pub fn new(socket: &Path, signer: Option<KeyPair>) -> Client {
3614×
        Client { socket: socket.to_path_buf(), signer }
3714×
    }
38
39
    /// Whether a daemon answers on the socket.
4031×
    pub async fn alive(socket: &Path) -> bool {
4131×
        tokio::net::UnixStream::connect(socket).await.is_ok()
4231×
    }
43
44
    /// Send `method path` with `body` and extra headers, signed.
4539×
    pub async fn send(&self, method: &str, path: &str, headers: &[(&str, String)], body: Vec<u8>) -> Result<Response> {
4639×
        let stream = tokio::net::UnixStream::connect(&self.socket)
4739×
            .await
4839×
            .with_context(|| format!("connecting to {} (is `spectra serve` running?)", self.socket.display()))?;
4939×
        let (mut sender, conn) = hyper::client::conn::http1::handshake(hyper_util::rt::TokioIo::new(stream)).await?;
5039×
        tokio::spawn(async move {
5139×
            let _ = conn.await;
5239×
        });
5339×
        let mut req = hyper::Request::builder()
5439×
            .method(method)
5539×
            .uri(path)
5639×
            .header("host", "spectra")
5739×
            .header("content-type", "application/json")
5839×
            .header("connection", "close");
59
        // One request a connection: the server closes it after answering, so
60
        // nothing lingers to hold up its shutdown.
61129×
        for (k, v) in headers {
62129×
            req = req.header(*k, v);
63129×
        }
6439×
        if let Some(pair) = &self.signer {
65152×
            for (k, v) in sign_headers(pair, &format!("{method} {path}"), &body) {
66152×
                req = req.header(k, v);
67152×
            }
681×
        }
6939×
        let resp = sender.send_request(req.body(Full::new(Bytes::from(body)))?).await?;
7039×
        let status = resp.status().as_u16();
71164×
        let headers = resp.headers().iter().map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("").to_string())).collect();
7239×
        let body = resp.into_body().collect().await?.to_bytes().to_vec();
7339×
        Ok(Response { status, headers, body })
7439×
    }
75
76
    /// A JSON-RPC request to `/mcp` with the protocol headers of `version`.
7733×
    pub async fn mcp(&self, version: &str, request: &serde_json::Value) -> Result<Response> {
7833×
        let method = request.get("method").and_then(|m| m.as_str()).unwrap_or("").to_string();
7933×
        let mut headers = vec![
8033×
            ("accept", "application/json, text/event-stream".to_string()),
8133×
            ("mcp-protocol-version", version.to_string()),
8233×
            ("mcp-method", method.clone()),
83
        ];
8433×
        if let Some(name) = request.pointer("/params/name").or_else(|| request.pointer("/params/uri")).and_then(|n| n.as_str()) {
8524×
            headers.push(("mcp-name", name.to_string()));
8624×
        }
8733×
        self.send("POST", "/mcp", &headers, serde_json::to_vec(request)?).await
8833×
    }
89
}
90
91
/// The signature headers of spec §8.5 for `method_path` and `body`.
9238×
pub fn sign_headers(pair: &KeyPair, method_path: &str, body: &[u8]) -> Vec<(&'static str, String)> {
9338×
    let p = Proof::sign(pair, method_path, body);
9438×
    vec![
9538×
        ("spectra-key", p.sig.key.to_hex()),
9638×
        ("spectra-time", p.time_ms.to_string()),
9738×
        ("spectra-nonce", hex::encode(p.nonce)),
9838×
        ("spectra-signature", hex::encode(oxy_core::cbor::encode(&p.sig.to_value()))),
99
    ]
10038×
}
101
102
/// The JSON-RPC result inside a response, whether it came as JSON or as
103
/// the last `data:` of an SSE stream.
10423×
pub fn rpc_result(r: &Response) -> Result<serde_json::Value> {
10523×
    let is_sse = r.header("content-type").is_some_and(|c| c.starts_with("text/event-stream"));
10623×
    if !is_sse {
10718×
        return r.json();
1085×
    }
1095×
    let text = String::from_utf8_lossy(&r.body);
1105×
    let last = text
1115×
        .lines()
1125×
        .rev()
11310×
        .filter_map(|l| l.strip_prefix("data:"))
1145×
        .map(str::trim)
1155×
        .find(|l| !l.is_empty())
1165×
        .context("an SSE response with no data")?;
1175×
    Ok(serde_json::from_str(last)?)
11823×
}