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>) -> Self
pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self
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) -> Self
pub fn on_duplicate(self, behavior: DuplicateBehavior) -> Self
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: AuthProvider + 'static>(self, provider: P) -> Self
pub fn auth_provider<P: AuthProvider + 'static>(self, provider: P) -> Self
Sets an authentication provider.
Sourcepub fn without_stats(self) -> Self
pub fn without_stats(self) -> Self
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) -> Self
pub fn request_timeout(self, secs: u64) -> Self
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) -> Self
pub fn list_page_size(self, page_size: usize) -> Self
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) -> Self
pub fn mask_error_details(self, enabled: bool) -> Self
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) -> Self
pub fn auto_mask_errors(self) -> Self
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) -> Self
pub fn strict_input_validation(self, enabled: bool) -> Self
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: Middleware + 'static>(self, middleware: M) -> Self
pub fn middleware<M: Middleware + 'static>(self, middleware: M) -> Self
Registers a middleware.
Sourcepub fn tool<H: ToolHandler + 'static>(self, handler: H) -> Self
pub fn tool<H: ToolHandler + 'static>(self, handler: H) -> Self
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: ResourceHandler + 'static>(self, handler: H) -> Self
pub fn resource<H: ResourceHandler + 'static>(self, handler: H) -> Self
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) -> Self
pub fn resource_template(self, template: ResourceTemplate) -> Self
Registers a resource template.
Sourcepub fn prompt<H: PromptHandler + 'static>(self, handler: H) -> Self
pub fn prompt<H: PromptHandler + 'static>(self, handler: H) -> Self
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) -> Self
pub fn proxy(self, client: ProxyClient, catalog: ProxyCatalog) -> Self
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<Self, McpError>
pub fn as_proxy(self, prefix: &str, client: Client) -> Result<Self, 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<Self, McpError>
pub fn as_proxy_raw(self, client: Client) -> Result<Self, 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>) -> Self
pub fn mount(self, server: Server, prefix: Option<&str>) -> Self
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>) -> Self
pub fn mount_tools(self, server: Server, prefix: Option<&str>) -> Self
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>) -> Self
pub fn mount_resources(self, server: Server, prefix: Option<&str>) -> Self
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>) -> Self
pub fn mount_prompts(self, server: Server, prefix: Option<&str>) -> Self
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>) -> Self
pub fn instructions(self, instructions: impl Into<String>) -> Self
Sets custom server instructions.
Sourcepub fn log_level(self, level: Level) -> Self
pub fn log_level(self, level: Level) -> Self
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) -> Self
pub fn log_level_filter(self, filter: LevelFilter) -> Self
Sets the log level from a filter.
Sourcepub fn log_timestamps(self, show: bool) -> Self
pub fn log_timestamps(self, show: bool) -> Self
Sets whether to show timestamps in logs.
Default is true.
Sourcepub fn log_targets(self, show: bool) -> Self
pub fn log_targets(self, show: bool) -> Self
Sets whether to show target/module paths in logs.
Default is true.
Sourcepub fn logging(self, config: LoggingConfig) -> Self
pub fn logging(self, config: LoggingConfig) -> Self
Sets the full logging configuration.
Sourcepub fn with_console_config(self, config: ConsoleConfig) -> Self
pub fn with_console_config(self, config: ConsoleConfig) -> Self
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) -> Self
pub fn with_traffic_logging(self, verbosity: TrafficVerbosity) -> Self
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) -> Self
pub fn with_periodic_stats(self, interval_secs: u64) -> Self
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) -> Self
pub fn plain_mode(self) -> Self
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) -> Self
pub fn force_color(self) -> Self
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) -> Self
pub fn on_startup<F, E>(self, hook: F) -> Self
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) -> Self
pub fn on_shutdown<F>(self, hook: F) -> Self
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: SharedTaskManager) -> Self
pub fn with_task_manager(self, task_manager: SharedTaskManager) -> Self
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();