defect-cli 0.1.0-alpha.6

defect: a highly configurable, ACP-native, resource-frugal headless general-purpose agent CLI.
Documentation
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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use agent_client_protocol::AcpAgent;
use agent_client_protocol_schema::{
    ContentBlock, EnvVariable, InitializeRequest, McpServer, McpServerSse, McpServerStdio,
    NewSessionRequest, PromptRequest, ProtocolVersion, SessionNotification, SessionUpdate,
    StopReason, ToolCallContent, ToolCallStatus,
};
use serde_json::Value;
use wiremock::matchers::{header, method, path};
use wiremock::{Mock, MockServer, Request, ResponseTemplate};

const TEST_OPENAI_API_KEY: &str = "test-openai-key";
const TEST_OPENAI_AUTH_HEADER: &str = "Bearer test-openai-key";
const DONE: &str = "[DONE]";

// MCP 测试桩从 `[[bin]]` 改成 `[[example]]`(避免被 cargo-binstall 枚举进 release
// 产物),故没有 `CARGO_BIN_EXE_*` 编译期 env。example 产物固定落在
// `target/<profile>/examples/<name>`,与本测试 bin 同处 `target/<profile>/` 下,
// 经 current_exe 上溯定位。Windows 需补 `.exe` 后缀。
fn example_bin(name: &str) -> PathBuf {
    let mut path = std::env::current_exe().expect("current exe path");
    path.pop(); // 去掉测试 bin 文件名
    if path.ends_with("deps") {
        path.pop(); // deps/ -> <profile>/
    }
    path.push("examples");
    path.push(format!("{name}{}", std::env::consts::EXE_SUFFIX));
    path
}

#[tokio::test]
async fn stdio_mcp_tool_round_trip() {
    let openai = MockServer::start().await;
    let state_root = tempfile::tempdir().expect("state tempdir");
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let round1 = openai_sse_body(&[
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_echo","type":"function","function":{"name":"mcp__mcp-echo__echo","arguments":""}}]},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"message\":\"hello from mcp\"}"}}]},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}"#,
    ]);
    let round2 = openai_sse_body(&[
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{"content":"done after mcp"},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}"#,
    ]);

    Mock::given(method("POST"))
        .and(path("/chat/completions"))
        .and(header("authorization", TEST_OPENAI_AUTH_HEADER))
        .respond_with(move |req: &Request| {
            let body: Value = serde_json::from_slice(&req.body).expect("body json");
            let has_tool_result = body
                .get("messages")
                .and_then(Value::as_array)
                .map(|messages| {
                    messages
                        .iter()
                        .any(|message| message.get("role").and_then(Value::as_str) == Some("tool"))
                })
                .unwrap_or(false);
            let payload = if has_tool_result {
                round2.clone()
            } else {
                round1.clone()
            };
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/event-stream")
                .set_body_raw(payload, "text/event-stream")
        })
        .expect(2)
        .mount(&openai)
        .await;

    let binary = PathBuf::from(env!("CARGO_BIN_EXE_defect"));
    let agent = AcpAgent::from_args([
        format!("XDG_STATE_HOME={}", state_root.path().display()),
        format!("OPENAI_API_KEY={TEST_OPENAI_API_KEY}"),
        format!("OPENAI_BASE_URL={}", openai.uri()),
        binary.display().to_string(),
        "--provider".to_string(),
        "openai".to_string(),
    ])
    .expect("valid defect command");

    let updates: Arc<Mutex<Vec<SessionUpdate>>> = Arc::new(Mutex::new(Vec::new()));
    let updates_for_handler = Arc::clone(&updates);
    let mcp_server = McpServer::Stdio(
        McpServerStdio::new("mcp-echo", example_bin("defect-mcp-test-server"))
            .env(vec![EnvVariable::new("MCP_TEST_VALUE", "from-env")]),
    );

    let stop_reason = agent_client_protocol::Client
        .builder()
        .name("stdio-mcp-smoke-client")
        .on_receive_notification(
            async move |notification: SessionNotification, _cx| {
                updates_for_handler
                    .lock()
                    .expect("updates mutex")
                    .push(notification.update);
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        )
        .connect_with(agent, async move |cx| {
            cx.send_request(InitializeRequest::new(ProtocolVersion::V1))
                .block_task()
                .await?;

            let session = cx
                .send_request(NewSessionRequest::new(cwd.path()).mcp_servers(vec![mcp_server]))
                .block_task()
                .await?;

            let response = cx
                .send_request(PromptRequest::new(
                    session.session_id,
                    vec![ContentBlock::from("please use the mcp tool")],
                ))
                .block_task()
                .await?;

            Ok(response.stop_reason)
        })
        .await
        .expect("client connection completed");

    assert_eq!(stop_reason, StopReason::EndTurn);

    let updates = updates.lock().expect("updates mutex");
    let tool_completion = updates.iter().find_map(|update| match update {
        SessionUpdate::ToolCallUpdate(tool_update)
            if tool_update.fields.status == Some(ToolCallStatus::Completed) =>
        {
            tool_update.fields.content.as_ref()
        }
        _ => None,
    });
    let Some(tool_completion) = tool_completion else {
        panic!("expected completed tool update; updates={updates:?}");
    };
    assert!(
        tool_completion.iter().any(|content| matches!(
            content,
            ToolCallContent::Content(block)
                if matches!(
                    &block.content,
                    ContentBlock::Text(text)
                        if text.text.contains(r#""echo":"hello from mcp""#)
                            && text.text.contains(r#""env":"from-env""#)
                )
        )),
        "tool completion should contain MCP response; updates={updates:?}",
    );

    let assistant_chunks: String = updates
        .iter()
        .filter_map(|update| match update {
            SessionUpdate::AgentMessageChunk(chunk) => Some(&chunk.content),
            _ => None,
        })
        .filter_map(|content| match content {
            ContentBlock::Text(text) => Some(text.text.as_str()),
            _ => None,
        })
        .collect();
    assert!(
        assistant_chunks.contains("done after mcp"),
        "assistant updates should include second-round text; got {assistant_chunks:?}",
    );
}

#[tokio::test]
async fn config_enabled_stdio_mcp_tool_round_trip() {
    let openai = MockServer::start().await;
    let state_root = tempfile::tempdir().expect("state tempdir");
    let config_root = tempfile::tempdir().expect("config tempdir");
    let cwd = tempfile::tempdir().expect("cwd tempdir");

    let round1 = openai_sse_body(&[
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_echo","type":"function","function":{"name":"mcp__echo__echo","arguments":""}}]},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"message\":\"hello from mcp\"}"}}]},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}"#,
    ]);
    let round2 = openai_sse_body(&[
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{"content":"done after mcp"},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}"#,
    ]);

    Mock::given(method("POST"))
        .and(path("/chat/completions"))
        .and(header("authorization", TEST_OPENAI_AUTH_HEADER))
        .respond_with(move |req: &Request| {
            let body: Value = serde_json::from_slice(&req.body).expect("body json");
            let has_tool_result = body
                .get("messages")
                .and_then(Value::as_array)
                .map(|messages| {
                    messages
                        .iter()
                        .any(|message| message.get("role").and_then(Value::as_str) == Some("tool"))
                })
                .unwrap_or(false);
            let payload = if has_tool_result {
                round2.clone()
            } else {
                round1.clone()
            };
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/event-stream")
                .set_body_raw(payload, "text/event-stream")
        })
        .expect(2)
        .mount(&openai)
        .await;

    let config_path = config_root.path().join("defect/config.toml");
    std::fs::create_dir_all(
        config_path
            .parent()
            .expect("config.toml should have a parent directory"),
    )
    .expect("config directory");
    std::fs::write(
        &config_path,
        format!(
            r#"[mcp]
enabled_servers = ["echo"]

[mcp.servers.echo]
transport = "stdio"
command = "{}"

[mcp.servers.echo.env]
MCP_TEST_VALUE = "from-config"
"#,
            example_bin("defect-mcp-test-server").display()
        ),
    )
    .expect("write user config");

    let binary = PathBuf::from(env!("CARGO_BIN_EXE_defect"));
    let agent = AcpAgent::from_args([
        format!("XDG_STATE_HOME={}", state_root.path().display()),
        format!("XDG_CONFIG_HOME={}", config_root.path().display()),
        format!("OPENAI_API_KEY={TEST_OPENAI_API_KEY}"),
        format!("OPENAI_BASE_URL={}", openai.uri()),
        binary.display().to_string(),
        "--provider".to_string(),
        "openai".to_string(),
    ])
    .expect("valid defect command");

    let updates: Arc<Mutex<Vec<SessionUpdate>>> = Arc::new(Mutex::new(Vec::new()));
    let updates_for_handler = Arc::clone(&updates);

    let stop_reason = agent_client_protocol::Client
        .builder()
        .name("config-stdio-mcp-smoke-client")
        .on_receive_notification(
            async move |notification: SessionNotification, _cx| {
                updates_for_handler
                    .lock()
                    .expect("updates mutex")
                    .push(notification.update);
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        )
        .connect_with(agent, async move |cx| {
            cx.send_request(InitializeRequest::new(ProtocolVersion::V1))
                .block_task()
                .await?;

            let session = cx
                .send_request(NewSessionRequest::new(cwd.path()))
                .block_task()
                .await?;

            let response = cx
                .send_request(PromptRequest::new(
                    session.session_id,
                    vec![ContentBlock::from("please use the configured mcp tool")],
                ))
                .block_task()
                .await?;

            Ok(response.stop_reason)
        })
        .await
        .expect("client connection completed");

    assert_eq!(stop_reason, StopReason::EndTurn);

    let updates = updates.lock().expect("updates mutex");
    let tool_completion = updates.iter().find_map(|update| match update {
        SessionUpdate::ToolCallUpdate(tool_update)
            if tool_update.fields.status == Some(ToolCallStatus::Completed) =>
        {
            tool_update.fields.content.as_ref()
        }
        _ => None,
    });
    let Some(tool_completion) = tool_completion else {
        panic!("expected completed tool update; updates={updates:?}");
    };
    assert!(
        tool_completion.iter().any(|content| matches!(
            content,
            ToolCallContent::Content(block)
                if matches!(
                    &block.content,
                    ContentBlock::Text(text)
                        if text.text.contains(r#""echo":"hello from mcp""#)
                            && text.text.contains(r#""env":"from-config""#)
                )
        )),
        "tool completion should contain configured MCP response; updates={updates:?}",
    );
}

fn openai_sse_body(chunks: &[&str]) -> Vec<u8> {
    let mut body = Vec::new();
    for chunk in chunks {
        body.extend_from_slice(b"data: ");
        body.extend_from_slice(chunk.as_bytes());
        body.extend_from_slice(b"\n\n");
    }
    body.extend_from_slice(b"data: ");
    body.extend_from_slice(DONE.as_bytes());
    body.extend_from_slice(b"\n\n");
    body
}

#[tokio::test]
async fn sse_mcp_tool_round_trip() {
    let state_root = tempfile::tempdir().expect("state tempdir");
    let cwd = tempfile::tempdir().expect("cwd tempdir");
    let server = spawn_streamable_http_server().await;

    let binary = PathBuf::from(env!("CARGO_BIN_EXE_defect"));
    let agent = AcpAgent::from_args([
        format!("XDG_STATE_HOME={}", state_root.path().display()),
        format!("OPENAI_API_KEY={TEST_OPENAI_API_KEY}"),
        format!("OPENAI_BASE_URL={}", server.openai.uri()),
        binary.display().to_string(),
        "--provider".to_string(),
        "openai".to_string(),
    ])
    .expect("valid defect command");

    let updates: Arc<Mutex<Vec<SessionUpdate>>> = Arc::new(Mutex::new(Vec::new()));
    let updates_for_handler = Arc::clone(&updates);

    let stop_reason = agent_client_protocol::Client
        .builder()
        .name("sse-mcp-smoke-client")
        .on_receive_notification(
            async move |notification: SessionNotification, _cx| {
                updates_for_handler
                    .lock()
                    .expect("updates mutex")
                    .push(notification.update);
                Ok(())
            },
            agent_client_protocol::on_receive_notification!(),
        )
        .connect_with(agent, async move |cx| {
            cx.send_request(InitializeRequest::new(ProtocolVersion::V1))
                .block_task()
                .await?;

            let mcp_server = McpServer::Sse(
                McpServerSse::new("mcp-sse", format!("{}/mcp", server.mcp_base_url)).headers(vec![
                    agent_client_protocol_schema::HttpHeader::new("x-mcp-test", "enabled"),
                ]),
            );
            let session = cx
                .send_request(NewSessionRequest::new(cwd.path()).mcp_servers(vec![mcp_server]))
                .block_task()
                .await?;
            let response = cx
                .send_request(PromptRequest::new(
                    session.session_id,
                    vec![ContentBlock::from("please use the sse mcp tool")],
                ))
                .block_task()
                .await?;
            Ok(response.stop_reason)
        })
        .await
        .expect("client connection completed");

    assert_eq!(stop_reason, StopReason::EndTurn);

    let updates = updates.lock().expect("updates mutex");
    let tool_completion = updates.iter().find_map(|update| match update {
        SessionUpdate::ToolCallUpdate(tool_update)
            if tool_update.fields.status == Some(ToolCallStatus::Completed) =>
        {
            tool_update.fields.content.as_ref()
        }
        _ => None,
    });
    let Some(tool_completion) = tool_completion else {
        panic!("expected completed tool update; updates={updates:?}");
    };
    assert!(
        tool_completion.iter().any(|content| matches!(
            content,
            ToolCallContent::Content(block)
                if matches!(
                    &block.content,
                    ContentBlock::Text(text)
                        if text.text.contains(r#""echo":"hello from mcp""#)
                            && text.text.contains(r#""env":"from-env""#)
                )
        )),
        "tool completion should contain MCP response; updates={updates:?}",
    );
}

struct StreamableHttpServerHandle {
    child: tokio::process::Child,
    mcp_base_url: String,
    openai: MockServer,
}

impl Drop for StreamableHttpServerHandle {
    fn drop(&mut self) {
        let _ = self.child.start_kill();
    }
}

async fn spawn_streamable_http_server() -> StreamableHttpServerHandle {
    let openai = MockServer::start().await;
    let round1 = openai_sse_body(&[
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{"role":"assistant","content":null,"tool_calls":[{"index":0,"id":"call_echo","type":"function","function":{"name":"mcp__mcp-sse__echo","arguments":""}}]},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{"tool_calls":[{"index":0,"function":{"arguments":"{\"message\":\"hello from mcp\"}"}}]},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r1","object":"chat.completion.chunk","created":1,"model":"gpt-test-001","choices":[{"index":0,"delta":{},"finish_reason":"tool_calls"}]}"#,
    ]);
    let round2 = openai_sse_body(&[
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{"content":"done after mcp"},"finish_reason":null}]}"#,
        r#"{"id":"chatcmpl-r2","object":"chat.completion.chunk","created":2,"model":"gpt-test-001","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}"#,
    ]);

    Mock::given(method("POST"))
        .and(path("/chat/completions"))
        .and(header("authorization", TEST_OPENAI_AUTH_HEADER))
        .respond_with(move |req: &Request| {
            let body: Value = serde_json::from_slice(&req.body).expect("body json");
            let has_tool_result = body
                .get("messages")
                .and_then(Value::as_array)
                .map(|messages| {
                    messages
                        .iter()
                        .any(|message| message.get("role").and_then(Value::as_str) == Some("tool"))
                })
                .unwrap_or(false);
            let payload = if has_tool_result {
                round2.clone()
            } else {
                round1.clone()
            };
            ResponseTemplate::new(200)
                .insert_header("content-type", "text/event-stream")
                .set_body_raw(payload, "text/event-stream")
        })
        .expect(2)
        .mount(&openai)
        .await;

    let addr_file = tempfile::NamedTempFile::new().expect("addr file");
    let addr_path = addr_file.path().to_path_buf();
    let child = tokio::process::Command::new(example_bin("defect-mcp-streamable-http-test-server"))
        .env("MCP_STREAMABLE_HTTP_BOUND_ADDR_FILE", addr_path.as_os_str())
        .env("MCP_TEST_VALUE", "from-env")
        .spawn()
        .expect("streamable http MCP server should spawn");

    let mcp_base_url = wait_for_bound_addr(&addr_path).await;
    StreamableHttpServerHandle {
        child,
        mcp_base_url: format!("http://{mcp_base_url}"),
        openai,
    }
}

async fn wait_for_bound_addr(path: &std::path::Path) -> String {
    const MAX_ATTEMPTS: usize = 100;
    const SLEEP_MS: u64 = 50;

    for _ in 0..MAX_ATTEMPTS {
        if let Ok(bound_addr) = std::fs::read_to_string(path) {
            let trimmed = bound_addr.trim();
            if !trimmed.is_empty() {
                return trimmed.to_string();
            }
        }
        tokio::time::sleep(Duration::from_millis(SLEEP_MS)).await;
    }

    panic!("timed out waiting for streamable http MCP server address at {path:?}");
}