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
use serde_json::{json, Value};
use std::sync::Arc;
use tokio::sync::Mutex;
use crate::{models::Config as ModelsConfig, tools::ToolHandler, McpError, McpRequest, McpResponse};
/// Auto-verify result stored after first initialization
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct AutoVerifyResult {
all_ok: bool,
hint: String,
config_path: String,
}
#[derive(Debug)]
pub struct McpServer {
initialized: Arc<Mutex<bool>>,
tool_handler: Arc<ToolHandler>,
auto_verify_result: Arc<Mutex<Option<AutoVerifyResult>>>,
}
impl McpServer {
pub fn new() -> Self {
let config = ModelsConfig::load().unwrap_or_default();
Self {
initialized: Arc::new(Mutex::new(false)),
tool_handler: Arc::new(ToolHandler::new(config)),
auto_verify_result: Arc::new(Mutex::new(None)),
}
}
/// Run verify_setup in background - non blocking
fn spawn_auto_verify(&self) {
let result_arc = self.auto_verify_result.clone();
tokio::spawn(async move {
// Get config
let config = ModelsConfig::load().unwrap_or_default();
let config_path = ModelsConfig::writable_config_path();
// Quick async file checks
let config_exists = tokio::task::spawn_blocking({
let path = config_path.clone();
move || path.exists()
}).await.unwrap_or(false);
let wine_ok = if let Some(wine) = &config.wine_executable {
let wine = wine.clone();
tokio::task::spawn_blocking(move || {
std::path::Path::new(&wine).exists()
}).await.unwrap_or(false)
} else {
false
};
let term_ok = if let Some(term) = &config.terminal_dir {
let term = term.clone();
tokio::task::spawn_blocking(move || {
std::path::Path::new(&term).is_dir()
}).await.unwrap_or(false)
} else {
false
};
let all_ok = config_exists && wine_ok && term_ok;
let hint = if all_ok {
"Environment fully configured and ready".to_string()
} else if !config_exists {
format!("Auto-discovery will run on first request. Config will be written to {}", config_path.display())
} else if !wine_ok {
"Wine/CrossOver not found - required for MT5 execution".to_string()
} else if !term_ok {
"MT5 directory not found - check installation".to_string()
} else {
"Fix missing paths in config".to_string()
};
let result = AutoVerifyResult {
all_ok,
hint,
config_path: config_path.to_string_lossy().to_string(),
};
// Store result
let mut guard = result_arc.lock().await;
*guard = Some(result);
});
}
/// Get current verify status (may be loading if called immediately after init)
#[allow(dead_code)]
async fn get_verify_status(&self) -> (Option<bool>, String) {
let guard = self.auto_verify_result.lock().await;
match guard.as_ref() {
Some(result) => (Some(result.all_ok), result.hint.clone()),
None => (None, "Checking environment...".to_string()),
}
}
/// Handle a notification (no id — no response sent)
pub async fn handle_notification(&self, request: McpRequest) {
match request.method.as_str() {
"notifications/initialized" => {
// Client confirms initialization is complete — no action needed
}
_ => {
tracing::debug!("Unhandled notification: {}", request.method);
}
}
}
pub async fn handle_request(&self, request: McpRequest) -> McpResponse {
match request.method.as_str() {
"initialize" => {
// Protocol version negotiation: client sends desired version
let client_version = request.params.as_ref()
.and_then(|p| p.get("protocolVersion"))
.and_then(|v| v.as_str())
.unwrap_or("2024-11-05");
// Server selects version (latest supported that client also supports)
let negotiated_version = if client_version.starts_with("2025-") {
"2024-11-05" // Fall back to stable version
} else {
"2024-11-05"
};
// Start background verify (non-blocking)
self.spawn_auto_verify();
*self.initialized.lock().await = true;
// Return immediately with fast status
let server_info = json!({
"name": "MT5-Quant",
"version": env!("CARGO_PKG_VERSION"),
"setup": {
"hint": "Auto-verification running... Use verify_setup tool for detailed status",
}
});
McpResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(json!({
"protocolVersion": negotiated_version,
"capabilities": {
"experimental": {},
"tools": {
"listChanged": false,
},
},
"serverInfo": server_info,
})),
error: None,
}
}
"tools/list" => {
let initialized = *self.initialized.lock().await;
if !initialized {
return McpResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: None,
error: Some(McpError {
code: -32600,
message: "Received request before initialization was complete".to_string(),
data: None,
}),
};
}
McpResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(json!({"tools": crate::tools::get_tools_list()})),
error: None,
}
}
"tools/call" => {
let initialized = *self.initialized.lock().await;
if !initialized {
return McpResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: None,
error: Some(McpError {
code: -32600,
message: "Received request before initialization was complete".to_string(),
data: None,
}),
};
}
if let Some(params) = request.params {
if let (Some(tool_name), Some(arguments)) = (
params.get("name").and_then(|v| v.as_str()),
params.get("arguments")
) {
let result = self.handle_tool_call(tool_name, arguments).await;
McpResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: Some(result),
error: None,
}
} else {
McpResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: None,
error: Some(McpError {
code: -32602,
message: "Invalid request parameters".to_string(),
data: None,
}),
}
}
} else {
McpResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: None,
error: Some(McpError {
code: -32602,
message: "Invalid request parameters".to_string(),
data: None,
}),
}
}
}
_ => {
McpResponse {
jsonrpc: "2.0".to_string(),
id: request.id,
result: None,
error: Some(McpError {
code: -32601,
message: format!("Method not found: {}", request.method),
data: None,
}),
}
}
}
}
async fn handle_tool_call(&self, tool_name: &str, arguments: &Value) -> Value {
self.tool_handler.handle(tool_name, arguments).await.unwrap_or_else(|e| json!({
"content": [{
"type": "text",
"text": format!("Tool execution failed: {}", e)
}],
"isError": true
}))
}
}