Skip to main content

Server

Struct Server 

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

An MCP server instance.

Servers are built using ServerBuilder and can run on various transports (stdio, SSE, WebSocket).

Implementations§

Source§

impl Server

Source

pub fn new(name: impl Into<String>, version: impl Into<String>) -> ServerBuilder

Creates a new server builder.

Source

pub fn info(&self) -> &ServerInfo

Returns the server info.

Source

pub fn capabilities(&self) -> &ServerCapabilities

Returns the server capabilities.

Source

pub fn tools(&self) -> Vec<Tool>

Lists all registered tools.

Source

pub fn resources(&self) -> Vec<Resource>

Lists all registered resources.

Source

pub fn resource_templates(&self) -> Vec<ResourceTemplate>

Lists all registered resource templates.

Source

pub fn prompts(&self) -> Vec<Prompt>

Lists all registered prompts.

Source

pub fn task_manager(&self) -> Option<&SharedTaskManager>

Returns the task manager, if configured.

Returns None if background tasks are not enabled.

Source

pub fn into_router(self) -> Router

Consumes the server and returns its router.

This is used for mounting one server’s components into another.

Source

pub fn has_tools(&self) -> bool

Returns the capabilities this server provides.

This is useful when determining what components a server has before mounting.

Source

pub fn has_resources(&self) -> bool

Returns whether this server has resources.

Source

pub fn has_prompts(&self) -> bool

Returns whether this server has prompts.

Source

pub fn stats(&self) -> Option<StatsSnapshot>

Returns a point-in-time snapshot of server statistics.

Returns None if statistics collection is disabled.

Source

pub fn stats_collector(&self) -> Option<&ServerStats>

Returns the raw statistics collector.

Useful for advanced scenarios where you need direct access. Returns None if statistics collection is disabled.

Source

pub fn display_stats(&self)

Renders a stats panel to stderr, if stats are enabled.

Source

pub fn console_config(&self) -> &ConsoleConfig

Returns the console configuration.

Source

pub fn dispatch_request( &self, cx: &Cx, session: &mut Session, request: JsonRpcRequest, notification_sender: &NotificationSender, request_sender: &RequestSender, ) -> Option<JsonRpcResponse>

Processes a single JSON-RPC request through the full server dispatch pipeline (initialization checks, middleware, routing, tool/resource/prompt execution, error masking, and statistics recording).

This is the public equivalent of the internal handle_request method that the built-in transports (run_stdio, run_http, etc.) use. It allows external code to drive the server from a custom transport or embedding without going through a Transport abstraction.

§Parameters
  • cx — The cancellation / budget context for this request.
  • session — Mutable reference to the session for this connection. The caller is responsible for session lifecycle (creation, sharing, locking if shared across threads).
  • request — The incoming JSON-RPC request (or notification).
  • notification_sender — Callback used to push server-initiated notifications (e.g. progress) back to the client.
  • request_sender — Sender for server-to-client requests (sampling, elicitation, roots).
§Returns

Some(JsonRpcResponse) for normal requests, or None for notifications (JSON-RPC messages without an id).

§Example
use std::sync::Arc;
use fastmcp_rust::{
    Server, Session, JsonRpcRequest, NotificationSender,
    bidirectional::RequestSender,
};
use fastmcp_core::Cx;

let server = Arc::new(
    Server::new("my-server", "1.0.0").build(),
);
let mut session = Session::new();
let cx = Cx::for_request();
let notify: NotificationSender = Arc::new(|_| {});
let req_sender = RequestSender::noop();

let request: JsonRpcRequest = /* ... */;
let response = server.dispatch_request(
    &cx, &mut session, request, &notify, &req_sender,
);
Source

pub fn dispatch_request_concurrent( &self, cx: &Cx, session: &Arc<Mutex<Session>>, request: JsonRpcRequest, notification_sender: &NotificationSender, request_sender: &RequestSender, ) -> Option<JsonRpcResponse>

Processes a single JSON-RPC request with automatic concurrency classification, allowing read-only requests to execute without holding the session mutex for the duration of the handler.

This is the concurrent counterpart of dispatch_request. Use it when the session is shared across threads behind an Arc<Mutex<Session>> (e.g. in HTTP or WebSocket transports where multiple requests may arrive simultaneously).

Internally, each request is classified into one of two execution modes:

  • ConcurrentReadOnly (resources/read, prompts/get, and tools/call on read-only tools): a lightweight session snapshot is taken and the mutex is released immediately, so other requests can proceed in parallel.
  • ExclusiveSession (everything else): the mutex is held for the full duration of the handler, guaranteeing exclusive access to session state.

Mutex poisoning is recovered from automatically (the poisoned inner value is used), matching the behaviour of the internal HTTP handler.

§Parameters
  • cx — The cancellation / budget context for this request.
  • session — Shared, mutex-protected session for this connection.
  • request — The incoming JSON-RPC request (or notification).
  • notification_sender — Callback used to push server-initiated notifications (e.g. progress) back to the client.
  • request_sender — Sender for server-to-client requests (sampling, elicitation, roots).
§Returns

Some(JsonRpcResponse) for normal requests, or None for notifications (JSON-RPC messages without an id).

§Example
use std::sync::{Arc, Mutex};
use fastmcp_rust::{
    Server, Session, JsonRpcRequest, NotificationSender,
    bidirectional::RequestSender,
};
use fastmcp_core::Cx;

let server = Arc::new(
    Server::new("my-server", "1.0.0").build(),
);
let session = Arc::new(Mutex::new(Session::new()));
let cx = Cx::for_request();
let notify: NotificationSender = Arc::new(|_| {});
let req_sender = RequestSender::noop();

let request: JsonRpcRequest = /* ... */;
let response = server.dispatch_request_concurrent(
    &cx, &session, request, &notify, &req_sender,
);
Source

pub fn run_stdio(self) -> !

Runs the server on stdio transport.

This is the primary way to run MCP servers as subprocesses. Creates a request-scoped Cx and runs the server loop.

Source

pub fn run_stdio_with_cx(self, cx: &Cx) -> !

Runs the server on stdio with a provided Cx.

This allows integration with a real asupersync runtime.

Source

pub fn run_transport<T>(self, transport: T) -> !
where T: Transport + Send + 'static,

Runs the server on a custom transport with a request-scoped Cx.

This is useful for SSE/WebSocket integrations where the transport is provided by an external server framework.

Source

pub fn run_transport_with_cx<T>(self, cx: &Cx, transport: T) -> !
where T: Transport + Send + 'static,

Runs the server on a custom transport with a provided Cx.

This allows integration with a real asupersync runtime.

Source

pub fn run_transport_returning_with_cx<T>(self, cx: &Cx, transport: T)
where T: Transport + Send + 'static,

Runs the server on a custom transport and returns when the transport closes or the Cx is cancelled.

Unlike run_transport_with_cx, this does not call std::process::exit on shutdown. This is useful for tests and embedding where you need the server loop to be joinable.

Source

pub fn run_transport_returning<T>(self, transport: T)
where T: Transport + Send + 'static,

Runs the server on a custom transport and returns when the transport closes.

This uses a request-scoped Cx, but unlike run_transport it does not exit the process.

Source

pub fn run_sse<W, R>( self, writer: W, request_source: R, endpoint_url: impl Into<String>, ) -> !
where W: Write + Send + 'static, R: Iterator<Item = JsonRpcRequest> + Send + 'static,

Runs the server using SSE transport with a testing Cx.

This is a convenience wrapper around SseServerTransport.

Source

pub fn run_sse_with_cx<W, R>( self, cx: &Cx, writer: W, request_source: R, endpoint_url: impl Into<String>, ) -> !
where W: Write + Send + 'static, R: Iterator<Item = JsonRpcRequest> + Send + 'static,

Runs the server using SSE transport with a provided Cx.

Source

pub fn run_websocket<R, W>(self, reader: R, writer: W) -> !
where R: Read + Send + 'static, W: Write + Send + 'static,

Runs the server using WebSocket transport with a testing Cx.

This is a convenience wrapper around WsTransport.

Source

pub fn run_websocket_with_cx<R, W>(self, cx: &Cx, reader: R, writer: W) -> !
where R: Read + Send + 'static, W: Write + Send + 'static,

Runs the server using WebSocket transport with a provided Cx.

Source

pub fn run_http(self, addr: impl Into<String>) -> !

Runs the server on HTTP transport, listening on the given address.

This is the HTTP equivalent of run_stdio. It binds a TCP listener, accepts connections, and dispatches MCP JSON-RPC requests over HTTP.

§Routes
MethodPathDescription
POST/mcpMCP JSON-RPC handler
GET/healthHealth check ({"status": "ok"})
OPTIONS/mcpCORS preflight (via HttpRequestHandler)
§Example
Server::new("my-server", "1.0.0")
    .tool(my_tool)
    .build()
    .run_http("0.0.0.0:3000");
Source

pub fn run_http_with_cx(self, cx: &Cx, addr: impl Into<String>) -> !

Runs the server on HTTP with a provided Cx.

This allows integration with a real asupersync runtime.

Source

pub fn run_http_returning(self, addr: impl Into<String>)

Runs the server on HTTP and returns when the listener closes or the Cx is cancelled.

Unlike run_http, this does not call std::process::exit on shutdown. This is useful for tests and embedding.

Source

pub fn run_http_returning_with_cx(self, cx: &Cx, addr: impl Into<String>)

Full control: custom Cx + returns on shutdown.

Auto Trait Implementations§

§

impl !Freeze for Server

§

impl !RefUnwindSafe for Server

§

impl Send for Server

§

impl Sync for Server

§

impl Unpin for Server

§

impl UnsafeUnpin for Server

§

impl !UnwindSafe for Server

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.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, _span: NoopSpan) -> Self

Instruments this future with a span (no-op when disabled).
Source§

fn in_current_span(self) -> Self

Instruments this future with the current span (no-op when disabled).
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> 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<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