bridgemem 0.1.0

Official lightweight HTTP and Model Context Protocol (MCP) client SDK for BridgeMem autonomous AI memory nodes.
Documentation
//! Official zero-dependency HTTP & MCP client SDK for **BridgeMem** nodes (`https://bridgemem.com`).
//!
//! Designed for connecting Rust services and AI agents to a local or private-mesh BridgeMem
//! Headless Gate (`http://<host>:8508`) with zero third-party crate dependencies.

#![forbid(unsafe_code)]

use std::fmt;
use std::io::{Read, Write};
use std::net::{TcpStream, ToSocketAddrs};
use std::time::Duration;

/// Errors returned by [`BridgeMemClient`].
#[derive(Debug)]
pub enum SdkError {
    InvalidEndpoint(String),
    Io(std::io::Error),
    HttpStatus { status: u16, body: String },
    MalformedResponse(String),
}

impl fmt::Display for SdkError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidEndpoint(msg) => write!(f, "invalid BridgeMem endpoint: {msg}"),
            Self::Io(err) => write!(f, "network I/O error: {err}"),
            Self::HttpStatus { status, body } => write!(f, "HTTP {status}: {body}"),
            Self::MalformedResponse(msg) => write!(f, "malformed HTTP response: {msg}"),
        }
    }
}

impl std::error::Error for SdkError {}

impl From<std::io::Error> for SdkError {
    fn from(value: std::io::Error) -> Self {
        Self::Io(value)
    }
}

/// Structured search request targeting a BridgeMem section.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchQuery {
    pub section_id: String,
    pub query: String,
    pub top_k: usize,
}

impl SearchQuery {
    /// Creates a new search query with a sensible default `top_k = 8`.
    pub fn new(section_id: impl Into<String>, query: impl Into<String>) -> Self {
        Self {
            section_id: section_id.into(),
            query: query.into(),
            top_k: 8,
        }
    }

    /// Sets the maximum number of evidence hits to return (`1..=100`).
    pub fn with_top_k(mut self, top_k: usize) -> Self {
        self.top_k = top_k.clamp(1, 100);
        self
    }

    /// Serializes this query into a RFC 8259 JSON payload without external dependencies.
    pub fn to_json_string(&self) -> String {
        format!(
            "{{\"section_id\":\"{}\",\"query\":\"{}\",\"top_k\":{}}}",
            escape_json_str(&self.section_id),
            escape_json_str(&self.query),
            self.top_k
        )
    }
}

/// Lightweight HTTP/1.1 & MCP JSON-RPC client for a BridgeMem Gate endpoint.
#[derive(Debug, Clone)]
pub struct BridgeMemClient {
    host_header: String,
    socket_target: String,
    base_path: String,
    bearer_token: Option<String>,
    timeout: Duration,
}

impl BridgeMemClient {
    /// Parses an `http://host:port` BridgeMem Gate URL (e.g. `http://127.0.0.1:8508`).
    pub fn new(endpoint: &str) -> Result<Self, SdkError> {
        let trimmed = endpoint.trim().trim_end_matches('/');
        let rest = trimmed.strip_prefix("http://").ok_or_else(|| {
            SdkError::InvalidEndpoint(
                "expected http://host:port endpoint (use a local TLS terminator or WireGuard tunnel for remote nodes)".into(),
            )
        })?;
        let (authority, path_part) = match rest.split_once('/') {
            Some((a, p)) => (a, format!("/{}", p.trim_matches('/'))),
            None => (rest, String::new()),
        };
        if authority.is_empty() {
            return Err(SdkError::InvalidEndpoint("empty host authority".into()));
        }
        let socket_target = if authority.contains(':') {
            authority.to_string()
        } else {
            format!("{authority}:80")
        };
        Ok(Self {
            host_header: authority.to_string(),
            socket_target,
            base_path: if path_part == "/" { String::new() } else { path_part },
            bearer_token: None,
            timeout: Duration::from_secs(10),
        })
    }

    /// Attaches a scoped BridgeMem API key (`brk_...`) or session `Bearer` token.
    pub fn with_bearer_token(mut self, token: impl Into<String>) -> Self {
        self.bearer_token = Some(token.into());
        self
    }

    /// Configures read/write socket timeout (default `10s`).
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Checks node liveness (`GET /healthz`).
    pub fn health(&self) -> Result<String, SdkError> {
        self.send_raw("GET", "/healthz", None)
    }

    /// Executes a triple-index search (`POST /api/v1/search`) and returns the raw JSON response.
    pub fn search(&self, query: &SearchQuery) -> Result<String, SdkError> {
        let body = query.to_json_string();
        self.send_raw("POST", "/api/v1/search", Some(&body))
    }

    /// Sends a Model Context Protocol (`MCP`) JSON-RPC 2.0 request to `POST /mcp`.
    pub fn mcp_rpc(&self, id: u64, method: &str, params_json: &str) -> Result<String, SdkError> {
        let payload = format!(
            "{{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"{}\",\"params\":{params_json}}}",
            escape_json_str(method)
        );
        self.send_raw("POST", "/mcp", Some(&payload))
    }

    /// Lists available MCP tools (`tools/list`) exposed by the BridgeMem node.
    pub fn mcp_list_tools(&self) -> Result<String, SdkError> {
        self.mcp_rpc(1, "tools/list", "{}")
    }

    fn send_raw(&self, method: &str, route: &str, json_body: Option<&str>) -> Result<String, SdkError> {
        let mut addrs = self
            .socket_target
            .to_socket_addrs()
            .map_err(|e| SdkError::InvalidEndpoint(format!("{}: {e}", self.socket_target)))?;
        let addr = addrs
            .next()
            .ok_or_else(|| SdkError::InvalidEndpoint("could not resolve socket address".into()))?;

        let mut stream = TcpStream::connect_timeout(&addr, self.timeout)?;
        stream.set_read_timeout(Some(self.timeout))?;
        stream.set_write_timeout(Some(self.timeout))?;

        let full_path = format!("{}{}", self.base_path, route);
        let body_bytes = json_body.unwrap_or("").as_bytes();
        let mut req = format!(
            "{method} {full_path} HTTP/1.1\r\nHost: {}\r\nAccept: application/json\r\nConnection: close\r\n",
            self.host_header
        );
        if let Some(ref tok) = self.bearer_token {
            req.push_str(&format!("Authorization: Bearer {}\r\n", tok.trim()));
        }
        if json_body.is_some() {
            req.push_str(&format!(
                "Content-Type: application/json\r\nContent-Length: {}\r\n",
                body_bytes.len()
            ));
        }
        req.push_str("\r\n");

        stream.write_all(req.as_bytes())?;
        if !body_bytes.is_empty() {
            stream.write_all(body_bytes)?;
        }
        stream.flush()?;

        let mut raw = Vec::with_capacity(4096);
        stream.read_to_end(&mut raw)?;
        parse_http_response(&raw)
    }
}

/// Escapes control characters, quotes, and backslashes per RFC 8259.
pub fn escape_json_str(input: &str) -> String {
    let mut out = String::with_capacity(input.len() + 8);
    for ch in input.chars() {
        match ch {
            '"' => out.push_str("\\\""),
            '\\' => out.push_str("\\\\"),
            '\n' => out.push_str("\\n"),
            '\r' => out.push_str("\\r"),
            '\t' => out.push_str("\\t"),
            c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
            c => out.push(c),
        }
    }
    out
}

fn parse_http_response(raw: &[u8]) -> Result<String, SdkError> {
    let sep = raw
        .windows(4)
        .position(|w| w == b"\r\n\r\n")
        .ok_or_else(|| SdkError::MalformedResponse("missing HTTP header terminator".into()))?;
    let head = std::str::from_utf8(&raw[..sep])
        .map_err(|_| SdkError::MalformedResponse("non-UTF8 HTTP status header".into()))?;
    let status_line = head
        .lines()
        .next()
        .ok_or_else(|| SdkError::MalformedResponse("empty status line".into()))?;
    let mut parts = status_line.split_whitespace();
    let _http_ver = parts.next();
    let status: u16 = parts
        .next()
        .ok_or_else(|| SdkError::MalformedResponse("missing status code".into()))?
        .parse()
        .map_err(|_| SdkError::MalformedResponse("invalid numeric status code".into()))?;

    let is_chunked = head.lines().any(|l| {
        l.to_ascii_lowercase().starts_with("transfer-encoding:")
            && l.to_ascii_lowercase().contains("chunked")
    });
    let body_slice = &raw[sep + 4..];
    let decoded = if is_chunked {
        decode_chunked(body_slice)?
    } else {
        body_slice.to_vec()
    };
    let text = String::from_utf8_lossy(&decoded).into_owned();
    if (200..300).contains(&status) {
        Ok(text)
    } else {
        Err(SdkError::HttpStatus { status, body: text })
    }
}

fn decode_chunked(mut buf: &[u8]) -> Result<Vec<u8>, SdkError> {
    let mut out = Vec::new();
    loop {
        let line_end = buf
            .windows(2)
            .position(|w| w == b"\r\n")
            .ok_or_else(|| SdkError::MalformedResponse("truncated chunk size".into()))?;
        let size_str = std::str::from_utf8(&buf[..line_end])
            .map_err(|_| SdkError::MalformedResponse("invalid chunk header".into()))?
            .split(';')
            .next()
            .unwrap_or("")
            .trim();
        let len = usize::from_str_radix(size_str, 16)
            .map_err(|_| SdkError::MalformedResponse("invalid hex chunk size".into()))?;
        buf = &buf[line_end + 2..];
        if len == 0 {
            break;
        }
        if buf.len() < len + 2 {
            return Err(SdkError::MalformedResponse("truncated chunk payload".into()));
        }
        out.extend_from_slice(&buf[..len]);
        buf = &buf[len + 2..];
    }
    Ok(out)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_query_json_escaping_and_clamping() {
        let q = SearchQuery::new("tech_docs", "quote \" and \\ newline\nok").with_top_k(500);
        assert_eq!(q.top_k, 100);
        let j = q.to_json_string();
        assert_eq!(
            j,
            r#"{"section_id":"tech_docs","query":"quote \" and \\ newline\nok","top_k":100}"#
        );
    }

    #[test]
    fn test_endpoint_validation_and_http_parser() {
        assert!(BridgeMemClient::new("https://bridgemem.com").is_err());
        let c = BridgeMemClient::new("http://127.0.0.1:8508/").unwrap();
        assert_eq!(c.socket_target, "127.0.0.1:8508");

        let raw = b"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\r\n{\"ok\":true}";
        assert_eq!(parse_http_response(raw).unwrap(), "{\"ok\":true}");
    }
}