trusty-search 0.26.0

Machine-wide hybrid code search service: BM25 + vector + KG, zero cold-start, MCP server
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
553
554
555
556
557
558
559
560
561
//! Core dispatch tests for the MCP tool dispatcher.
//!
//! Why: validates the JSON-RPC protocol layer (version check, notification
//! suppression, `tools/call` vs bare-method dispatch, error code mapping)
//! and the cross-cutting tool characteristics (all tools appear in
//! `tools/list`, schema requires the right fields, `grep`/`search_all`
//! param validation).
//! What: unit tests that either do not need a live daemon (mock base URL
//! `http://127.0.0.1:1` that cannot connect) or spin up a tiny axum mock
//! daemon on a loopback port.
//! Test: this file.

use serde_json::Value;

use super::{error_codes, McpServer, Request};

pub(super) fn req(method: &str, params: Value) -> Request {
    Request {
        jsonrpc: Some("2.0".into()),
        id: Some(Value::from(1u64)),
        method: method.into(),
        params: Some(params),
    }
}

#[tokio::test]
async fn rejects_wrong_jsonrpc_version() {
    let server = McpServer::new("http://127.0.0.1:1");
    let r = Request {
        jsonrpc: Some("1.0".into()),
        id: Some(Value::from(7u64)),
        method: "search_health".into(),
        params: None,
    };
    let resp = server.dispatch(r).await;
    let err = resp.error.expect("expected error");
    assert_eq!(err.code, error_codes::INVALID_REQUEST);
    assert_eq!(resp.id, Some(Value::from(7u64)));
}

#[tokio::test]
async fn unknown_tool_returns_method_not_found() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server.dispatch(req("not_a_tool", Value::Null)).await;
    let err = resp.error.expect("expected error");
    assert_eq!(err.code, error_codes::METHOD_NOT_FOUND);
}

#[tokio::test]
async fn missing_params_returns_invalid_params() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server
        .dispatch(req("index_file", serde_json::json!({})))
        .await;
    let err = resp.error.expect("expected error");
    assert_eq!(err.code, error_codes::INVALID_PARAMS);
}

#[tokio::test]
async fn tools_list_returns_all_tools() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server.dispatch(req("tools/list", Value::Null)).await;
    let result = resp.result.expect("expected result");
    let tools = result
        .get("tools")
        .and_then(Value::as_array)
        .expect("array");
    // Issue #36 requires the 6 core MCP tools to be present; we ship
    // additional tools beyond that minimum.
    assert!(
        tools.len() >= 6,
        "expected at least 6 tools, got {}",
        tools.len()
    );
    let names: Vec<&str> = tools
        .iter()
        .filter_map(|t| t.get("name").and_then(Value::as_str))
        .collect();
    for required in [
        "search",
        "index_file",
        "remove_file",
        "list_indexes",
        "create_index",
        "search_health",
    ] {
        assert!(
            names.contains(&required),
            "missing required tool: {required}"
        );
    }
}

/// Issue #36 — verify the `initialize` handshake returns the spec-shaped
/// payload Claude Code expects on startup.
#[tokio::test]
async fn test_initialize_response() {
    let server = McpServer::new("http://127.0.0.1:1");
    let r = Request {
        jsonrpc: Some("2.0".into()),
        id: Some(Value::from(1u64)),
        method: "initialize".into(),
        params: Some(serde_json::json!({
            "protocolVersion": "2024-11-05",
            "capabilities": {},
            "clientInfo": { "name": "test", "version": "0.0.0" }
        })),
    };
    let resp = server.dispatch(r).await;
    assert!(resp.error.is_none(), "initialize must not error");
    let result = resp.result.expect("expected result");
    assert_eq!(result["protocolVersion"], "2024-11-05");
    assert!(result["capabilities"].get("tools").is_some());
    assert_eq!(result["serverInfo"]["name"], "trusty-search");
    assert!(result["serverInfo"]["version"].is_string());
}

/// Issue #36 — `tools/list` must surface every spec-required tool so
/// MCP clients can render the full manifest.
#[tokio::test]
async fn test_tools_list_response() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server.dispatch(req("tools/list", Value::Null)).await;
    let result = resp.result.expect("expected result");
    let tools = result
        .get("tools")
        .and_then(Value::as_array)
        .expect("array");
    let names: Vec<&str> = tools
        .iter()
        .filter_map(|t| t.get("name").and_then(Value::as_str))
        .collect();
    for required in [
        "search",
        "index_file",
        "remove_file",
        "list_indexes",
        "create_index",
        "search_health",
    ] {
        assert!(
            names.contains(&required),
            "tools/list missing '{required}' (got {names:?})"
        );
    }
    // Each tool must carry an inputSchema so clients can validate args.
    for t in tools {
        assert!(t.get("name").is_some());
        assert!(t.get("inputSchema").is_some());
    }
}

/// Issue #36 — JSON-RPC method-not-found surfaces as -32601.
#[tokio::test]
async fn test_unknown_method_returns_error() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server
        .dispatch(req("definitely_not_a_method", Value::Null))
        .await;
    let err = resp.error.expect("expected error");
    assert_eq!(err.code, error_codes::METHOD_NOT_FOUND);
}

/// `notifications/initialized` is a JSON-RPC notification — the server
/// must NOT emit a response, signalled by `Response::suppress = true`.
#[tokio::test]
async fn notification_initialized_is_suppressed() {
    let server = McpServer::new("http://127.0.0.1:1");
    let r = Request {
        jsonrpc: Some("2.0".into()),
        id: None, // notifications carry no id
        method: "notifications/initialized".into(),
        params: None,
    };
    let resp = server.dispatch(r).await;
    assert!(resp.suppress, "notifications must be suppressed");
}

/// Parity gate: every HTTP endpoint reachable via REST must also be callable
/// as an MCP tool. This guards the "MCP and HTTP are functionally equivalent"
/// invariant — if a new HTTP route lands without a matching tool, this fails.
#[tokio::test]
async fn test_tools_list_complete() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server.dispatch(req("tools/list", Value::Null)).await;
    let result = resp.result.expect("expected result");
    let tools = result
        .get("tools")
        .and_then(Value::as_array)
        .expect("array");
    let names: Vec<&str> = tools
        .iter()
        .filter_map(|t| t.get("name").and_then(Value::as_str))
        .collect();
    for required in [
        "search",
        "index_file",
        "remove_file",
        "list_indexes",
        "create_index",
        "search_health",
        "delete_index",
        "reindex",
        "index_status",
        "list_chunks",
        "chat",
        "search_all",
    ] {
        assert!(
            names.contains(&required),
            "tools/list missing '{required}' (got {names:?})"
        );
    }
}

/// Issue #10 — `search_all` requires the `query` arg and rejects missing it
/// before any HTTP round-trip.
#[tokio::test]
async fn search_all_missing_query_returns_invalid_params() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server
        .dispatch(req("search_all", serde_json::json!({})))
        .await;
    let err = resp.error.expect("expected error");
    assert_eq!(err.code, error_codes::INVALID_PARAMS);
}

#[tokio::test]
async fn tools_call_without_name_returns_invalid_params() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server
        .dispatch(req("tools/call", serde_json::json!({})))
        .await;
    let err = resp.error.expect("expected error");
    assert_eq!(err.code, error_codes::INVALID_PARAMS);
}

/// `grep` is listed and missing-pattern fast-fails before any HTTP hop.
#[tokio::test]
async fn grep_missing_pattern_returns_invalid_params() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server.dispatch(req("grep", serde_json::json!({}))).await;
    let err = resp.error.expect("expected error");
    assert_eq!(err.code, error_codes::INVALID_PARAMS);
}

/// Issue #447 — `max_count` is forwarded as `max_results` to the daemon.
///
/// Why: when the MCP client passes `max_count` (ripgrep's `--max-count`
/// flag name) the dispatcher must translate it to `max_results` before
/// POSTing to the daemon. Without the alias the parameter was silently
/// dropped and the daemon applied its default cap of 100 regardless.
/// What: asserts that a `grep` call with `max_count=5` (and no
/// `max_results`) forwards `max_results: 5` in the daemon request body.
/// Test: spins up a tiny mock daemon that echoes back the request body,
/// then asserts the forwarded body contains `max_results == 5`.
#[tokio::test]
async fn grep_max_count_alias_forwarded_as_max_results() {
    use axum::routing::post;
    use axum::{Json, Router};
    use std::sync::Arc;
    use tokio::sync::Mutex;

    let captured: Arc<Mutex<Option<Value>>> = Arc::new(Mutex::new(None));
    let captured_clone = Arc::clone(&captured);

    async fn grep_handler(
        axum::extract::State(captured): axum::extract::State<Arc<Mutex<Option<Value>>>>,
        Json(body): Json<Value>,
    ) -> Json<Value> {
        *captured.lock().await = Some(body);
        Json(serde_json::json!({ "matches": [], "total": 0, "truncated": false }))
    }

    let app = Router::new()
        .route("/indexes/idx/grep", post(grep_handler))
        .with_state(captured_clone);
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        let _ = axum::serve(listener, app).await;
    });

    let server = McpServer::new(format!("http://{addr}"));
    let resp = server
        .dispatch(req(
            "grep",
            serde_json::json!({
                "pattern": "fn foo",
                "index_id": "idx",
                "max_count": 5_u64,
            }),
        ))
        .await;
    assert!(resp.error.is_none(), "unexpected error: {:?}", resp.error);
    let body = captured.lock().await.clone().expect("no request captured");
    assert_eq!(
        body.get("max_results").and_then(Value::as_u64),
        Some(5),
        "max_count must be forwarded as max_results; got body: {body:?}"
    );
}

/// `grep` appears in `tools/list` with a `pattern`-required schema.
#[tokio::test]
async fn grep_listed_in_tools_with_required_pattern() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server.dispatch(req("tools/list", Value::Null)).await;
    let result = resp.result.expect("expected result");
    let tools = result
        .get("tools")
        .and_then(Value::as_array)
        .expect("array");
    let grep = tools
        .iter()
        .find(|t| t.get("name").and_then(Value::as_str) == Some("grep"))
        .expect("grep tool missing from tools/list");
    let required = grep["inputSchema"]["required"]
        .as_array()
        .expect("required array");
    assert!(
        required.iter().any(|v| v.as_str() == Some("pattern")),
        "grep schema must require 'pattern'"
    );
}

// ----------------------------------------------------------------
// Issue #138 — per-lane MCP tools: shared mock-daemon helper
// ----------------------------------------------------------------

/// Spin up a one-shot axum mock daemon on a loopback port.
///
/// Why: the per-lane tool tests in `tests_lane.rs` all need a controllable
/// daemon — this helper lets each test specify exactly what `GET
/// /indexes/:id/status` and `POST /indexes/:id/search` return, and
/// captures the inbound request bodies so tests can assert the correct
/// `SearchQuery` shape was dispatched.
/// What: returns `(base_url, captured_search_bodies, captured_search_paths)`.
/// Test: used by every test in `tests_lane.rs`.
pub(super) async fn spawn_mock_daemon(
    status_response: Value,
    search_response: Value,
) -> (
    String,
    std::sync::Arc<tokio::sync::Mutex<Vec<Value>>>,
    std::sync::Arc<tokio::sync::Mutex<Vec<String>>>,
) {
    use axum::extract::{Path, State};
    use axum::routing::{get, post};
    use axum::{Json, Router};
    use std::sync::Arc;
    use tokio::sync::Mutex;

    #[derive(Clone)]
    struct MockState {
        status_response: Value,
        search_response: Value,
        captured_bodies: Arc<Mutex<Vec<Value>>>,
        captured_paths: Arc<Mutex<Vec<String>>>,
    }

    let captured_bodies: Arc<Mutex<Vec<Value>>> = Arc::new(Mutex::new(Vec::new()));
    let captured_paths: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));
    let state = MockState {
        status_response,
        search_response,
        captured_bodies: Arc::clone(&captured_bodies),
        captured_paths: Arc::clone(&captured_paths),
    };

    async fn status_handler(Path(id): Path<String>, State(s): State<MockState>) -> Json<Value> {
        // Inject the index_id so the handler returns a payload that
        // looks like a real daemon response.
        let mut v = s.status_response.clone();
        if v.is_object() {
            v["index_id"] = Value::String(id);
        }
        Json(v)
    }

    async fn search_handler_mock(
        Path(id): Path<String>,
        State(s): State<MockState>,
        Json(body): Json<Value>,
    ) -> Json<Value> {
        s.captured_paths
            .lock()
            .await
            .push(format!("/indexes/{id}/search"));
        s.captured_bodies.lock().await.push(body);
        Json(s.search_response.clone())
    }

    let app = Router::new()
        .route("/indexes/{id}/status", get(status_handler))
        .route("/indexes/{id}/search", post(search_handler_mock))
        .with_state(state);

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        let _ = axum::serve(listener, app).await;
    });

    let base_url = format!("http://{addr}");
    (base_url, captured_bodies, captured_paths)
}

// Issue #1373 — pinned-index resolution + serve-time pin
// ----------------------------------------------------------------

/// `resolve_index_id` precedence: explicit arg wins, else pinned, else None.
///
/// Why: the whole #1373 fix hinges on this precedence — a pinned session must
/// default an omitted `index_id` to the pin, still honour an explicit id, and
/// (without a pin) fall through to `None` so behaviour is unchanged.
/// What: exercises all four combinations on the bare helper.
/// Test: this is the test.
#[test]
fn resolve_index_id_prefers_explicit_then_pinned() {
    let pinned = McpServer::new("http://127.0.0.1:1").with_pinned_index("my-project");
    // Omitted → pinned.
    assert_eq!(
        pinned.resolve_index_id(&serde_json::json!({})),
        Some("my-project".to_string())
    );
    // Explicit wins over the pin.
    assert_eq!(
        pinned.resolve_index_id(&serde_json::json!({ "index_id": "other" })),
        Some("other".to_string())
    );
    // Empty explicit id is ignored → falls back to the pin.
    assert_eq!(
        pinned.resolve_index_id(&serde_json::json!({ "index_id": "" })),
        Some("my-project".to_string())
    );

    // No pin: omitted → None (unchanged legacy behaviour).
    let unpinned = McpServer::new("http://127.0.0.1:1");
    assert_eq!(unpinned.resolve_index_id(&serde_json::json!({})), None);
    assert_eq!(
        unpinned.resolve_index_id(&serde_json::json!({ "index_id": "x" })),
        Some("x".to_string())
    );
}

/// A blank `--index ""` pin is treated as "no pin" so a degenerate flag can't
/// wedge every call onto an empty-string index.
///
/// Why: defensive — an operator (or a buggy launcher) passing `--index ""`
/// must not silently pin to `""`.
/// What: asserts `with_pinned_index("")` leaves `pinned_index` unset.
/// Test: this is the test.
#[test]
fn blank_pin_is_treated_as_no_pin() {
    let s = McpServer::new("http://127.0.0.1:1").with_pinned_index("   ");
    assert_eq!(s.resolve_index_id(&serde_json::json!({})), None);
}

/// Without a pin, `search` with no `index_id` fast-fails (unchanged).
///
/// Why: backward-compatibility — the pre-#1373 contract requires `index_id`,
/// and the fix must not relax that when no pin is configured.
/// What: dispatches `search` (no index_id, no pin) and asserts INVALID_PARAMS.
/// Test: this is the test.
#[tokio::test]
async fn search_without_pin_requires_index_id() {
    let server = McpServer::new("http://127.0.0.1:1");
    let resp = server
        .dispatch(req("search", serde_json::json!({ "query": "fn main" })))
        .await;
    let err = resp.error.expect("expected error");
    assert_eq!(err.code, error_codes::INVALID_PARAMS);
}

/// With a pin, `search` with no `index_id` targets the pinned index endpoint.
///
/// Why: the core acceptance criterion — a pinned session must resolve a bare
/// `search` to its own project index, never sweeping or guessing.
/// What: spins up the mock daemon, dispatches `search` (query only) against a
/// server pinned to `pinned-proj`, and asserts the daemon saw a POST to
/// `/indexes/pinned-proj/search`.
/// Test: this is the test.
#[tokio::test]
async fn pinned_search_defaults_index_id_to_pin() {
    let (base_url, _bodies, paths) = spawn_mock_daemon(
        serde_json::json!({ "search_capabilities": ["vector", "kg"] }),
        serde_json::json!({ "results": [], "intent": "Definition", "latency_ms": 1 }),
    )
    .await;
    let server =
        McpServer::with_client(base_url, reqwest::Client::new()).with_pinned_index("pinned-proj");

    let resp = server
        .dispatch(req("search", serde_json::json!({ "query": "fn main" })))
        .await;
    assert!(
        resp.error.is_none(),
        "pinned search should succeed: {resp:?}"
    );

    let seen = paths.lock().await;
    assert_eq!(seen.len(), 1, "exactly one daemon search call: {seen:?}");
    assert_eq!(seen[0], "/indexes/pinned-proj/search");
}

/// With a pin, `grep` with no `index_id` scopes to the pinned index endpoint
/// instead of the global fan-out `/grep`.
///
/// Why: #1373 requires fan-out tools to scope to the pin so a project session
/// never sweeps every registered index.
/// What: mock daemon captures the grep path; asserts the pinned per-index
/// endpoint was hit.
/// Test: this is the test.
#[tokio::test]
async fn pinned_grep_scopes_to_pinned_index() {
    use axum::extract::{Path, State};
    use axum::routing::post;
    use axum::{Json, Router};
    use std::sync::Arc;
    use tokio::sync::Mutex;

    let captured: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(Vec::new()));

    async fn per_index_grep(
        Path(id): Path<String>,
        State(c): State<Arc<Mutex<Vec<String>>>>,
        Json(_body): Json<Value>,
    ) -> Json<Value> {
        c.lock().await.push(format!("/indexes/{id}/grep"));
        Json(serde_json::json!({ "matches": [] }))
    }
    async fn global_grep(
        State(c): State<Arc<Mutex<Vec<String>>>>,
        Json(_body): Json<Value>,
    ) -> Json<Value> {
        c.lock().await.push("/grep".to_string());
        Json(serde_json::json!({ "matches": [] }))
    }

    let app = Router::new()
        .route("/indexes/{id}/grep", post(per_index_grep))
        .route("/grep", post(global_grep))
        .with_state(Arc::clone(&captured));
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        let _ = axum::serve(listener, app).await;
    });
    let base_url = format!("http://{addr}");

    let server =
        McpServer::with_client(base_url, reqwest::Client::new()).with_pinned_index("pinned-proj");
    let resp = server
        .dispatch(req("grep", serde_json::json!({ "pattern": "fn foo" })))
        .await;
    assert!(resp.error.is_none(), "pinned grep should succeed: {resp:?}");

    let seen = captured.lock().await;
    assert_eq!(seen.as_slice(), &["/indexes/pinned-proj/grep".to_string()]);
}