json_mcp_server/mcp/
protocol.rs

1use serde::{Deserialize, Serialize};
2use serde_json::Value;
3use std::collections::HashMap;
4
5#[derive(Debug, Clone, Serialize, Deserialize)]
6pub struct MCPRequest {
7    pub jsonrpc: String,
8    pub id: Option<Value>,
9    pub method: String,
10    pub params: Option<Value>,
11}
12
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct MCPResponse {
15    pub jsonrpc: String,
16    pub id: Option<Value>,
17    #[serde(skip_serializing_if = "Option::is_none")]
18    pub result: Option<Value>,
19    #[serde(skip_serializing_if = "Option::is_none")]
20    pub error: Option<MCPError>,
21}
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
24pub struct MCPError {
25    pub code: i32,
26    pub message: String,
27    #[serde(skip_serializing_if = "Option::is_none")]
28    pub data: Option<Value>,
29}
30
31#[derive(Debug, Clone, Serialize, Deserialize)]
32pub struct Tool {
33    pub name: String,
34    pub description: String,
35    pub input_schema: Value,
36}
37
38#[derive(Debug, Clone, Serialize, Deserialize)]
39pub struct ToolCall {
40    pub name: String,
41    pub arguments: HashMap<String, Value>,
42}
43
44#[derive(Debug, Clone, Serialize, Deserialize)]
45pub struct ToolResult {
46    pub content: Vec<ToolContent>,
47    #[serde(skip_serializing_if = "Option::is_none")]
48    pub is_error: Option<bool>,
49}
50
51#[derive(Debug, Clone, Serialize, Deserialize)]
52pub struct ToolContent {
53    #[serde(rename = "type")]
54    pub content_type: String,
55    pub text: String,
56}
57
58impl MCPResponse {
59    pub fn success(id: Option<Value>, result: Value) -> Self {
60        Self {
61            jsonrpc: "2.0".to_string(),
62            id,
63            result: Some(result),
64            error: None,
65        }
66    }
67
68    pub fn error(id: Option<Value>, code: i32, message: &str) -> Self {
69        Self {
70            jsonrpc: "2.0".to_string(),
71            id,
72            result: None,
73            error: Some(MCPError {
74                code,
75                message: message.to_string(),
76                data: None,
77            }),
78        }
79    }
80}
81
82impl ToolResult {
83    pub fn success(text: String) -> Self {
84        Self {
85            content: vec![ToolContent {
86                content_type: "text".to_string(),
87                text,
88            }],
89            is_error: None,
90        }
91    }
92
93    pub fn error(text: String) -> Self {
94        Self {
95            content: vec![ToolContent {
96                content_type: "text".to_string(),
97                text,
98            }],
99            is_error: Some(true),
100        }
101    }
102}