Struct HttpTransport

Source
pub struct HttpTransport { /* private fields */ }
Expand description

HTTP-based MCP transport

Provides communication with MCP servers over HTTP using JSON-RPC 2.0 protocol. This transport is ideal for RESTful MCP services, public APIs, and servers behind load balancers. Supports both regular JSON responses and Server-Sent Events (SSE).

§Features

  • HTTP/HTTPS Support: Secure communication with TLS encryption
  • Server-Sent Events: Handles streaming responses via SSE format
  • Bearer Token Authentication: Automatic Authorization header injection
  • Custom Headers: Support for additional headers (API keys, versioning, etc.)
  • Configurable Timeouts: Request-level timeout control
  • Error Handling: Comprehensive JSON-RPC and HTTP error handling

§Use Cases

  • Public MCP APIs: Connect to hosted MCP services
  • RESTful Services: Integration with REST-based tool providers
  • Load-Balanced Servers: Works well behind HTTP load balancers
  • Development/Testing: Easy debugging with standard HTTP tools

§Example Usage

use mistralrs_mcp::transport::{HttpTransport, McpTransport};
use std::collections::HashMap;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    // Create headers with Bearer token and API version
    let mut headers = HashMap::new();
    headers.insert("Authorization".to_string(), "Bearer your-api-token".to_string());
    headers.insert("X-API-Version".to_string(), "v1".to_string());

    // Connect to HTTP MCP server
    let transport = HttpTransport::new(
        "https://api.example.com/mcp".to_string(),
        Some(30), // 30 second timeout
        Some(headers)
    )?;

    // Use the transport for MCP communication
    let result = transport.send_request("tools/list", serde_json::Value::Null).await?;
    println!("Available tools: {}", result);

    Ok(())
}

§Protocol Support

This transport implements JSON-RPC 2.0 over HTTP with support for:

  • Standard JSON responses
  • Server-Sent Events (SSE) for streaming data
  • Bearer token authentication
  • Custom HTTP headers

Implementations§

Source§

impl HttpTransport

Source

pub fn new( base_url: String, timeout_secs: Option<u64>, headers: Option<HashMap<String, String>>, ) -> Result<Self>

Creates a new HTTP transport for MCP communication

§Arguments
  • base_url - Base URL of the MCP server (http:// or https://)
  • timeout_secs - Optional timeout for HTTP requests in seconds (defaults to 30s)
  • headers - Optional custom headers to include in all requests
§Returns

A configured HttpTransport ready for MCP communication

§Errors
  • Invalid URL format
  • HTTP client configuration errors
  • TLS/SSL setup failures
§Example
use mistralrs_mcp::transport::HttpTransport;
use std::collections::HashMap;

// Basic HTTP transport
let transport = HttpTransport::new(
    "https://api.example.com/mcp".to_string(),
    Some(60), // 1 minute timeout
    None
)?;

// With custom headers and authentication
let mut headers = HashMap::new();
headers.insert("Authorization".to_string(), "Bearer token123".to_string());
headers.insert("X-Client-Version".to_string(), "1.0.0".to_string());

let transport = HttpTransport::new(
    "https://secure-api.example.com/mcp".to_string(),
    Some(30),
    Some(headers)
)?;

Trait Implementations§

Source§

impl McpTransport for HttpTransport

Source§

fn send_request<'life0, 'life1, 'async_trait>( &'life0 self, method: &'life1 str, params: Value, ) -> Pin<Box<dyn Future<Output = Result<Value>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait, 'life1: 'async_trait,

Sends an MCP request over HTTP and returns the response

This method implements JSON-RPC 2.0 over HTTP with support for both standard JSON responses and Server-Sent Events (SSE). It handles authentication, custom headers, and comprehensive error reporting.

§Arguments
  • method - The MCP method name (e.g., “tools/list”, “tools/call”, “resources/read”)
  • params - JSON parameters for the method call
§Returns

The result portion of the JSON-RPC response

§Errors
  • HTTP connection errors (network issues, DNS resolution)
  • HTTP status errors (4xx, 5xx responses)
  • JSON serialization/deserialization errors
  • MCP server errors (returned in JSON-RPC error field)
  • SSE parsing errors for streaming responses
§Example
use mistralrs_mcp::transport::{HttpTransport, McpTransport};
use serde_json::json;

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let transport = HttpTransport::new(
        "https://api.example.com/mcp".to_string(),
        None,
        None
    )?;
     
    // List available tools
    let tools = transport.send_request("tools/list", serde_json::Value::Null).await?;
     
    // Call a specific tool
    let params = json!({
        "name": "search",
        "arguments": {"query": "example search"}
    });
    let result = transport.send_request("tools/call", params).await?;
     
    Ok(())
}
Source§

fn ping<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Tests the HTTP connection by sending a ping request

Sends a “ping” method call to verify that the MCP server is responsive and the HTTP connection is working properly.

§Returns

Ok(()) if the ping was successful

§Errors
  • HTTP connection errors
  • Server unavailable or unresponsive
  • Authentication failures
Source§

fn close<'life0, 'async_trait>( &'life0 self, ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + 'async_trait>>
where Self: 'async_trait, 'life0: 'async_trait,

Closes the HTTP transport connection

HTTP connections are stateless and managed by the underlying HTTP client, so this method is a no-op but provided for interface compatibility.

§Returns

Always returns Ok(()) as HTTP connections don’t require explicit cleanup

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> IntoEither for T

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
§

impl<T> PolicyExt for T
where T: ?Sized,

§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] only if self and other return Action::Follow. Read more
§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns [Action::Follow] if either self or other returns Action::Follow. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

§

fn vzip(self) -> V

§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

impl<T> ErasedDestructor for T
where T: 'static,

§

impl<T> Ungil for T
where T: Send,