84 lines
2.3 KiB
Rust
84 lines
2.3 KiB
Rust
use log::debug;
|
|
use serde_json::Value;
|
|
|
|
use super::tools::{KeepTools, ToolError};
|
|
use crate::modes::server::common::AppState;
|
|
|
|
/// Server handler for MCP (Model Context Protocol) requests.
|
|
///
|
|
/// Routes requests to appropriate tools and handles responses. Clones AppState for tool usage.
|
|
///
|
|
/// # Fields
|
|
///
|
|
/// * `state` - The shared application state (DB, config, etc.).
|
|
#[derive(Clone)]
|
|
pub struct KeepMcpServer {
|
|
state: AppState,
|
|
}
|
|
|
|
/// Creates a new `KeepMcpServer` instance.
|
|
///
|
|
/// # Arguments
|
|
///
|
|
/// * `state` - The application state containing DB, config, and services.
|
|
///
|
|
/// # Returns
|
|
///
|
|
/// A new `KeepMcpServer` instance.
|
|
///
|
|
/// # Examples
|
|
///
|
|
/// ```
|
|
/// let server = KeepMcpServer::new(app_state);
|
|
/// ```
|
|
impl KeepMcpServer {
|
|
pub fn new(state: AppState) -> Self {
|
|
Self { state }
|
|
}
|
|
|
|
/// Handles an MCP request by routing to the appropriate tool.
|
|
///
|
|
/// Supports methods like "save_item", "get_item", "list_items". Logs the request and delegates to KeepTools.
|
|
///
|
|
/// # Arguments
|
|
///
|
|
/// * `method` - The MCP method name (string).
|
|
/// * `params` - Optional JSON parameters as serde_json::Value.
|
|
///
|
|
/// # Returns
|
|
///
|
|
/// `Ok(String)` with JSON-serialized response on success, or `Err(ToolError)` on failure.
|
|
///
|
|
/// # Errors
|
|
///
|
|
/// * ToolError::UnknownTool if method unsupported.
|
|
/// * Propagates tool-specific errors (e.g., invalid args, DB failures).
|
|
///
|
|
/// # Examples
|
|
///
|
|
/// ```
|
|
/// let result = server.handle_request("save_item", Some(params)).await?;
|
|
/// ```
|
|
pub async fn handle_request(
|
|
&self,
|
|
method: &str,
|
|
params: Option<Value>,
|
|
) -> Result<String, ToolError> {
|
|
debug!(
|
|
"MCP: Handling request '{}' with params: {:?}",
|
|
method, params
|
|
);
|
|
|
|
let tools = KeepTools::new(self.state.clone());
|
|
|
|
match method {
|
|
"save_item" => tools.save_item(params).await,
|
|
"get_item" => tools.get_item(params).await,
|
|
"get_latest_item" => tools.get_latest_item(params).await,
|
|
"list_items" => tools.list_items(params).await,
|
|
"search_items" => tools.search_items(params).await,
|
|
_ => Err(ToolError::UnknownTool(method.to_string())),
|
|
}
|
|
}
|
|
}
|