aptu-coder 0.17.1

MCP server for multi-language code structure analysis
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
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
// SPDX-FileCopyrightText: 2026 aptu-coder contributors
// SPDX-License-Identifier: Apache-2.0

mod common;

use aptu_coder::logging::LogEvent;
use common::call_tool_raw;
use rmcp::model::{CallToolResult, Content, LoggingLevel, Meta};

#[tokio::test]
async fn test_batch_draining_with_multiple_events() {
    use serde_json::json;

    let (event_tx, mut event_rx) = tokio::sync::mpsc::unbounded_channel::<LogEvent>();

    for i in 0..5 {
        let log_event = LogEvent {
            level: LoggingLevel::Info,
            logger: format!("logger_{i}"),
            data: json!({"index": i}),
        };
        let _ = event_tx.send(log_event);
    }

    let mut buffer = Vec::with_capacity(64);
    event_rx.recv_many(&mut buffer, 64).await;

    assert_eq!(buffer.len(), 5);
    for (i, event) in buffer.iter().enumerate() {
        assert_eq!(event.logger, format!("logger_{i}"));
        assert_eq!(event.data, json!({"index": i}));
    }
}

#[test]
fn test_call_tool_result_cache_hint_metadata() {
    let mut meta = serde_json::Map::new();
    meta.insert(
        "cache_hint".to_string(),
        serde_json::Value::String("no-cache".to_string()),
    );

    let result =
        CallToolResult::success(vec![Content::text("test output")]).with_meta(Some(Meta(meta)));

    let json_val = serde_json::to_value(&result).expect("should serialize");

    assert_eq!(
        json_val
            .get("_meta")
            .and_then(|m| m.get("cache_hint"))
            .and_then(|v| v.as_str()),
        Some("no-cache"),
        "Expected _meta.cache_hint to be 'no-cache' in serialized JSON: {json_val}"
    );
}

#[tokio::test]
async fn test_analyze_directory_bounded_traversal_skips_deep() {
    use tempfile::TempDir;

    // Arrange: three-level directory tree within CWD so validate_path accepts it.
    let cwd = std::env::current_dir().unwrap();
    let dir = TempDir::new_in(&cwd).unwrap();
    let root = dir.path();
    // depth 1
    std::fs::create_dir(root.join("a")).unwrap();
    std::fs::write(root.join("a/file1.rs"), "fn a1() {}").unwrap();
    // depth 2
    std::fs::create_dir(root.join("a/b")).unwrap();
    std::fs::write(root.join("a/b/file2.rs"), "fn b1() {}").unwrap();
    // depth 3 -- must be omitted
    std::fs::create_dir(root.join("a/b/c")).unwrap();
    std::fs::write(root.join("a/b/c/deep.rs"), "fn deep() {}").unwrap();

    // Act: analyze_directory with max_depth=2
    let resp = call_tool_raw(
        "analyze_directory",
        serde_json::json!({
            "path": root.to_str().unwrap(),
            "max_depth": 2,
            "page_size": 100
        }),
    )
    .await;

    // Assert: no error
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected success; got: {resp}"
    );

    // The text output must not mention the depth-3 file
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        !text.contains("deep.rs"),
        "depth-3 file 'deep.rs' must not appear in max_depth=2 output; got: {text}"
    );

    // The text must mention the depth-1 and depth-2 files
    assert!(
        text.contains("file1.rs") || text.contains("file2.rs"),
        "shallow files must appear in max_depth=2 output; got: {text}"
    );
}

#[tokio::test]
async fn test_path_outside_cwd_rejected() {
    // Arrange: path=/etc/passwd is outside the server's CWD
    let resp = call_tool_raw(
        "analyze_directory",
        serde_json::json!({
            "path": "/etc/passwd",
            "max_depth": 0,
            "page_size": 10
        }),
    )
    .await;

    // Assert: handler must reject with isError=true and mention 'outside'
    assert!(
        resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected isError=true for path outside CWD: {resp}"
    );
    let content_text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        content_text.contains("outside"),
        "error message should contain 'outside': {content_text}"
    );
}

#[tokio::test]
async fn test_analyze_module_moduleonly_cache_tier_metrics() {
    use std::io::Write as _;
    use tempfile::NamedTempFile;

    // Arrange: a temp Rust file inside CWD so validate_path accepts it
    let cwd = std::env::current_dir().unwrap();
    let mut f = NamedTempFile::with_suffix_in(".rs", &cwd).unwrap();
    writeln!(f, "fn hello() {{}}").unwrap();

    // Act: first call -- cache miss (L2 disk cache is empty for a fresh unique file)
    let resp1 = call_tool_raw(
        "analyze_module",
        serde_json::json!({ "path": f.path().to_str().unwrap() }),
    )
    .await;

    // Assert first call succeeds and returns the function name
    assert!(
        !resp1["result"]["isError"].as_bool().unwrap_or(false),
        "first analyze_module call must succeed; got: {resp1}"
    );
    let text1 = resp1["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text1.contains("hello"),
        "first call output must contain function 'hello'; got: {text1}"
    );

    // Wait for the write-behind L2 task to flush the cache entry to disk.
    // Poll for the expected cache file rather than sleeping a fixed duration to avoid flakiness.
    {
        let file_bytes = std::fs::read(f.path()).expect("temp file must be readable");
        let hash = blake3::hash(&file_bytes);
        let hex = hash.to_hex();
        let cache_dir = std::env::var("APTU_CODER_DISK_CACHE_DIR")
            .map(std::path::PathBuf::from)
            .unwrap_or_else(|_| {
                let xdg = std::env::var("XDG_DATA_HOME").unwrap_or_else(|_| {
                    std::env::var("HOME")
                        .map(|h| format!("{h}/.local/share"))
                        .unwrap_or_else(|_| ".".to_string())
                });
                std::path::PathBuf::from(xdg)
                    .join("aptu-coder")
                    .join("analysis-cache")
            });
        let entry = cache_dir
            .join("analyze_module")
            .join(&hex[..2])
            .join(format!("{}.json.snap", hex.as_str()));
        let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
        loop {
            if entry.exists() {
                break;
            }
            assert!(
                std::time::Instant::now() < deadline,
                "L2 disk cache entry not written within 5 s; expected path: {}",
                entry.display()
            );
            tokio::time::sleep(tokio::time::Duration::from_millis(10)).await;
        }
    }

    // Act: second call on same file -- content hash unchanged so L2 disk cache should hit
    let resp2 = call_tool_raw(
        "analyze_module",
        serde_json::json!({ "path": f.path().to_str().unwrap() }),
    )
    .await;

    // Assert second call succeeds with consistent output
    assert!(
        !resp2["result"]["isError"].as_bool().unwrap_or(false),
        "second analyze_module call must succeed; got: {resp2}"
    );
    let text2 = resp2["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text2.contains("hello"),
        "second call output must contain function 'hello'; got: {text2}"
    );
}

#[tokio::test]
async fn test_fields_functions_only_structured() {
    use std::io::Write as _;
    use tempfile::NamedTempFile;

    // Arrange: temp Rust file with functions, a class, and an import
    let cwd = std::env::current_dir().unwrap();
    let mut f = NamedTempFile::with_suffix_in(".rs", &cwd).unwrap();
    writeln!(
        f,
        "use std::collections::HashMap;\npub struct Foo {{}}\nimpl Foo {{\n    pub fn bar(&self) {{}}\n}}\npub fn baz() {{}}\n"
    )
    .unwrap();

    // Act: analyze_file with fields=[functions]
    let resp = call_tool_raw(
        "analyze_file",
        serde_json::json!({
            "path": f.path().to_str().unwrap(),
            "ast_recursion_limit": null,
            "page_size": null,
            "fields": ["functions"]
        }),
    )
    .await;

    // Assert: no error
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected success; got: {resp}"
    );

    // Inspect structuredContent.semantic
    let sc = &resp["result"]["structuredContent"];
    let functions = sc["semantic"]["functions"]
        .as_array()
        .expect("functions must be array");
    let classes = sc["semantic"]["classes"]
        .as_array()
        .expect("classes must be array");
    let imports = sc["semantic"]["imports"]
        .as_array()
        .expect("imports must be array");

    assert!(
        !functions.is_empty(),
        "functions must be non-empty for fields=[functions]; got: {sc}"
    );
    assert!(
        classes.is_empty(),
        "classes must be empty for fields=[functions]; got: {sc}"
    );
    assert!(
        imports.is_empty(),
        "imports must be empty for fields=[functions]; got: {sc}"
    );
}

#[tokio::test]
async fn test_fields_classes_only_structured() {
    use std::io::Write as _;
    use tempfile::NamedTempFile;

    // Arrange: temp Rust file with functions, a class, and an import
    let cwd = std::env::current_dir().unwrap();
    let mut f = NamedTempFile::with_suffix_in(".rs", &cwd).unwrap();
    writeln!(
        f,
        "use std::collections::HashMap;\npub struct Foo {{}}\nimpl Foo {{\n    pub fn bar(&self) {{}}\n}}\npub fn baz() {{}}\n"
    )
    .unwrap();

    // Act: analyze_file with fields=[classes]
    let resp = call_tool_raw(
        "analyze_file",
        serde_json::json!({
            "path": f.path().to_str().unwrap(),
            "ast_recursion_limit": null,
            "page_size": null,
            "fields": ["classes"]
        }),
    )
    .await;

    // Assert: no error
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected success; got: {resp}"
    );

    // Inspect structuredContent.semantic
    let sc = &resp["result"]["structuredContent"];
    let functions = sc["semantic"]["functions"]
        .as_array()
        .expect("functions must be array");
    let classes = sc["semantic"]["classes"]
        .as_array()
        .expect("classes must be array");
    let imports = sc["semantic"]["imports"]
        .as_array()
        .expect("imports must be array");

    assert!(
        functions.is_empty(),
        "functions must be empty for fields=[classes]; got: {sc}"
    );
    assert!(
        !classes.is_empty(),
        "classes must be non-empty for fields=[classes]; got: {sc}"
    );
    assert!(
        imports.is_empty(),
        "imports must be empty for fields=[classes]; got: {sc}"
    );
}

#[tokio::test]
async fn test_fields_imports_only_structured() {
    use std::io::Write as _;
    use tempfile::NamedTempFile;

    // Arrange: temp Rust file with functions, a class, and an import
    let cwd = std::env::current_dir().unwrap();
    let mut f = NamedTempFile::with_suffix_in(".rs", &cwd).unwrap();
    writeln!(
        f,
        "use std::collections::HashMap;\npub struct Foo {{}}\nimpl Foo {{\n    pub fn bar(&self) {{}}\n}}\npub fn baz() {{}}\n"
    )
    .unwrap();

    // Act: analyze_file with fields=[imports]
    let resp = call_tool_raw(
        "analyze_file",
        serde_json::json!({
            "path": f.path().to_str().unwrap(),
            "ast_recursion_limit": null,
            "page_size": null,
            "fields": ["imports"]
        }),
    )
    .await;

    // Assert: no error
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected success; got: {resp}"
    );

    // Inspect structuredContent.semantic
    let sc = &resp["result"]["structuredContent"];
    let functions = sc["semantic"]["functions"]
        .as_array()
        .expect("functions must be array");
    let classes = sc["semantic"]["classes"]
        .as_array()
        .expect("classes must be array");
    let imports = sc["semantic"]["imports"]
        .as_array()
        .expect("imports must be array");

    assert!(
        functions.is_empty(),
        "functions must be empty for fields=[imports]; got: {sc}"
    );
    assert!(
        classes.is_empty(),
        "classes must be empty for fields=[imports]; got: {sc}"
    );
    assert!(
        !imports.is_empty(),
        "imports must be non-empty for fields=[imports]; got: {sc}"
    );
}

#[tokio::test]
async fn test_fields_none_structured_full() {
    use std::io::Write as _;
    use tempfile::NamedTempFile;

    // Arrange: temp Rust file with functions, a class, and an import
    let cwd = std::env::current_dir().unwrap();
    let mut f = NamedTempFile::with_suffix_in(".rs", &cwd).unwrap();
    writeln!(
        f,
        "use std::collections::HashMap;\npub struct Foo {{}}\nimpl Foo {{\n    pub fn bar(&self) {{}}\n}}\npub fn baz() {{}}\n"
    )
    .unwrap();

    // Act: analyze_file with fields=None (no projection)
    let resp = call_tool_raw(
        "analyze_file",
        serde_json::json!({
            "path": f.path().to_str().unwrap(),
            "ast_recursion_limit": null,
            "page_size": null
        }),
    )
    .await;

    // Assert: no error
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(false),
        "expected success; got: {resp}"
    );

    // Inspect structuredContent.semantic -- all sections must be present (regression)
    let sc = &resp["result"]["structuredContent"];
    let functions = sc["semantic"]["functions"]
        .as_array()
        .expect("functions must be array");
    let classes = sc["semantic"]["classes"]
        .as_array()
        .expect("classes must be array");
    let imports = sc["semantic"]["imports"]
        .as_array()
        .expect("imports must be array");

    assert!(
        !functions.is_empty(),
        "functions must be non-empty when fields=None; got: {sc}"
    );
    assert!(
        !classes.is_empty(),
        "classes must be non-empty when fields=None; got: {sc}"
    );
    assert!(
        !imports.is_empty(),
        "imports must be non-empty when fields=None; got: {sc}"
    );
}

#[tokio::test]
async fn test_analyze_file_unsupported_extension() {
    use std::io::Write as _;
    use tempfile::NamedTempFile;

    // Arrange: .txt file inside CWD so validate_path accepts it
    let cwd = std::env::current_dir().unwrap();
    let mut f = NamedTempFile::with_suffix_in(".txt", &cwd).expect("should create temp file");
    writeln!(f, "hello world").expect("should write");
    writeln!(f, "second line").expect("should write");

    let resp = call_tool_raw(
        "analyze_file",
        serde_json::json!({ "path": f.path().to_str().unwrap() }),
    )
    .await;

    // Success, not INVALID_PARAMS
    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(false),
        "analyze_file on unsupported extension must succeed; got: {resp}"
    );

    // Correct line count
    let sc = &resp["result"]["structuredContent"];
    let line_count = sc["line_count"]
        .as_u64()
        .expect("line_count must be present");
    assert_eq!(line_count, 2, "line_count must be 2; got: {resp}");

    // Semantic fields empty
    assert!(
        sc["semantic"]["functions"]
            .as_array()
            .expect("functions must be array")
            .is_empty(),
        "functions must be empty for unsupported extension"
    );
    assert!(
        sc["semantic"]["classes"]
            .as_array()
            .expect("classes must be array")
            .is_empty(),
        "classes must be empty for unsupported extension"
    );
    assert!(
        sc["semantic"]["imports"]
            .as_array()
            .expect("imports must be array")
            .is_empty(),
        "imports must be empty for unsupported extension"
    );

    // Formatted text includes unsupported-extension note
    let text = resp["result"]["content"][0]["text"].as_str().unwrap_or("");
    assert!(
        text.to_lowercase().contains("unsupported"),
        "formatted output must include unsupported-extension note; got: {text}"
    );
}

#[tokio::test]
async fn test_analyze_module_unsupported_fallback() {
    use std::io::Write as _;
    use tempfile::NamedTempFile;

    // Happy path: analyze_module on unsupported extension returns success
    // with empty functions and imports lists.
    let cwd = std::env::current_dir().unwrap();
    let mut f = NamedTempFile::with_suffix_in(".txt", &cwd).expect("should create temp file");
    writeln!(f, "some content").expect("should write");

    let resp = call_tool_raw(
        "analyze_module",
        serde_json::json!({ "path": f.path().to_str().unwrap() }),
    )
    .await;

    assert!(
        !resp["result"]["isError"].as_bool().unwrap_or(false),
        "analyze_module on unsupported extension must succeed; got: {resp}"
    );

    let sc = &resp["result"]["structuredContent"];

    // Correct line count
    let line_count = sc["line_count"]
        .as_u64()
        .expect("line_count must be present");
    assert_eq!(line_count, 1, "line_count must be 1; got: {resp}");

    // Function and import lists empty
    assert!(
        sc["functions"]
            .as_array()
            .expect("functions must be array")
            .is_empty(),
        "functions must be empty for unsupported extension"
    );
    assert!(
        sc["imports"]
            .as_array()
            .expect("imports must be array")
            .is_empty(),
        "imports must be empty for unsupported extension"
    );
}