leindex 1.7.1

LeIndex MCP and semantic code search engine for AI tools and large codebases
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
// MCP Stdio End-to-End Integration Tests
//
// Tests the full JSON-RPC dispatch stack as used by the stdio transport:
//   - JSON serialization/deserialization correctness
//   - Protocol method routing (initialize, tools/list, tools/call, notifications)
//   - All 16 tool handlers registered and named correctly
//   - Error responses carry proper structure
//   - No double-newline in serialized responses (the transport bug from Task A.1)

#![cfg(feature = "cli")]

use leindex::cli::mcp::handlers::{
    ContextHandler, DeepAnalyzeHandler, DiagnosticsHandler, EditApplyHandler, EditPreviewHandler,
    FileSummaryHandler, GitStatusHandler, GrepSymbolsHandler, ImpactAnalysisHandler, IndexHandler,
    PhaseAnalysisAliasHandler, PhaseAnalysisHandler, ProjectMapHandler, ReadFileHandler,
    ReadSymbolHandler, RenameSymbolHandler, SearchHandler, SymbolLookupHandler, TextSearchHandler,
    ToolHandler, WriteHandler,
};
use leindex::cli::mcp::protocol::{JsonRpcRequest, JsonRpcResponse};
use leindex::cli::mcp::server::{handle_tool_call, list_tools_json};
use std::sync::Arc;
use tempfile::TempDir;

// ============================================================================
// Test helpers
// ============================================================================

/// Build the full set of 16 tool handlers (mirrors cli.rs and server.rs setup).
fn all_handlers() -> Vec<ToolHandler> {
    vec![
        ToolHandler::DeepAnalyze(DeepAnalyzeHandler),
        ToolHandler::Diagnostics(DiagnosticsHandler),
        ToolHandler::Index(IndexHandler),
        ToolHandler::Context(ContextHandler),
        ToolHandler::Search(SearchHandler),
        ToolHandler::PhaseAnalysis(PhaseAnalysisHandler),
        ToolHandler::PhaseAnalysisAlias(PhaseAnalysisAliasHandler),
        // Phase C: Tool Supremacy
        ToolHandler::FileSummary(FileSummaryHandler),
        ToolHandler::SymbolLookup(SymbolLookupHandler),
        ToolHandler::ProjectMap(ProjectMapHandler),
        ToolHandler::GrepSymbols(GrepSymbolsHandler),
        ToolHandler::ReadSymbol(ReadSymbolHandler),
        ToolHandler::Write(WriteHandler),
        // Phase D: Context-Aware Editing
        ToolHandler::EditPreview(EditPreviewHandler),
        ToolHandler::EditApply(EditApplyHandler),
        ToolHandler::RenameSymbol(RenameSymbolHandler),
        ToolHandler::ImpactAnalysis(ImpactAnalysisHandler),
        // Phase E: Precision Tooling
        ToolHandler::TextSearch(TextSearchHandler),
        ToolHandler::ReadFile(ReadFileHandler),
        ToolHandler::GitStatus(GitStatusHandler),
    ]
}

/// Create a minimal LeIndex state backed by a temp directory (not indexed).
fn make_state(tmp: &TempDir) -> Arc<leindex::cli::ProjectRegistry> {
    let leindex =
        leindex::cli::leindex::LeIndex::new(tmp.path()).expect("Failed to create LeIndex for test");
    Arc::new(leindex::cli::ProjectRegistry::with_initial_project(
        5, leindex,
    ))
}

/// Parse a JSON-RPC request from a JSON string (simulates stdin line).
fn parse_request(json: &str) -> JsonRpcRequest {
    serde_json::from_str(json).expect("Failed to parse JsonRpcRequest")
}

/// Serialize a response and verify it contains no double-newline (transport bug guard).
fn assert_no_double_newline(resp: &JsonRpcResponse) {
    let serialized = serde_json::to_string(resp).expect("Failed to serialize response");
    assert!(
        !serialized.contains("\n\n"),
        "Response contains double-newline (MCP transport bug): {:?}",
        &serialized[..serialized.len().min(200)]
    );
    // Also verify writeln! would produce exactly one newline (not two)
    let with_writeln = format!("{}\n", serialized);
    assert_eq!(
        with_writeln.matches('\n').count(),
        1,
        "writeln! with {{}} resp should produce exactly one trailing newline"
    );
}

// ============================================================================
// Protocol format tests
// ============================================================================

#[test]
fn test_initialize_request_parses_correctly() {
    let json = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{}}}"#;
    let req = parse_request(json);
    assert_eq!(req.method, "initialize");
    assert_eq!(req.id, Some(serde_json::json!(1)));
}

#[test]
fn test_initialize_response_format() {
    // The initialize response must contain protocolVersion, capabilities, and serverInfo.
    let resp = JsonRpcResponse::success(
        serde_json::json!(1),
        serde_json::json!({
            "protocolVersion": "2024-11-05",
            "capabilities": { "tools": {} },
            "serverInfo": { "name": "leindex", "version": "0.1.0" }
        }),
    );

    let serialized = serde_json::to_string(&resp).unwrap();
    let parsed: serde_json::Value = serde_json::from_str(&serialized).unwrap();

    assert_eq!(parsed["jsonrpc"], "2.0");
    assert_eq!(parsed["id"], 1);
    assert!(parsed["result"]["protocolVersion"].is_string());
    assert!(parsed["result"]["capabilities"].is_object());
    assert!(parsed["result"]["serverInfo"]["name"].is_string());

    assert_no_double_newline(&resp);
}

#[test]
fn test_notification_has_no_id_field() {
    // MCP notifications omit the "id" field.
    let json = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
    let req = parse_request(json);
    assert_eq!(req.method, "notifications/initialized");
    assert!(req.id.is_none(), "Notification should not have an id");
}

#[test]
fn test_no_double_newline_in_error_response() {
    let err =
        leindex::cli::mcp::protocol::JsonRpcError::method_not_found("unknown_method".to_string());
    let resp = JsonRpcResponse::error(serde_json::json!(42), err);
    assert_no_double_newline(&resp);
}

#[test]
fn test_no_double_newline_in_success_response() {
    let resp = JsonRpcResponse::success(serde_json::json!(99), serde_json::json!({ "tools": [] }));
    assert_no_double_newline(&resp);
}

// ============================================================================
// tools/list — all 16 tools registered
// ============================================================================

#[test]
fn test_tools_list_returns_20_tools() {
    let handlers = all_handlers();
    let result = list_tools_json(&handlers);
    let tools = result["tools"].as_array().expect("tools must be an array");
    assert_eq!(
        tools.len(),
        20,
        "Expected exactly 20 registered tools, got {}",
        tools.len()
    );
}

#[test]
fn test_tools_list_all_expected_names_present() {
    let handlers = all_handlers();
    let result = list_tools_json(&handlers);
    let tools = result["tools"].as_array().unwrap();

    let names: Vec<&str> = tools
        .iter()
        .map(|t| t["name"].as_str().expect("tool name must be a string"))
        .collect();

    let expected_names = [
        "leindex.index",
        "leindex.search",
        "leindex.deep-analyze",
        "leindex.context",
        "leindex.diagnostics",
        "leindex.phase-analysis",
        "phase_analysis",
        // Phase C
        "leindex.file-summary",
        "leindex.symbol-lookup",
        "leindex.project-map",
        "leindex.grep-symbols",
        "leindex.read-symbol",
        "leindex.write",
        // Phase D
        "leindex.edit-preview",
        "leindex.edit-apply",
        "leindex.rename-symbol",
        "leindex.impact-analysis",
        // Phase E
        "leindex.text-search",
        "leindex.read-file",
        "leindex.git-status",
    ];

    for expected in &expected_names {
        assert!(
            names.contains(expected),
            "Missing tool '{}' from tools/list. Got: {:?}",
            expected,
            names
        );
    }
}

#[test]
fn test_tools_list_every_tool_has_description_and_schema() {
    let handlers = all_handlers();
    let result = list_tools_json(&handlers);
    let tools = result["tools"].as_array().unwrap();

    for tool in tools {
        let name = tool["name"].as_str().unwrap_or("<unnamed>");
        let desc = tool["description"].as_str().unwrap_or("");
        assert!(
            !desc.is_empty(),
            "Tool '{}' has empty or missing description",
            name
        );
        assert!(
            desc.len() <= 300,
            "Tool '{}' description exceeds 300 chars ({} chars): {}",
            name,
            desc.len(),
            desc
        );
        assert!(
            tool["inputSchema"].is_object(),
            "Tool '{}' has missing or non-object inputSchema",
            name
        );
    }
}

// ============================================================================
// tools/call — handler dispatch and structured error responses
// ============================================================================

/// Build a tools/call request JSON-RPC message.
fn make_tool_call(id: i64, tool_name: &str, args: serde_json::Value) -> JsonRpcRequest {
    parse_request(&format!(
        r#"{{"jsonrpc":"2.0","id":{},"method":"tools/call","params":{{"name":"{}","arguments":{}}}}}"#,
        id, tool_name, args
    ))
}

#[tokio::test]
async fn test_tools_call_unknown_tool_returns_error() {
    let tmp = TempDir::new().unwrap();
    let state = make_state(&tmp);
    let handlers = all_handlers();

    let req = make_tool_call(1, "leindex_nonexistent_tool", serde_json::json!({}));
    let result = handle_tool_call(&state, &handlers, &req).await;

    // Should be an Err (method not found) or an Ok with isError:true
    // The server wraps errors as isError:true for MCP compliance
    // handle_tool_call returns Err for method-not-found
    assert!(result.is_err(), "Expected error for unknown tool");
}

#[tokio::test]
async fn test_tools_call_file_summary_unindexed_returns_structured_response() {
    let tmp = TempDir::new().unwrap();
    let state = make_state(&tmp);
    let handlers = all_handlers();

    let req = make_tool_call(
        2,
        "leindex.file-summary",
        serde_json::json!({ "file_path": "/nonexistent/file.rs" }),
    );

    // handle_tool_call always returns Ok (error is wrapped as isError:true)
    let result = handle_tool_call(&state, &handlers, &req).await;
    assert!(
        result.is_ok(),
        "Tool call should return Ok with structured error response"
    );

    let response = result.unwrap();
    // MCP wraps errors as isError:true with content array
    assert!(
        response.get("isError").is_some() || response.get("content").is_some(),
        "Response must have 'isError' or 'content' field. Got: {:?}",
        response
    );
}

#[tokio::test]
async fn test_tools_call_symbol_lookup_unindexed_returns_structured_response() {
    let tmp = TempDir::new().unwrap();
    let state = make_state(&tmp);
    let handlers = all_handlers();

    let req = make_tool_call(
        3,
        "leindex.symbol-lookup",
        serde_json::json!({ "symbol": "some_function" }),
    );

    let result = handle_tool_call(&state, &handlers, &req).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // Even on error, MCP response must have content or isError
    assert!(
        response.get("isError").is_some() || response.get("content").is_some(),
        "Response must have 'isError' or 'content' field"
    );
}

#[tokio::test]
async fn test_tools_call_project_map_unindexed_returns_structured_response() {
    let tmp = TempDir::new().unwrap();
    let state = make_state(&tmp);
    let handlers = all_handlers();

    let req = make_tool_call(4, "leindex.project-map", serde_json::json!({}));

    let result = handle_tool_call(&state, &handlers, &req).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    assert!(
        response.get("isError").is_some() || response.get("content").is_some(),
        "Response must have 'isError' or 'content' field"
    );
}

#[tokio::test]
async fn test_tools_call_edit_preview_unindexed_returns_structured_response() {
    let tmp = TempDir::new().unwrap();
    let state = make_state(&tmp);
    let handlers = all_handlers();

    let req = make_tool_call(
        5,
        "leindex.edit-preview",
        serde_json::json!({
            "file_path": "/nonexistent/file.rs",
            "changes": [{"type": "replace_text", "old_text": "foo", "new_text": "bar"}]
        }),
    );

    let result = handle_tool_call(&state, &handlers, &req).await;
    assert!(result.is_ok());
    let response = result.unwrap();
    assert!(response.get("isError").is_some() || response.get("content").is_some());
}

#[tokio::test]
async fn test_tools_call_diagnostics_returns_ok() {
    // diagnostics does NOT require an indexed project — always returns system info
    let tmp = TempDir::new().unwrap();
    let state = make_state(&tmp);
    let handlers = all_handlers();

    let req = make_tool_call(6, "leindex.diagnostics", serde_json::json!({}));
    let result = handle_tool_call(&state, &handlers, &req).await;
    assert!(result.is_ok());

    let response = result.unwrap();
    // diagnostics should succeed (isError: false)
    assert_eq!(
        response.get("isError").and_then(|v| v.as_bool()),
        Some(false),
        "Diagnostics should succeed: {:?}",
        response
    );
}

// ============================================================================
// Notification handling — no response for notifications
// ============================================================================

#[test]
fn test_notification_request_has_no_id() {
    // MCP notifications must not generate a response — verified by checking no id
    let json = r#"{"jsonrpc":"2.0","method":"notifications/initialized","params":{}}"#;
    let req: JsonRpcRequest = serde_json::from_str(json).unwrap();
    assert!(
        req.id.is_none(),
        "Notification must have no id (so callers know not to send a response)"
    );
}

#[test]
fn test_jsonrpc_response_serialization_is_single_line() {
    // Verify that serde_json::to_string produces no embedded newlines
    // (writeln! adds exactly one, producing single-line JSON per MCP spec)
    let resp = JsonRpcResponse::success(
        serde_json::json!(1),
        serde_json::json!({"tools": [{"name": "LeIndex [Index]"}]}),
    );
    let s = serde_json::to_string(&resp).unwrap();
    assert!(
        !s.contains('\n'),
        "serde_json::to_string must not produce embedded newlines. Got: {}",
        s
    );
}