Skip to main content

ServerBuilder

Struct ServerBuilder 

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

Builder for configuring an MCP server.

Implementations§

Source§

impl ServerBuilder

Source

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

Creates a new server builder.

Statistics collection is enabled by default. Use without_stats to disable it for performance-critical scenarios.

Console configuration defaults to environment-based settings. Use with_console_config for programmatic control.

Source

pub fn on_duplicate(self, behavior: DuplicateBehavior) -> ServerBuilder

Sets the behavior when registering duplicate component names.

Controls what happens when a tool, resource, or prompt is registered with a name that already exists:

§Example
Server::new("demo", "1.0")
    .on_duplicate(DuplicateBehavior::Error)  // Strict mode
    .tool(handler1)
    .tool(handler2)  // Fails if name conflicts
    .build();
Source

pub fn auth_provider<P>(self, provider: P) -> ServerBuilder
where P: AuthProvider + 'static,

Sets an authentication provider.

Source

pub fn without_stats(self) -> ServerBuilder

Disables statistics collection.

Use this for performance-critical scenarios where the overhead of atomic operations for stats tracking is undesirable. The overhead is minimal (typically nanoseconds per request), so this is rarely needed.

Source

pub fn request_timeout(self, secs: u64) -> ServerBuilder

Sets the request timeout in seconds.

Set to 0 to disable timeout enforcement. Default is 30 seconds.

Source

pub fn list_page_size(self, page_size: usize) -> ServerBuilder

Sets the pagination page size for list methods.

When set, list methods will return up to page_size items and provide an opaque nextCursor for retrieving the next page. When not set (default), list methods return all items in a single response.

Source

pub fn mask_error_details(self, enabled: bool) -> ServerBuilder

Enables or disables error detail masking.

When enabled, internal error details are hidden from client responses:

  • Stack traces removed
  • File paths sanitized
  • Internal state not exposed
  • Generic “Internal server error” message returned

Client errors (invalid request, method not found, etc.) are preserved since they don’t contain sensitive internal details.

Default is false (disabled) for development convenience.

§Example
let server = Server::new("api", "1.0")
    .mask_error_details(true)  // Always mask in production
    .build();
Source

pub fn auto_mask_errors(self) -> ServerBuilder

Automatically masks error details based on environment.

Masking is enabled when:

  • FASTMCP_ENV is set to “production”
  • FASTMCP_MASK_ERRORS is set to “true” or “1”
  • The build is a release build (cfg!(not(debug_assertions)))

Masking is explicitly disabled when:

  • FASTMCP_MASK_ERRORS is set to “false” or “0”
§Example
let server = Server::new("api", "1.0")
    .auto_mask_errors()
    .build();
Source

pub fn is_error_masking_enabled(&self) -> bool

Returns whether error masking is enabled.

Source

pub fn strict_input_validation(self, enabled: bool) -> ServerBuilder

Enables or disables strict input validation.

When enabled, tool input validation will reject any properties not explicitly defined in the tool’s input schema (enforces additionalProperties: false).

When disabled (default), extra properties are allowed unless the schema explicitly sets additionalProperties: false.

§Example
let server = Server::new("api", "1.0")
    .strict_input_validation(true)  // Reject unknown properties
    .build();
Source

pub fn is_strict_input_validation_enabled(&self) -> bool

Returns whether strict input validation is enabled.

Source

pub fn middleware<M>(self, middleware: M) -> ServerBuilder
where M: Middleware + 'static,

Registers a middleware.

Source

pub fn tool<H>(self, handler: H) -> ServerBuilder
where H: ToolHandler + 'static,

Registers a tool handler.

Duplicate handling is controlled by on_duplicate. If DuplicateBehavior::Error is set and a duplicate is found, an error will be logged and the tool will not be registered.

Source

pub fn resource<H>(self, handler: H) -> ServerBuilder
where H: ResourceHandler + 'static,

Registers a resource handler.

Duplicate handling is controlled by on_duplicate. If DuplicateBehavior::Error is set and a duplicate is found, an error will be logged and the resource will not be registered.

Source

pub fn resource_template(self, template: ResourceTemplate) -> ServerBuilder

Registers a resource template.

Source

pub fn prompt<H>(self, handler: H) -> ServerBuilder
where H: PromptHandler + 'static,

Registers a prompt handler.

Duplicate handling is controlled by on_duplicate. If DuplicateBehavior::Error is set and a duplicate is found, an error will be logged and the prompt will not be registered.

Source

pub fn proxy(self, client: ProxyClient, catalog: ProxyCatalog) -> ServerBuilder

Registers proxy handlers for a remote MCP server.

Use ProxyCatalog::from_client or ProxyClient::catalog to fetch definitions before calling this method.

Source

pub fn as_proxy( self, prefix: &str, client: Client, ) -> Result<ServerBuilder, McpError>

Creates a proxy to an external MCP server with automatic discovery.

This is a convenience method that combines connection, discovery, and handler registration. The client should already be initialized (connected to the server).

All tools, resources, and prompts from the external server are registered as proxy handlers with the specified prefix.

§Example
use fastmcp_client::Client;

// Create and initialize client
let mut client = Client::new(transport)?;
client.initialize()?;

// Create main server with proxy to external
let main = Server::new("main", "1.0")
    .tool(local_tool)
    .as_proxy("ext", client)?    // ext/external_tool, etc.
    .build();
§Errors

Returns an error if the catalog fetch fails.

Source

pub fn as_proxy_raw(self, client: Client) -> Result<ServerBuilder, McpError>

Creates a proxy to an external MCP server without a prefix.

Similar to as_proxy, but tools/resources/prompts keep their original names. Use this when proxying a single external server or when you don’t need namespace separation.

§Example
let main = Server::new("main", "1.0")
    .as_proxy_raw(client)?  // External tools appear with original names
    .build();
Source

pub fn mount(self, server: Server, prefix: Option<&str>) -> ServerBuilder

Mounts another server’s components into this server with an optional prefix.

This consumes the source server and moves all its tools, resources, and prompts into this server. Names/URIs are prefixed with prefix/ if a prefix is provided.

§Example
let db_server = Server::new("db", "1.0")
    .tool(query_tool)
    .tool(insert_tool)
    .build();

let api_server = Server::new("api", "1.0")
    .tool(endpoint_tool)
    .build();

let main = Server::new("main", "1.0")
    .mount(db_server, Some("db"))      // db/query, db/insert
    .mount(api_server, Some("api"))    // api/endpoint
    .build();
§Prefix Rules
  • Prefixes must be alphanumeric plus underscores and hyphens
  • Prefixes cannot contain slashes
  • With prefix "db", tool "query" becomes "db/query"
  • Without prefix, names are preserved (may cause conflicts)
Source

pub fn mount_tools(self, server: Server, prefix: Option<&str>) -> ServerBuilder

Mounts only tools from another server with an optional prefix.

Similar to mount, but only transfers tools, ignoring resources and prompts.

§Example
let utils_server = Server::new("utils", "1.0")
    .tool(format_tool)
    .tool(parse_tool)
    .resource(config_resource)  // Will NOT be mounted
    .build();

let main = Server::new("main", "1.0")
    .mount_tools(utils_server, Some("utils"))  // Only tools
    .build();
Source

pub fn mount_resources( self, server: Server, prefix: Option<&str>, ) -> ServerBuilder

Mounts only resources from another server with an optional prefix.

Similar to mount, but only transfers resources, ignoring tools and prompts.

§Example
let data_server = Server::new("data", "1.0")
    .resource(config_resource)
    .resource(schema_resource)
    .tool(query_tool)  // Will NOT be mounted
    .build();

let main = Server::new("main", "1.0")
    .mount_resources(data_server, Some("data"))  // Only resources
    .build();
Source

pub fn mount_prompts( self, server: Server, prefix: Option<&str>, ) -> ServerBuilder

Mounts only prompts from another server with an optional prefix.

Similar to mount, but only transfers prompts, ignoring tools and resources.

§Example
let templates_server = Server::new("templates", "1.0")
    .prompt(greeting_prompt)
    .prompt(error_prompt)
    .tool(format_tool)  // Will NOT be mounted
    .build();

let main = Server::new("main", "1.0")
    .mount_prompts(templates_server, Some("tmpl"))  // Only prompts
    .build();
Source

pub fn instructions(self, instructions: impl Into<String>) -> ServerBuilder

Sets custom server instructions.

Source

pub fn log_level(self, level: Level) -> ServerBuilder

Sets the log level.

Default is read from FASTMCP_LOG environment variable, or INFO if not set.

Source

pub fn log_level_filter(self, filter: LevelFilter) -> ServerBuilder

Sets the log level from a filter.

Source

pub fn log_timestamps(self, show: bool) -> ServerBuilder

Sets whether to show timestamps in logs.

Default is true.

Source

pub fn log_targets(self, show: bool) -> ServerBuilder

Sets whether to show target/module paths in logs.

Default is true.

Source

pub fn logging(self, config: LoggingConfig) -> ServerBuilder

Sets the full logging configuration.

Source

pub fn with_console_config(self, config: ConsoleConfig) -> ServerBuilder

Sets the complete console configuration.

This provides full control over all console output settings including banner, traffic logging, periodic stats, and error formatting.

§Example
use fastmcp_console::config::{ConsoleConfig, BannerStyle};

Server::new("demo", "1.0.0")
    .with_console_config(
        ConsoleConfig::new()
            .with_banner(BannerStyle::Compact)
            .plain_mode()
    )
    .build();
Source

pub fn with_banner(self, style: BannerStyle) -> ServerBuilder

Sets the banner style.

Controls how the startup banner is displayed. Default is BannerStyle::Full.

Source

pub fn without_banner(self) -> ServerBuilder

Disables the startup banner.

Source

pub fn with_traffic_logging(self, verbosity: TrafficVerbosity) -> ServerBuilder

Enables request/response traffic logging.

Controls the verbosity of traffic logging:

  • None: No traffic logging (default)
  • Summary: Method name and timing only
  • Headers: Include metadata/headers
  • Full: Full request/response bodies
Source

pub fn with_periodic_stats(self, interval_secs: u64) -> ServerBuilder

Enables periodic statistics display.

When enabled, statistics will be printed to stderr at the specified interval. Requires stats collection to be enabled (the default).

Source

pub fn plain_mode(self) -> ServerBuilder

Forces plain text output (no colors/styling).

Useful for CI environments, logging to files, or when running as an MCP server where rich output might interfere with the JSON-RPC protocol.

Source

pub fn force_color(self) -> ServerBuilder

Forces color output even in non-TTY environments.

Source

pub fn console_config(&self) -> &ConsoleConfig

Returns a reference to the current console configuration.

Source

pub fn on_startup<F, E>(self, hook: F) -> ServerBuilder
where F: FnOnce() -> Result<(), E> + Send + 'static, E: Error + Send + Sync + 'static,

Registers a startup hook that runs before the server starts accepting connections.

The hook can perform initialization tasks like:

  • Opening database connections
  • Loading configuration files
  • Initializing caches

If the hook returns an error, the server will not start.

§Example
Server::new("demo", "1.0.0")
    .on_startup(|| {
        println!("Server starting up...");
        Ok(())
    })
    .run_stdio();
Source

pub fn on_shutdown<F>(self, hook: F) -> ServerBuilder
where F: FnOnce() + Send + 'static,

Registers a shutdown hook that runs when the server is shutting down.

The hook can perform cleanup tasks like:

  • Closing database connections
  • Flushing caches
  • Saving state

Shutdown hooks are run on a best-effort basis. If the process is forcefully terminated, hooks may not run.

§Example
Server::new("demo", "1.0.0")
    .on_shutdown(|| {
        println!("Server shutting down...");
    })
    .run_stdio();
Source

pub fn with_task_manager(self, task_manager: Arc<TaskManager>) -> ServerBuilder

Sets a task manager for background tasks (Docket/SEP-1686).

When a task manager is configured, the server will advertise task capabilities and handle task-related methods.

§Example
use fastmcp_server::TaskManager;

let task_manager = TaskManager::new();
Server::new("demo", "1.0.0")
    .with_task_manager(task_manager.into_shared())
    .run_stdio();
Source

pub fn build(self) -> Server

Builds the server.

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.

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