mcp_core_fishcode2025/
handler.rs

1use async_trait::async_trait;
2use schemars::JsonSchema;
3use serde::{Deserialize, Serialize};
4use serde_json::Value;
5use thiserror::Error;
6
7#[non_exhaustive]
8#[derive(Error, Debug, Clone, Deserialize, Serialize, PartialEq)]
9pub enum ToolError {
10    #[error("Invalid parameters: {0}")]
11    InvalidParameters(String),
12    #[error("Execution failed: {0}")]
13    ExecutionError(String),
14    #[error("Schema error: {0}")]
15    SchemaError(String),
16    #[error("Tool not found: {0}")]
17    NotFound(String),
18}
19
20pub type ToolResult<T> = std::result::Result<T, ToolError>;
21
22#[derive(Error, Debug)]
23pub enum ResourceError {
24    #[error("Execution failed: {0}")]
25    ExecutionError(String),
26    #[error("Resource not found: {0}")]
27    NotFound(String),
28}
29
30#[derive(Error, Debug)]
31pub enum PromptError {
32    #[error("Invalid parameters: {0}")]
33    InvalidParameters(String),
34    #[error("Internal error: {0}")]
35    InternalError(String),
36    #[error("Prompt not found: {0}")]
37    NotFound(String),
38}
39
40/// Trait for implementing MCP tools
41#[async_trait]
42pub trait ToolHandler: Send + Sync + 'static {
43    /// The name of the tool
44    fn name(&self) -> &'static str;
45
46    /// A description of what the tool does
47    fn description(&self) -> &'static str;
48
49    /// JSON schema describing the tool's parameters
50    fn schema(&self) -> Value;
51
52    /// Execute the tool with the given parameters
53    async fn call(&self, params: Value) -> ToolResult<Value>;
54}
55
56/// Trait for implementing MCP resources
57#[async_trait]
58pub trait ResourceTemplateHandler: Send + Sync + 'static {
59    /// The URL template for this resource
60    fn template() -> &'static str;
61
62    /// JSON schema describing the resource parameters
63    fn schema() -> Value;
64
65    /// Get the resource value
66    async fn get(&self, params: Value) -> ToolResult<String>;
67}
68
69/// Helper function to generate JSON schema for a type
70pub fn generate_schema<T: JsonSchema>() -> ToolResult<Value> {
71    let schema = schemars::schema_for!(T);
72    serde_json::to_value(schema).map_err(|e| ToolError::SchemaError(e.to_string()))
73}