pub struct Server { /* private fields */ }Expand description
Main MCP server
Implementations§
Source§impl Server
impl Server
Sourcepub fn capabilities(&self) -> Arc<ServerCapabilities>
pub fn capabilities(&self) -> Arc<ServerCapabilities>
Get current capabilities
Sourcepub fn set_capabilities(&self, capabilities: ServerCapabilities)
pub fn set_capabilities(&self, capabilities: ServerCapabilities)
Update server capabilities
Sourcepub fn instructions(&self) -> Option<String>
pub fn instructions(&self) -> Option<String>
Get current instructions
Sourcepub fn set_instructions(&self, instructions: Option<String>)
pub fn set_instructions(&self, instructions: Option<String>)
Set server instructions for LLMs
Sourcepub fn set_environment(&mut self, environment: Arc<dyn Environment>)
pub fn set_environment(&mut self, environment: Arc<dyn Environment>)
Set environment for visibility checks
Sourcepub fn add_middleware(&mut self, middleware: MiddlewareFn)
pub fn add_middleware(&mut self, middleware: MiddlewareFn)
Add middleware to the chain
Sourcepub fn tool_registry(&self) -> &ToolRegistry
pub fn tool_registry(&self) -> &ToolRegistry
Get tool registry
Sourcepub fn resource_manager(&self) -> &ResourceManager
pub fn resource_manager(&self) -> &ResourceManager
Get resource manager
Sourcepub fn prompt_manager(&self) -> &PromptManager
pub fn prompt_manager(&self) -> &PromptManager
Get prompt manager
Sourcepub fn subscription_manager(&self) -> &SubscriptionManager
pub fn subscription_manager(&self) -> &SubscriptionManager
Get subscription manager for resource subscriptions
Sourcepub fn completion_manager(&self) -> &CompletionManager
pub fn completion_manager(&self) -> &CompletionManager
Get completion manager for argument value suggestions
Sourcepub fn notification_sender(&self) -> UnboundedSender<JsonRpcNotification>
pub fn notification_sender(&self) -> UnboundedSender<JsonRpcNotification>
Get notification sender (for background tasks)
Sourcepub fn send_notification(
&self,
method: impl Into<String>,
params: Option<Value>,
) -> Result<(), Box<dyn Error>>
pub fn send_notification( &self, method: impl Into<String>, params: Option<Value>, ) -> Result<(), Box<dyn Error>>
Send a notification to the client
Sourcepub fn get_session(&self, session_id: &str) -> Option<Session>
pub fn get_session(&self, session_id: &str) -> Option<Session>
Get session by ID
Sourcepub fn remove_session(&self, session_id: &str) -> Option<Session>
pub fn remove_session(&self, session_id: &str) -> Option<Session>
Remove session
Also cleans up any resource subscriptions for the session.
Sourcepub fn notify_resource_updated(&self, uri: &str)
pub fn notify_resource_updated(&self, uri: &str)
Sourcepub fn notify_resources_updated(&self, uris: &[&str])
pub fn notify_resources_updated(&self, uris: &[&str])
Notify subscribers for multiple resources (batch operation)
Convenience method for notifying about multiple resource updates at once.
Sourcepub fn multiplexer(&self) -> Arc<RequestMultiplexer>
pub fn multiplexer(&self) -> Arc<RequestMultiplexer>
Get the request multiplexer (for advanced use cases)
Sourcepub fn cancellation_manager(&self) -> &CancellationManager
pub fn cancellation_manager(&self) -> &CancellationManager
Get the cancellation manager
Use this to register cancellable operations and check cancellation status.
Sourcepub fn create_client_requester(
&self,
session_id: &str,
) -> Option<ClientRequester>
pub fn create_client_requester( &self, session_id: &str, ) -> Option<ClientRequester>
Create a client requester for the given session
The client requester allows tools to make server→client requests like roots/list, sampling/createMessage, and elicitation/create.
Sourcepub async fn request_roots(
&self,
session_id: &str,
timeout: Option<Duration>,
) -> Result<Vec<Root>, MultiplexerError>
pub async fn request_roots( &self, session_id: &str, timeout: Option<Duration>, ) -> Result<Vec<Root>, MultiplexerError>
Request workspace roots from the client
Sends a roots/list request to the client and waits for the response.
The client must have the roots capability advertised.
§Arguments
session_id- The session to check for roots capabilitytimeout- Optional timeout (defaults to 30 seconds)
§Returns
List of workspace roots, or an error if:
- Client doesn’t support roots capability
- Request times out
- Client returns an error
§Example
let roots = server.request_roots("session-123", None).await?;
for root in roots {
println!("Root: {} ({})", root.name.unwrap_or_default(), root.uri);
}Sourcepub async fn request_sampling(
&self,
session_id: &str,
params: CreateMessageParams,
timeout: Option<Duration>,
) -> Result<CreateMessageResult, MultiplexerError>
pub async fn request_sampling( &self, session_id: &str, params: CreateMessageParams, timeout: Option<Duration>, ) -> Result<CreateMessageResult, MultiplexerError>
Request an LLM completion from the client
Sends a sampling/createMessage request to the client.
The client must have the sampling capability advertised.
§Arguments
session_id- The session to check for sampling capabilityparams- The sampling parameterstimeout- Optional timeout (defaults to 30 seconds)
§Returns
The completion result, or an error if:
- Client doesn’t support sampling capability
- Request times out
- Client returns an error
§Example
use mcp_host::server::multiplexer::{CreateMessageParams, SamplingContent, SamplingMessage};
let params = CreateMessageParams {
messages: vec![SamplingMessage {
role: "user".to_string(),
content: SamplingContent::Text { text: "Hello!".to_string() },
}],
max_tokens: 1000,
..Default::default()
};
let result = server.request_sampling("session-123", params, None).await?;
println!("Response: {:?}", result.content);Sourcepub async fn request_elicitation(
&self,
session_id: &str,
message: impl Into<String>,
requested_schema: Value,
timeout: Option<Duration>,
) -> Result<CreateElicitationResult, MultiplexerError>
pub async fn request_elicitation( &self, session_id: &str, message: impl Into<String>, requested_schema: Value, timeout: Option<Duration>, ) -> Result<CreateElicitationResult, MultiplexerError>
Request structured user input from the client
Sends an elicitation/create request to the client.
The client must have the elicitation capability advertised.
§Arguments
session_id- The session to check for elicitation capabilitymessage- The message to show the userrequested_schema- JSON Schema for the structured inputtimeout- Optional timeout (defaults to 30 seconds)
§Returns
The elicitation result (action + optional content), or an error if:
- Client doesn’t support elicitation capability
- Request times out
- Client returns an error
§Example
use mcp_host::protocol::elicitation::ElicitationSchema;
use mcp_host::protocol::types::ElicitationAction;
let schema = ElicitationSchema::builder()
.required_email("email")
.required_integer("age", 0, 150)
.optional_bool("newsletter", false)
.build_unchecked();
let result = server.request_elicitation(
"session-123",
"Please provide your information",
serde_json::to_value(&schema).unwrap(),
None,
).await?;
match result.action {
ElicitationAction::Accept => {
if let Some(content) = result.content {
let email = content["email"].as_str().unwrap();
let age = content["age"].as_i64().unwrap();
println!("User: {} (age {})", email, age);
}
}
ElicitationAction::Decline => println!("User declined"),
ElicitationAction::Cancel => println!("User cancelled"),
}Sourcepub async fn run<T: Transport>(
&self,
transport: T,
) -> Result<(), Box<dyn Error>>
pub async fn run<T: Transport>( &self, transport: T, ) -> Result<(), Box<dyn Error>>
Run server with the given transport
This is the main event loop that reads requests from the transport, processes them, and writes responses back.
Supports bidirectional communication:
- Incoming client requests are handled and responses sent
- Server-initiated requests are sent via channels and responses routed back
Sourcepub async fn handle_request(
&self,
session_id: &str,
request: JsonRpcRequest,
) -> JsonRpcResponse
pub async fn handle_request( &self, session_id: &str, request: JsonRpcRequest, ) -> JsonRpcResponse
Handle incoming JSON-RPC request