Skip to content

Commit 22d41e0

Browse files
committed
chore: refine the code
replace GDBCommandReponse with Ok(String) or AppError Signed-off-by: Lix Zhou
1 parent 5a5f242 commit 22d41e0

File tree

5 files changed

+57
-138
lines changed

5 files changed

+57
-138
lines changed

src/bin/gdb_client.rs

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use mcp_core::{
77
transport::{ClientSseTransport, ClientSseTransportBuilder, ClientStdioTransport},
88
types::{ClientCapabilities, Implementation, ToolResponseContent},
99
};
10-
use serde_json::{json, Value};
10+
use serde_json::{Value, json};
1111
use tracing::{debug, info};
1212
use tracing_subscriber::{EnvFilter, layer::SubscriberExt, util::SubscriberInitExt};
1313

@@ -42,7 +42,11 @@ struct Args {
4242
}
4343

4444
// Helper function to call the call_tool method on any type of client
45-
async fn call_tool(client: &Box<dyn Any>, tool_name: &str, params: Option<Value>) -> Result<Vec<ToolResponseContent>> {
45+
async fn call_tool(
46+
client: &Box<dyn Any>,
47+
tool_name: &str,
48+
params: Option<Value>,
49+
) -> Result<Vec<ToolResponseContent>> {
4650
info!("Calling tool: {}", tool_name);
4751
debug!("Params: {:?}", params);
4852
if let Some(client) = client.downcast_ref::<Client<ClientStdioTransport>>() {
@@ -75,8 +79,10 @@ async fn main() -> Result<()> {
7579
// Create client based on transport type
7680
let client: Box<dyn Any> = match args.transport {
7781
TransportType::Stdio => {
78-
let transport =
79-
ClientStdioTransport::new("./target/debug/mcp_server_gdb", &["--log-level", "debug"])?;
82+
let transport = ClientStdioTransport::new(
83+
"./target/debug/mcp_server_gdb",
84+
&["--log-level", "debug"],
85+
)?;
8086
let client = ClientBuilder::new(transport).build();
8187

8288
// Connect to server
@@ -111,7 +117,8 @@ async fn main() -> Result<()> {
111117
let session_response = call_tool(
112118
&client,
113119
"create_session",
114-
args.executable.map(|path| json!({ "executable_path": path })),
120+
args.executable
121+
.map(|path| json!({ "executable_path": path })),
115122
)
116123
.await?;
117124

src/error.rs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@ pub enum AppError {
66
#[error("GDB error: {0}")]
77
GDBError(String),
88

9+
#[error("GDB timeout")]
10+
GDBTimeout,
11+
912
#[error("Parse error: {0}")]
1013
#[allow(dead_code)]
1114
ParseError(String),

src/gdb.rs

Lines changed: 30 additions & 110 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use uuid::Uuid;
1616
use crate::{
1717
config::Config,
1818
error::{AppError, AppResult},
19-
models::{Breakpoint, GDBCommandResponse, GDBSession, GDBSessionStatus, StackFrame, Variable},
19+
models::{Breakpoint, GDBSession, GDBSessionStatus, StackFrame, Variable},
2020
};
2121

2222
/// GDB Session Manager
@@ -148,7 +148,7 @@ impl GDBManager {
148148
&self,
149149
session_id: &str,
150150
command: &str,
151-
) -> AppResult<GDBCommandResponse> {
151+
) -> AppResult<String> {
152152
let sessions = self.sessions.read().await;
153153
let handle = sessions
154154
.get(session_id)
@@ -158,24 +158,20 @@ impl GDBManager {
158158

159159
// Parse output
160160
let success = !output.contains("^error");
161-
let error = if !success {
161+
if !success {
162162
// Extract error message
163163
static ERROR_REGEX: LazyLock<Regex> =
164164
LazyLock::new(|| Regex::new(r#"\^error,msg="(.+)""#).unwrap());
165165

166-
ERROR_REGEX
166+
let error = ERROR_REGEX
167167
.captures(&output)
168168
.and_then(|caps| caps.get(1))
169169
.map(|m| m.as_str().to_string())
170-
} else {
171-
None
172-
};
170+
.unwrap_or_else(|| "Unknown error".to_string());
171+
return Err(AppError::GDBError(error));
172+
}
173173

174-
Ok(GDBCommandResponse {
175-
success,
176-
output,
177-
error,
178-
})
174+
Ok(output)
179175
}
180176

181177
/// Send raw command to GDB
@@ -250,66 +246,50 @@ impl GDBManager {
250246
&self,
251247
session_id: &str,
252248
command: &str,
253-
) -> AppResult<GDBCommandResponse> {
249+
) -> AppResult<String> {
254250
let command_timeout = self.config.command_timeout;
255251
match tokio::time::timeout(
256252
Duration::from_secs(command_timeout),
257253
self.send_command(session_id, command),
258254
)
259255
.await
260256
{
261-
Ok(result) => result,
262-
Err(_) => Err(AppError::GDBError(format!(
263-
"GDB command '{}' timed out",
264-
command
265-
))),
257+
Ok(Ok(result)) => {
258+
Ok(result)
259+
}
260+
Ok(Err(e)) => Err(e),
261+
Err(_) => Err(AppError::GDBTimeout),
266262
}
267263
}
268264

269265
/// Start debugging
270-
pub async fn start_debugging(&self, session_id: &str) -> AppResult<()> {
266+
pub async fn start_debugging(&self, session_id: &str) -> AppResult<String> {
271267
let response = self
272268
.send_command_with_timeout(session_id, "-exec-run")
273269
.await?;
274270

275-
if !response.success {
276-
return Err(AppError::GDBError(
277-
response
278-
.error
279-
.unwrap_or_else(|| "Failed to start debugging".to_string()),
280-
));
281-
}
282-
283271
// Update session status
284272
let mut sessions = self.sessions.write().await;
285273
if let Some(handle) = sessions.get_mut(session_id) {
286274
handle.info.status = GDBSessionStatus::Running;
287275
}
288276

289-
Ok(())
277+
Ok(response)
290278
}
291279

292280
/// Stop debugging
293-
pub async fn stop_debugging(&self, session_id: &str) -> AppResult<()> {
281+
pub async fn stop_debugging(&self, session_id: &str) -> AppResult<String> {
294282
let response = self
295283
.send_command_with_timeout(session_id, "-exec-interrupt")
296284
.await?;
297285

298-
if !response.success {
299-
return Err(AppError::GDBError(
300-
response
301-
.error
302-
.unwrap_or_else(|| "Failed to stop debugging".to_string()),
303-
));
304-
}
305-
306286
// Update session status
307287
let mut sessions = self.sessions.write().await;
308288
if let Some(handle) = sessions.get_mut(session_id) {
309289
handle.info.status = GDBSessionStatus::Stopped;
310290
}
311291

312-
Ok(())
292+
Ok(response)
313293
}
314294

315295
/// Get breakpoint list
@@ -318,14 +298,6 @@ impl GDBManager {
318298
.send_command_with_timeout(session_id, "-break-list")
319299
.await?;
320300

321-
if !response.success {
322-
return Err(AppError::GDBError(
323-
response
324-
.error
325-
.unwrap_or_else(|| "Failed to get breakpoint list".to_string()),
326-
));
327-
}
328-
329301
// Parse breakpoint information (simplified version, actually needs more complex parsing)
330302
let breakpoints = Vec::new();
331303

@@ -345,14 +317,6 @@ impl GDBManager {
345317
let command = format!("-break-insert {}:{}", file, line);
346318
let response = self.send_command_with_timeout(session_id, &command).await?;
347319

348-
if !response.success {
349-
return Err(AppError::GDBError(
350-
response
351-
.error
352-
.unwrap_or_else(|| "Failed to set breakpoint".to_string()),
353-
));
354-
}
355-
356320
// Parse breakpoint ID (simplified)
357321
let breakpoint_id = Uuid::new_v4().to_string(); // Should actually be extracted from response
358322

@@ -365,19 +329,15 @@ impl GDBManager {
365329
}
366330

367331
/// Delete breakpoint
368-
pub async fn delete_breakpoint(&self, session_id: &str, breakpoint_id: &str) -> AppResult<()> {
332+
pub async fn delete_breakpoint(
333+
&self,
334+
session_id: &str,
335+
breakpoint_id: &str,
336+
) -> AppResult<String> {
369337
let command = format!("-break-delete {}", breakpoint_id);
370338
let response = self.send_command_with_timeout(session_id, &command).await?;
371339

372-
if !response.success {
373-
return Err(AppError::GDBError(
374-
response
375-
.error
376-
.unwrap_or_else(|| "Failed to delete breakpoint".to_string()),
377-
));
378-
}
379-
380-
Ok(())
340+
Ok(response)
381341
}
382342

383343
/// Get stack frames
@@ -386,14 +346,6 @@ impl GDBManager {
386346
.send_command_with_timeout(session_id, "-stack-list-frames")
387347
.await?;
388348

389-
if !response.success {
390-
return Err(AppError::GDBError(
391-
response
392-
.error
393-
.unwrap_or_else(|| "Failed to get stack frames".to_string()),
394-
));
395-
}
396-
397349
// Parse stack frame information (simplified)
398350
let frames = Vec::new(); // Actually needs to parse response
399351

@@ -409,74 +361,42 @@ impl GDBManager {
409361
let command = format!("-stack-list-variables --frame {} --simple-values", frame_id);
410362
let response = self.send_command_with_timeout(session_id, &command).await?;
411363

412-
if !response.success {
413-
return Err(AppError::GDBError(
414-
response
415-
.error
416-
.unwrap_or_else(|| "Failed to get local variables".to_string()),
417-
));
418-
}
419-
420364
// Parse variable information (simplified)
421365
let variables = Vec::new(); // Actually needs to parse response
422366

423367
Ok(variables)
424368
}
425369

426370
/// Continue execution
427-
pub async fn continue_execution(&self, session_id: &str) -> AppResult<()> {
371+
pub async fn continue_execution(&self, session_id: &str) -> AppResult<String> {
428372
let response = self
429373
.send_command_with_timeout(session_id, "-exec-continue")
430374
.await?;
431375

432-
if !response.success {
433-
return Err(AppError::GDBError(
434-
response
435-
.error
436-
.unwrap_or_else(|| "Failed to continue execution".to_string()),
437-
));
438-
}
439-
440376
// Update session status
441377
let mut sessions = self.sessions.write().await;
442378
if let Some(handle) = sessions.get_mut(session_id) {
443379
handle.info.status = GDBSessionStatus::Running;
444380
}
445381

446-
Ok(())
382+
Ok(response)
447383
}
448384

449385
/// Step execution
450-
pub async fn step_execution(&self, session_id: &str) -> AppResult<()> {
386+
pub async fn step_execution(&self, session_id: &str) -> AppResult<String> {
451387
let response = self
452388
.send_command_with_timeout(session_id, "-exec-step")
453389
.await?;
454390

455-
if !response.success {
456-
return Err(AppError::GDBError(
457-
response
458-
.error
459-
.unwrap_or_else(|| "Failed to step execution".to_string()),
460-
));
461-
}
462-
463-
Ok(())
391+
Ok(response)
464392
}
465393

466394
/// Next execution
467-
pub async fn next_execution(&self, session_id: &str) -> AppResult<()> {
395+
pub async fn next_execution(&self, session_id: &str) -> AppResult<String> {
468396
let response = self
469397
.send_command_with_timeout(session_id, "-exec-next")
470398
.await?;
471399

472-
if !response.success {
473-
return Err(AppError::GDBError(
474-
response
475-
.error
476-
.unwrap_or_else(|| "Failed to execute next step".to_string()),
477-
));
478-
}
479-
480-
Ok(())
400+
Ok(response)
481401
}
482402
}

src/models.rs

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -33,17 +33,6 @@ pub struct GDBCommandRequest {
3333
pub command: String,
3434
}
3535

36-
/// GDB command response
37-
#[derive(Debug, Clone, Serialize, Deserialize)]
38-
pub struct GDBCommandResponse {
39-
/// Success status
40-
pub success: bool,
41-
/// Response content
42-
pub output: String,
43-
/// Error message (if any)
44-
pub error: Option<String>,
45-
}
46-
4736
/// Create session request
4837
#[derive(Debug, Clone, Serialize, Deserialize)]
4938
pub struct CreateSessionRequest {

0 commit comments

Comments
 (0)