pub struct ServerBuilder { /* private fields */ }Expand description
Builder for configuring an MCP server.
Implementations§
Source§impl ServerBuilder
impl ServerBuilder
Sourcepub fn new(name: impl Into<String>, version: impl Into<String>) -> ServerBuilder
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.
Sourcepub fn on_duplicate(self, behavior: DuplicateBehavior) -> ServerBuilder
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:
DuplicateBehavior::Error: Fail with an errorDuplicateBehavior::Warn: Log warning, keep original (default)DuplicateBehavior::Replace: Replace with new componentDuplicateBehavior::Ignore: Silently keep original
§Example
Server::new("demo", "1.0")
.on_duplicate(DuplicateBehavior::Error) // Strict mode
.tool(handler1)
.tool(handler2) // Fails if name conflicts
.build();Sourcepub fn auth_provider<P>(self, provider: P) -> ServerBuilderwhere
P: AuthProvider + 'static,
pub fn auth_provider<P>(self, provider: P) -> ServerBuilderwhere
P: AuthProvider + 'static,
Sets an authentication provider.
Sourcepub fn without_stats(self) -> ServerBuilder
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.
Sourcepub fn request_timeout(self, secs: u64) -> ServerBuilder
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.
Sourcepub fn list_page_size(self, page_size: usize) -> ServerBuilder
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.
Sourcepub fn mask_error_details(self, enabled: bool) -> ServerBuilder
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();Sourcepub fn auto_mask_errors(self) -> ServerBuilder
pub fn auto_mask_errors(self) -> ServerBuilder
Automatically masks error details based on environment.
Masking is enabled when:
FASTMCP_ENVis set to “production”FASTMCP_MASK_ERRORSis set to “true” or “1”- The build is a release build (
cfg!(not(debug_assertions)))
Masking is explicitly disabled when:
FASTMCP_MASK_ERRORSis set to “false” or “0”
§Example
let server = Server::new("api", "1.0")
.auto_mask_errors()
.build();Sourcepub fn is_error_masking_enabled(&self) -> bool
pub fn is_error_masking_enabled(&self) -> bool
Returns whether error masking is enabled.
Sourcepub fn strict_input_validation(self, enabled: bool) -> ServerBuilder
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();Sourcepub fn is_strict_input_validation_enabled(&self) -> bool
pub fn is_strict_input_validation_enabled(&self) -> bool
Returns whether strict input validation is enabled.
Sourcepub fn middleware<M>(self, middleware: M) -> ServerBuilderwhere
M: Middleware + 'static,
pub fn middleware<M>(self, middleware: M) -> ServerBuilderwhere
M: Middleware + 'static,
Registers a middleware.
Sourcepub fn tool<H>(self, handler: H) -> ServerBuilderwhere
H: ToolHandler + 'static,
pub fn tool<H>(self, handler: H) -> ServerBuilderwhere
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.
Sourcepub fn resource<H>(self, handler: H) -> ServerBuilderwhere
H: ResourceHandler + 'static,
pub fn resource<H>(self, handler: H) -> ServerBuilderwhere
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.
Sourcepub fn resource_template(self, template: ResourceTemplate) -> ServerBuilder
pub fn resource_template(self, template: ResourceTemplate) -> ServerBuilder
Registers a resource template.
Sourcepub fn prompt<H>(self, handler: H) -> ServerBuilderwhere
H: PromptHandler + 'static,
pub fn prompt<H>(self, handler: H) -> ServerBuilderwhere
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.
Sourcepub fn proxy(self, client: ProxyClient, catalog: ProxyCatalog) -> ServerBuilder
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.
Sourcepub fn as_proxy(
self,
prefix: &str,
client: Client,
) -> Result<ServerBuilder, McpError>
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.
Sourcepub fn as_proxy_raw(self, client: Client) -> Result<ServerBuilder, McpError>
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();Sourcepub fn mount(self, server: Server, prefix: Option<&str>) -> ServerBuilder
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)
Sourcepub fn mount_tools(self, server: Server, prefix: Option<&str>) -> ServerBuilder
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();Sourcepub fn mount_resources(
self,
server: Server,
prefix: Option<&str>,
) -> ServerBuilder
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();Sourcepub fn mount_prompts(
self,
server: Server,
prefix: Option<&str>,
) -> ServerBuilder
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();Sourcepub fn instructions(self, instructions: impl Into<String>) -> ServerBuilder
pub fn instructions(self, instructions: impl Into<String>) -> ServerBuilder
Sets custom server instructions.
Sourcepub fn log_level(self, level: Level) -> ServerBuilder
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.
Sourcepub fn log_level_filter(self, filter: LevelFilter) -> ServerBuilder
pub fn log_level_filter(self, filter: LevelFilter) -> ServerBuilder
Sets the log level from a filter.
Sourcepub fn log_timestamps(self, show: bool) -> ServerBuilder
pub fn log_timestamps(self, show: bool) -> ServerBuilder
Sets whether to show timestamps in logs.
Default is true.
Sourcepub fn log_targets(self, show: bool) -> ServerBuilder
pub fn log_targets(self, show: bool) -> ServerBuilder
Sets whether to show target/module paths in logs.
Default is true.
Sourcepub fn logging(self, config: LoggingConfig) -> ServerBuilder
pub fn logging(self, config: LoggingConfig) -> ServerBuilder
Sets the full logging configuration.
Sourcepub fn with_console_config(self, config: ConsoleConfig) -> ServerBuilder
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();Sets the banner style.
Controls how the startup banner is displayed.
Default is BannerStyle::Full.
Disables the startup banner.
Sourcepub fn with_traffic_logging(self, verbosity: TrafficVerbosity) -> ServerBuilder
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 onlyHeaders: Include metadata/headersFull: Full request/response bodies
Sourcepub fn with_periodic_stats(self, interval_secs: u64) -> ServerBuilder
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).
Sourcepub fn plain_mode(self) -> ServerBuilder
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.
Sourcepub fn force_color(self) -> ServerBuilder
pub fn force_color(self) -> ServerBuilder
Forces color output even in non-TTY environments.
Sourcepub fn console_config(&self) -> &ConsoleConfig
pub fn console_config(&self) -> &ConsoleConfig
Returns a reference to the current console configuration.
Sourcepub fn on_startup<F, E>(self, hook: F) -> ServerBuilder
pub fn on_startup<F, E>(self, hook: F) -> ServerBuilder
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();Sourcepub fn on_shutdown<F>(self, hook: F) -> ServerBuilder
pub fn on_shutdown<F>(self, hook: F) -> ServerBuilder
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();Sourcepub fn with_task_manager(self, task_manager: Arc<TaskManager>) -> ServerBuilder
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();