blyte 0.90.0

The blyte coding-agent harness: headless runs with a sealed verification gate, and a REPL.
Documentation
//! High-level MCP JSON-RPC 2.0 client over stdio and Streamable HTTP transports.

use std::collections::BTreeMap;
use std::time::Duration;

use serde_json::{json, Value};

use crate::mcp::config::{ConfiguredServer, EnvLookup, ServerTransport};
use crate::mcp::http::StreamableHttpTransport;
use crate::mcp::protocol::{
    ImplementationInfo, InitializeResult, McpError, Tool, ToolCallResult, ToolsListResult,
    MCP_PROTOCOL_VERSION,
};
use crate::mcp::stdio::StdioTransport;

/// Default request timeout for MCP JSON-RPC calls.
pub const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);

const MAX_TOOLS_PAGES: usize = 100;

/// Underlying bidirectional JSON-RPC 2.0 transport used by [`McpClient`].
pub trait McpTransport: Send {
    fn send_request(
        &mut self,
        request_id: u64,
        method: &str,
        params: Option<Value>,
        timeout: Duration,
    ) -> Result<Value, McpError>;

    fn send_notification(
        &mut self,
        method: &str,
        params: Option<Value>,
        timeout: Duration,
    ) -> Result<(), McpError>;
}

/// Model Context Protocol client supporting `initialize`, `tools/list`, and `tools/call`.
pub struct McpClient {
    transport: Box<dyn McpTransport>,
    next_id: u64,
    timeout: Duration,
    initialized: Option<InitializeResult>,
}

impl McpClient {
    /// Wraps any [`McpTransport`] implementation.
    pub fn new(transport: impl McpTransport + 'static) -> Self {
        Self {
            transport: Box::new(transport),
            next_id: 1,
            timeout: DEFAULT_TIMEOUT,
            initialized: None,
        }
    }

    /// Overrides the per-request timeout.
    pub fn with_timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// Updates the per-request timeout on an existing client.
    pub fn set_timeout(&mut self, timeout: Duration) {
        self.timeout = timeout;
    }

    /// Spawns a stdio MCP server and returns an uninitialized client.
    pub fn open_stdio(
        command: &str,
        args: &[String],
        env: &BTreeMap<String, String>,
        timeout: Duration,
    ) -> Result<Self, McpError> {
        let transport = StdioTransport::spawn(command, args, env)?;
        Ok(Self::new(transport).with_timeout(timeout))
    }

    /// Creates a Streamable HTTP MCP client (uninitialized).
    pub fn open_http(
        url: impl Into<String>,
        headers: BTreeMap<String, String>,
        bearer_token: Option<String>,
        timeout: Duration,
    ) -> Self {
        let transport = StreamableHttpTransport::new(url, headers, bearer_token);
        Self::new(transport).with_timeout(timeout)
    }

    /// Opens a transport for a validated [`ConfiguredServer`].
    /// Refuses untrusted project servers before spawning commands or making HTTP requests.
    pub fn open_server(
        server: &ConfiguredServer,
        env_lookup: &EnvLookup,
        bearer_token: Option<String>,
        timeout: Duration,
    ) -> Result<Self, McpError> {
        if !server.trusted {
            return Err(McpError::UntrustedProjectServer {
                name: server.name.clone(),
                path: server.source_path.clone(),
            });
        }
        match server.resolve_transport(env_lookup)? {
            ServerTransport::Stdio { command, args, env } => {
                Self::open_stdio(&command, &args, &env, timeout)
            }
            ServerTransport::Http { url, headers } => {
                Ok(Self::open_http(url, headers, bearer_token, timeout))
            }
        }
    }

    /// Opens and performs the MCP `initialize` handshake for a [`ConfiguredServer`].
    pub fn connect_server(
        server: &ConfiguredServer,
        env_lookup: &EnvLookup,
        bearer_token: Option<String>,
        timeout: Duration,
    ) -> Result<(Self, InitializeResult), McpError> {
        let mut client = Self::open_server(server, env_lookup, bearer_token, timeout)?;
        let init = client.initialize()?;
        Ok((client, init))
    }

    /// Returns the cached `InitializeResult` if `initialize` has completed.
    pub fn server_info(&self) -> Option<&InitializeResult> {
        self.initialized.as_ref()
    }

    /// Runs the MCP `initialize` request followed by `notifications/initialized`.
    pub fn initialize(&mut self) -> Result<InitializeResult, McpError> {
        let params = json!({
            "protocolVersion": MCP_PROTOCOL_VERSION,
            "capabilities": {},
            "clientInfo": ImplementationInfo::blyte(),
        });
        let raw = self.request("initialize", Some(params))?;
        let result: InitializeResult = serde_json::from_value(raw)
            .map_err(|e| McpError::Protocol(format!("invalid 'initialize' result payload: {e}")))?;
        self.notify("notifications/initialized", None)?;
        self.initialized = Some(result.clone());
        Ok(result)
    }

    /// Fetches a single page from `tools/list`.
    pub fn list_tools_page(&mut self, cursor: Option<&str>) -> Result<ToolsListResult, McpError> {
        let params = match cursor {
            Some(c) => Some(json!({ "cursor": c })),
            None => Some(json!({})),
        };
        let raw = self.request("tools/list", params)?;
        serde_json::from_value(raw)
            .map_err(|e| McpError::Protocol(format!("invalid 'tools/list' result payload: {e}")))
    }

    /// Fetches all tools from `tools/list`, following `nextCursor` pagination if returned.
    pub fn list_tools(&mut self) -> Result<Vec<Tool>, McpError> {
        let mut tools = Vec::new();
        let mut cursor: Option<String> = None;
        for _ in 0..MAX_TOOLS_PAGES {
            let page = self.list_tools_page(cursor.as_deref())?;
            tools.extend(page.tools);
            match page.next_cursor {
                Some(next) if !next.is_empty() => cursor = Some(next),
                _ => return Ok(tools),
            }
        }
        Err(McpError::Protocol(format!(
            "'tools/list' exceeded maximum pagination depth ({MAX_TOOLS_PAGES} pages)"
        )))
    }

    /// Invokes a tool via `tools/call` and returns structured content blocks and `isError`.
    pub fn call_tool(&mut self, name: &str, arguments: Value) -> Result<ToolCallResult, McpError> {
        let params = json!({
            "name": name,
            "arguments": arguments,
        });
        let raw = self.request("tools/call", Some(params))?;
        serde_json::from_value(raw)
            .map_err(|e| McpError::Protocol(format!("invalid 'tools/call' result payload: {e}")))
    }

    /// Sends a JSON-RPC 2.0 request and returns its `result` value.
    pub fn request(&mut self, method: &str, params: Option<Value>) -> Result<Value, McpError> {
        let id = self.next_id;
        self.next_id += 1;
        self.transport
            .send_request(id, method, params, self.timeout)
    }

    /// Sends a JSON-RPC 2.0 notification (no `id`).
    pub fn notify(&mut self, method: &str, params: Option<Value>) -> Result<(), McpError> {
        self.transport
            .send_notification(method, params, self.timeout)
    }
}