rust_mcp_sdk/mcp_handlers/mcp_server_handler.rs
1use async_trait::async_trait;
2use rust_mcp_schema::{schema_utils::CallToolError, *};
3use serde_json::Value;
4
5use crate::mcp_traits::mcp_server::McpServer;
6
7/// Defines the `ServerHandler` trait for handling Model Context Protocol (MCP) operations on a server.
8/// This trait provides default implementations for request and notification handlers in an MCP server,
9/// allowing developers to override methods for custom behavior.
10#[allow(unused)]
11#[async_trait]
12pub trait ServerHandler: Send + Sync + 'static {
13 /// Invoked when the server finishes initialization and receives an `initialized_notification` from the client.
14 ///
15 /// The `runtime` parameter provides access to the server's runtime environment, allowing
16 /// interaction with the server's capabilities.
17 /// The default implementation does nothing.
18 async fn on_initialized(&self, runtime: &dyn McpServer) {}
19
20 /// Handles the InitializeRequest from a client.
21 ///
22 /// # Arguments
23 /// * `initialize_request` - The initialization request containing client parameters
24 /// * `runtime` - Reference to the MCP server runtime
25 ///
26 /// # Returns
27 /// Returns the server info as InitializeResult on success or a JSON-RPC error on failure
28 /// Do not override this unless the standard initialization process doesn't work for you or you need to modify it.
29 async fn handle_initialize_request(
30 &self,
31 initialize_request: InitializeRequest,
32 runtime: &dyn McpServer,
33 ) -> std::result::Result<InitializeResult, RpcError> {
34 runtime
35 .set_client_details(initialize_request.params.clone())
36 .map_err(|err| RpcError::internal_error().with_message(format!("{}", err)))?;
37
38 Ok(runtime.server_info().to_owned())
39 }
40
41 /// Handles ping requests from clients.
42 ///
43 /// # Returns
44 /// By default, it returns an empty result structure
45 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
46 async fn handle_ping_request(
47 &self,
48 _: PingRequest,
49 _: &dyn McpServer,
50 ) -> std::result::Result<Result, RpcError> {
51 Ok(Result::default())
52 }
53
54 /// Handles requests to list available resources.
55 ///
56 /// Default implementation returns method not found error.
57 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
58 async fn handle_list_resources_request(
59 &self,
60 request: ListResourcesRequest,
61 runtime: &dyn McpServer,
62 ) -> std::result::Result<ListResourcesResult, RpcError> {
63 runtime.assert_server_request_capabilities(request.method())?;
64 Err(RpcError::method_not_found().with_message(format!(
65 "No handler is implemented for '{}'.",
66 request.method(),
67 )))
68 }
69
70 /// Handles requests to list resource templates.
71 ///
72 /// Default implementation returns method not found error.
73 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
74 async fn handle_list_resource_templates_request(
75 &self,
76 request: ListResourceTemplatesRequest,
77 runtime: &dyn McpServer,
78 ) -> std::result::Result<ListResourceTemplatesResult, RpcError> {
79 runtime.assert_server_request_capabilities(request.method())?;
80 Err(RpcError::method_not_found().with_message(format!(
81 "No handler is implemented for '{}'.",
82 request.method(),
83 )))
84 }
85
86 /// Handles requests to read a specific resource.
87 ///
88 /// Default implementation returns method not found error.
89 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
90 async fn handle_read_resource_request(
91 &self,
92 request: ReadResourceRequest,
93 runtime: &dyn McpServer,
94 ) -> std::result::Result<ReadResourceResult, RpcError> {
95 runtime.assert_server_request_capabilities(request.method())?;
96 Err(RpcError::method_not_found().with_message(format!(
97 "No handler is implemented for '{}'.",
98 request.method(),
99 )))
100 }
101
102 /// Handles subscription requests from clients.
103 ///
104 /// Default implementation returns method not found error.
105 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
106 async fn handle_subscribe_request(
107 &self,
108 request: SubscribeRequest,
109 runtime: &dyn McpServer,
110 ) -> std::result::Result<Result, RpcError> {
111 runtime.assert_server_request_capabilities(request.method())?;
112 Err(RpcError::method_not_found().with_message(format!(
113 "No handler is implemented for '{}'.",
114 request.method(),
115 )))
116 }
117
118 /// Handles unsubscribe requests from clients.
119 ///
120 /// Default implementation returns method not found error.
121 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
122 async fn handle_unsubscribe_request(
123 &self,
124 request: UnsubscribeRequest,
125 runtime: &dyn McpServer,
126 ) -> std::result::Result<Result, RpcError> {
127 runtime.assert_server_request_capabilities(request.method())?;
128 Err(RpcError::method_not_found().with_message(format!(
129 "No handler is implemented for '{}'.",
130 request.method(),
131 )))
132 }
133
134 /// Handles requests to list available prompts.
135 ///
136 /// Default implementation returns method not found error.
137 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
138 async fn handle_list_prompts_request(
139 &self,
140 request: ListPromptsRequest,
141 runtime: &dyn McpServer,
142 ) -> std::result::Result<ListPromptsResult, RpcError> {
143 runtime.assert_server_request_capabilities(request.method())?;
144 Err(RpcError::method_not_found().with_message(format!(
145 "No handler is implemented for '{}'.",
146 request.method(),
147 )))
148 }
149
150 /// Handles requests to get a specific prompt.
151 ///
152 /// Default implementation returns method not found error.
153 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
154 async fn handle_get_prompt_request(
155 &self,
156 request: GetPromptRequest,
157 runtime: &dyn McpServer,
158 ) -> std::result::Result<GetPromptResult, RpcError> {
159 runtime.assert_server_request_capabilities(request.method())?;
160 Err(RpcError::method_not_found().with_message(format!(
161 "No handler is implemented for '{}'.",
162 request.method(),
163 )))
164 }
165
166 /// Handles requests to list available tools.
167 ///
168 /// Default implementation returns method not found error.
169 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
170 async fn handle_list_tools_request(
171 &self,
172 request: ListToolsRequest,
173 runtime: &dyn McpServer,
174 ) -> std::result::Result<ListToolsResult, RpcError> {
175 runtime.assert_server_request_capabilities(request.method())?;
176 Err(RpcError::method_not_found().with_message(format!(
177 "No handler is implemented for '{}'.",
178 request.method(),
179 )))
180 }
181
182 /// Handles requests to call a specific tool.
183 ///
184 /// Default implementation returns an unknown tool error.
185 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
186 async fn handle_call_tool_request(
187 &self,
188 request: CallToolRequest,
189 runtime: &dyn McpServer,
190 ) -> std::result::Result<CallToolResult, CallToolError> {
191 runtime
192 .assert_server_request_capabilities(request.method())
193 .map_err(CallToolError::new)?;
194 Ok(CallToolError::unknown_tool(format!("Unknown tool: {}", request.params.name)).into())
195 }
196
197 /// Handles requests to enable or adjust logging level.
198 ///
199 /// Default implementation returns method not found error.
200 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
201 async fn handle_set_level_request(
202 &self,
203 request: SetLevelRequest,
204 runtime: &dyn McpServer,
205 ) -> std::result::Result<Result, RpcError> {
206 runtime.assert_server_request_capabilities(request.method())?;
207 Err(RpcError::method_not_found().with_message(format!(
208 "No handler is implemented for '{}'.",
209 request.method(),
210 )))
211 }
212
213 /// Handles completion requests from clients.
214 ///
215 /// Default implementation returns method not found error.
216 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
217 async fn handle_complete_request(
218 &self,
219 request: CompleteRequest,
220 runtime: &dyn McpServer,
221 ) -> std::result::Result<CompleteResult, RpcError> {
222 runtime.assert_server_request_capabilities(request.method())?;
223 Err(RpcError::method_not_found().with_message(format!(
224 "No handler is implemented for '{}'.",
225 request.method(),
226 )))
227 }
228
229 /// Handles custom requests not defined in the standard protocol.
230 ///
231 /// Default implementation returns method not found error.
232 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
233 async fn handle_custom_request(
234 &self,
235 request: Value,
236 runtime: &dyn McpServer,
237 ) -> std::result::Result<Value, RpcError> {
238 Err(RpcError::method_not_found()
239 .with_message("No handler is implemented for custom requests.".to_string()))
240 }
241
242 // Notification Handlers
243
244 /// Handles initialized notifications from clients.
245 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
246 async fn handle_initialized_notification(
247 &self,
248 notification: InitializedNotification,
249 runtime: &dyn McpServer,
250 ) -> std::result::Result<(), RpcError> {
251 Ok(())
252 }
253
254 /// Handles cancelled operation notifications.
255 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
256 async fn handle_cancelled_notification(
257 &self,
258 notification: CancelledNotification,
259 runtime: &dyn McpServer,
260 ) -> std::result::Result<(), RpcError> {
261 Ok(())
262 }
263
264 /// Handles progress update notifications.
265 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
266 async fn handle_progress_notification(
267 &self,
268 notification: ProgressNotification,
269 runtime: &dyn McpServer,
270 ) -> std::result::Result<(), RpcError> {
271 Ok(())
272 }
273
274 /// Handles notifications received from the client indicating that the list of roots has changed
275 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
276 async fn handle_roots_list_changed_notification(
277 &self,
278 notification: RootsListChangedNotification,
279 runtime: &dyn McpServer,
280 ) -> std::result::Result<(), RpcError> {
281 Ok(())
282 }
283
284 /// Handles custom notifications not defined in the standard protocol.
285 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
286 async fn handle_custom_notification(
287 &self,
288 notification: Value,
289 ) -> std::result::Result<(), RpcError> {
290 Ok(())
291 }
292
293 // Error Handler
294
295 /// Handles server errors that occur during operation.
296 ///
297 /// # Arguments
298 /// * `error` - The error that occurred
299 /// * `runtime` - Reference to the MCP server runtime
300 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
301 async fn handle_error(
302 &self,
303 error: RpcError,
304 runtime: &dyn McpServer,
305 ) -> std::result::Result<(), RpcError> {
306 Ok(())
307 }
308
309 /// Called when the server has successfully started.
310 ///
311 /// Sends a "Server started successfully" message to stderr.
312 /// Customize this function in your specific handler to implement behavior tailored to your MCP server's capabilities and requirements.
313 async fn on_server_started(&self, runtime: &dyn McpServer) {
314 let _ = runtime
315 .stderr_message("Server started successfully".into())
316 .await;
317 }
318}