forked from EmilLindfors/mcp
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmod.rs
More file actions
299 lines (263 loc) · 8.45 KB
/
mod.rs
File metadata and controls
299 lines (263 loc) · 8.45 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::{collections::HashMap, sync::Arc};
use test_tool::{PingTool, TestTool};
use tokio::sync::{mpsc, RwLock};
use typed_builder::TypedBuilder;
pub mod calculator;
pub mod file_system;
pub mod test_tool;
use crate::error::McpError;
use crate::protocol::JsonRpcNotification;
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolType {
Calculator,
TestTool,
PingTool,
FileSystem,
}
impl ToolType {
pub fn to_tool_provider(&self) -> Arc<dyn ToolProvider> {
match self {
ToolType::Calculator => Arc::new(calculator::CalculatorTool::new()),
ToolType::TestTool => Arc::new(TestTool::new()),
ToolType::PingTool => Arc::new(PingTool::new()),
ToolType::FileSystem => Arc::new(file_system::FileSystemTools::new()),
}
}
}
// Tool Types
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tool {
pub name: String,
pub description: String,
pub input_schema: ToolInputSchema,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolInputSchema {
#[serde(rename = "type")]
pub schema_type: String,
pub properties: HashMap<String, Value>,
pub required: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
#[serde(rename_all = "camelCase")]
pub enum ToolContent {
#[serde(rename = "text")]
Text { text: String },
#[serde(rename = "image")]
Image { data: String, mime_type: String },
#[serde(rename = "resource")]
Resource { resource: ResourceContent },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ResourceContent {
pub uri: String,
pub mime_type: Option<String>,
pub text: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolResult {
pub content: Vec<ToolContent>,
pub is_error: bool,
#[serde(skip_serializing_if = "Option::is_none")]
#[serde(default)]
#[serde(rename = "_meta")]
pub _meta: Option<HashMap<String, Value>>,
}
// Request/Response types
#[derive(Debug, Deserialize, Serialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ListToolsRequest {
pub cursor: Option<String>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListToolsResponse {
pub tools: Vec<Tool>,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<String>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CallToolRequest {
pub name: String,
pub arguments: Value,
#[serde(flatten)]
#[serde(skip_serializing_if = "Option::is_none")]
pub metadata: Option<CallToolArgs>,
}
#[derive(Debug, Serialize, Deserialize, TypedBuilder)]
#[serde(rename_all = "camelCase")]
pub struct CallToolArgs {
#[serde(skip_serializing_if = "Option::is_none")]
#[builder(default, setter(into))]
pub tool_id: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
#[builder(default, setter(into))]
pub session_id: Option<String>,
}
// Tool Provider trait
#[async_trait]
pub trait ToolProvider: Send + Sync {
/// Get tool definition
fn get_tool(&self) -> Tool;
/// Execute tool
async fn execute(
&self,
arguments: Value,
metadata: Option<CallToolArgs>,
) -> Result<ToolResult, McpError>;
}
// Tool Manager
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolCapabilities {
pub list_changed: bool,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ToolUpdateNotification {
pub tool_name: String,
pub update_type: ToolUpdateType,
pub details: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ToolUpdateType {
Added,
Updated,
Removed,
}
pub struct ToolManager {
pub tools: Arc<RwLock<HashMap<String, Arc<dyn ToolProvider>>>>,
pub capabilities: ToolCapabilities,
notification_tx: Option<mpsc::Sender<JsonRpcNotification>>,
}
impl ToolManager {
pub fn new(capabilities: ToolCapabilities) -> Self {
Self {
tools: Arc::new(RwLock::new(HashMap::new())),
notification_tx: None,
capabilities,
}
}
pub fn with_notification_sender(
capabilities: ToolCapabilities,
notification_tx: mpsc::Sender<JsonRpcNotification>,
) -> Self {
Self {
tools: Arc::new(RwLock::new(HashMap::new())),
notification_tx: Some(notification_tx),
capabilities,
}
}
pub async fn register_tool(&self, provider: Arc<dyn ToolProvider>) {
let tool = provider.get_tool();
let mut tools = self.tools.write().await;
tools.insert(tool.name.clone(), provider);
// Send notification if tool updates are enabled
if self.capabilities.list_changed {
self.send_tool_update_notification(
&tool.name,
ToolUpdateType::Added,
Some(format!("Tool '{}' registered", tool.name)),
)
.await;
}
}
pub async fn unregister_tool(&self, name: &str) -> Result<(), McpError> {
let mut tools = self.tools.write().await;
if tools.remove(name).is_some() {
// Send notification if tool updates are enabled
if self.capabilities.list_changed {
self.send_tool_update_notification(
name,
ToolUpdateType::Removed,
Some(format!("Tool '{}' unregistered", name)),
)
.await;
}
Ok(())
} else {
Err(McpError::InvalidRequest(format!(
"Tool '{}' not found",
name
)))
}
}
pub async fn update_tool(&self, provider: Arc<dyn ToolProvider>) -> Result<(), McpError> {
let tool = provider.get_tool();
let mut tools = self.tools.write().await;
if tools.contains_key(&tool.name) {
tools.insert(tool.name.clone(), provider);
// Send notification if tool updates are enabled
if self.capabilities.list_changed {
self.send_tool_update_notification(
&tool.name,
ToolUpdateType::Updated,
Some(format!("Tool '{}' updated", tool.name)),
)
.await;
}
Ok(())
} else {
Err(McpError::InvalidRequest(format!(
"Tool '{}' not found",
tool.name
)))
}
}
async fn send_tool_update_notification(
&self,
tool_name: &str,
update_type: ToolUpdateType,
details: Option<String>,
) {
if let Some(tx) = &self.notification_tx {
let notification = ToolUpdateNotification {
tool_name: tool_name.to_string(),
update_type,
details,
};
let json_notification = JsonRpcNotification {
jsonrpc: "2.0".to_string(),
method: "tools/update".to_string(),
params: Some(serde_json::to_value(notification).unwrap_or_default()),
};
if let Err(e) = tx.send(json_notification).await {
tracing::error!("Failed to send tool update notification: {}", e);
}
}
}
pub async fn list_tools(&self, _cursor: Option<String>) -> Result<ListToolsResponse, McpError> {
let tools = self.tools.read().await;
let mut tool_list = Vec::new();
for provider in tools.values() {
tool_list.push(provider.get_tool());
}
Ok(ListToolsResponse {
tools: tool_list,
next_cursor: None, // Implement pagination if needed
})
}
pub async fn call_tool(
&self,
name: &str,
arguments: Value,
metadata: Option<CallToolArgs>,
) -> Result<ToolResult, McpError> {
let tools = self.tools.read().await;
let provider = tools
.get(name)
.ok_or_else(|| McpError::InvalidRequest(format!("Unknown tool: {}", name)))?;
provider.execute(arguments, metadata).await
}
}