Skip to main content

WebSocketTransport

Struct WebSocketTransport 

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

WebSocket transport for MCP servers

Provides full-duplex communication over WebSocket.

WebSocket is a tower-mcp custom transport binding, not a standard 2026-07-28 MCP transport. JSON-RPC request bodies remain the source of truth for final per-request metadata. The optional mcp.version.* subprotocol is an upgrade-time compatibility hint constrained by this transport’s exact ProtocolSupport allow-list.

Connection and cancellation semantics remain those of this custom binding: a WebSocket close terminates the connection, and reconnecting a stored session closes the older socket. It does not currently cancel an in-flight handler. notifications/cancelled is processed between requests, so it cannot interrupt a handler that is already executing. Final subscriptions/listen multiplexing is not implemented on this binding.

Implementations§

Source§

impl WebSocketTransport

Source

pub fn new(router: McpRouter) -> Self

Create a new WebSocket transport

Source

pub fn with_sampling(self) -> Self

Enable sampling support for this transport.

When sampling is enabled, tool handlers can use ctx.sample() to request LLM completions from connected clients.

Source

pub fn protocol_support(self, support: ProtocolSupport) -> Self

Set the exact protocol versions this custom binding accepts.

Source

pub fn protocol_versions<I, V>( self, versions: I, ) -> Result<Self, ProtocolSupportError>
where I: IntoIterator<Item = V>, V: Into<String>,

Construct and set an exact runtime protocol-version allow-list.

Source

pub fn oauth(self, metadata: ProtectedResourceMetadata) -> Self

Configure OAuth 2.1 Protected Resource Metadata for this transport.

When set, adds a GET endpoint at the resource’s path-aware RFC 9728 well-known location. This method only serves metadata; prefer Self::into_oauth_router for a complete protected setup.

§Example
use tower_mcp::oauth::ProtectedResourceMetadata;
use tower_mcp::transport::websocket::WebSocketTransport;
use tower_mcp::McpRouter;

let metadata = ProtectedResourceMetadata::new("https://mcp.example.com")
    .authorization_server("https://auth.example.com")
    .scope("mcp:read");

let router = McpRouter::new().server_info("my-server", "1.0.0");
let transport = WebSocketTransport::new(router).oauth(metadata);
Source

pub fn into_oauth_router<V>( self, validator: V, metadata: ProtectedResourceMetadata, policy: ScopePolicy, ) -> Result<Router, ProtectedResourceMetadataError>
where V: TokenValidator,

Build a fully protected OAuth WebSocket resource-server router.

This validates and serves Protected Resource Metadata, authenticates WebSocket upgrades, enforces the canonical resource audience, and installs fail-closed per-operation scope checks.

Source

pub fn into_oauth_router_at<V>( self, path: &str, validator: V, metadata: ProtectedResourceMetadata, policy: ScopePolicy, ) -> Result<Router, ProtectedResourceMetadataError>
where V: TokenValidator,

Build a path-mounted, fully protected OAuth WebSocket router.

Source

pub fn layer<L>(self, layer: L) -> Self
where L: Layer<McpRouter> + Send + Sync + 'static, L::Service: Service<RouterRequest, Response = RouterResponse> + Clone + Send + 'static, <L::Service as Service<RouterRequest>>::Error: Display + Send, <L::Service as Service<RouterRequest>>::Future: Send,

Apply a tower middleware layer to MCP request processing.

The layer is applied to the McpRouter service within each session, wrapping the Service<RouterRequest> pipeline. This allows middleware like timeouts, rate limiting, or custom instrumentation to be applied at the MCP request level.

Middleware errors are automatically converted into JSON-RPC error responses, so the transport’s error handling remains unchanged.

§Example
use std::time::Duration;
use tower::ServiceBuilder;
use tower::timeout::TimeoutLayer;
use tower_mcp::McpRouter;
use tower_mcp::transport::websocket::WebSocketTransport;

let router = McpRouter::new().server_info("my-server", "1.0.0");
let transport = WebSocketTransport::new(router)
    .layer(
        ServiceBuilder::new()
            .layer(TimeoutLayer::new(Duration::from_secs(30)))
            .concurrency_limit(10)
            .into_inner(),
    );
Source

pub fn into_router(self) -> Router

Build the axum router for this transport

Source

pub fn into_router_at(self, path: &str) -> Router

Build an axum router mounted at a specific path

Source

pub async fn serve(self, addr: &str) -> Result<()>

Serve the transport on the given address

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,

Source§

impl<T> Instrument for T

Source§

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

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

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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Sized + 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> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

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.
Source§

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

Source§

fn vzip(self) -> V

Source§

impl<T> WithSubscriber for T

Source§

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
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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