trusty-review 0.3.4

Fast local PR-review service for trusty-tools — orchestrates LLM-backed code review
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
//! JSON-RPC 2.0 / MCP stdio service for trusty-review.
//!
//! Why: Claude Code speaks MCP over stdio; this module lets operators wire
//! trusty-review into Claude Code via `.mcp.json` without running the HTTP
//! daemon.  The stdio path reuses the same `AppState` and pipeline as the HTTP
//! daemon, so behaviour is identical.
//!
//! What: `run(state)` builds the shared state once and calls
//! `trusty_common::mcp::run_stdio_loop`, which reads JSON-RPC requests
//! line-by-line from stdin and writes responses to stdout.  `dispatch` handles
//! `initialize`, `notifications/initialized`, `tools/list`, `tools/call`, and
//! bare method names.  All tracing goes to stderr; stdout is the transport.
//!
//! Test: `dispatch_initialize_returns_server_info`,
//! `dispatch_tools_list_returns_three_tools`,
//! `dispatch_unknown_tool_returns_method_not_found`,
//! `dispatch_notification_is_suppressed`.

pub mod tools;

use std::sync::Arc;

use anyhow::Result;
use serde_json::Value;
use tracing::{debug, info, warn};

use trusty_common::mcp::{Request, Response, error_codes, initialize_response, run_stdio_loop};

use crate::config::ReviewConfig;
use crate::integrations::{analyze_client::HttpAnalyzeClient, search_client::HttpSearchClient};
use crate::llm::build_provider;
use crate::mcp::tools::{ToolError, call_tool, tool_descriptors, wrap_tool_error};
use crate::service::AppState;

// Re-export the reusable surface an embedding host (e.g. trusty-analyze, #630)
// needs to delegate into the trusty-review pipeline without depending on the
// binary's serve assembly: the tool descriptors, the `tools/call` router, the
// router's error type, and the shared `AppState`.
pub use crate::mcp::tools::{ToolError as ReviewToolError, call_tool as call_review_tool};
pub use crate::service::AppState as ReviewAppState;

// ─── Entry point ─────────────────────────────────────────────────────────────

/// Start the MCP stdio JSON-RPC loop using the provided `AppState`.
///
/// Why: the `serve --stdio` CLI path needs a single async entry-point that
/// accepts requests on stdin and writes responses to stdout until EOF.
/// What: wraps `AppState` in an `Arc` (so it can be shared across the async
/// closure without lifetime issues), then calls `run_stdio_loop` from
/// `trusty-common` which owns the parse/dispatch/flush cycle.
/// Test: `run` is side-effectful (reads stdin); coverage comes from unit tests
/// on `dispatch` with synthetic requests.
pub async fn run(state: AppState) -> Result<()> {
    let state = Arc::new(state);
    run_stdio_loop(move |req| {
        let state = Arc::clone(&state);
        async move { dispatch(req, &state).await }
    })
    .await
}

/// Build a fully-wired trusty-review [`AppState`] from environment + config file.
///
/// Why: an embedding host (e.g. trusty-analyze's MCP server, #630) needs to run
/// the trusty-review pipeline without copying the binary's `serve` assembly,
/// which lives behind `crate::cli_verify` in the binary target and is therefore
/// not reachable from a library consumer. This entry point reproduces that
/// assembly using only library-public builders so the host can obtain an
/// `AppState` and delegate `tools/call` to [`tools::call_tool`].
/// What: loads [`ReviewConfig`] from env + the default XDG config file, builds
/// the reviewer LLM provider (Bedrock or OpenRouter, per config), optionally
/// builds the verifier provider (degrading to `None` on failure — embedded use
/// must not hard-fail a host daemon over a missing verifier model), builds the
/// HTTP search + analyze clients from config (the analyze client defaults to
/// `http://localhost:7879`, i.e. loopback to the hosting analyze daemon, so
/// embedded reviews get authoritative static-analysis context), and returns the
/// assembled `AppState`. No dedup store is opened — embedded callers do not post
/// comments (`allow_posting=false` in every tool handler), so cross-process
/// dedup is unnecessary.
/// Test: the build path is network/credential-bound (AWS / OpenRouter) and is
/// therefore exercised by the live smoke test rather than a unit test; the
/// dispatch/tools surface it feeds is covered by `mcp::tests` and
/// `tools::tests`.
pub async fn build_review_state() -> Result<AppState> {
    let config = ReviewConfig::load(None);

    let reviewer_model = config.role_models.reviewer.model.clone();
    let default_provider = config.role_models.reviewer.provider.clone();
    let llm = build_provider(
        &reviewer_model,
        &default_provider,
        &config.openrouter_api_key,
    )
    .await
    .map_err(|e| anyhow::anyhow!("failed to build reviewer LLM provider: {e}"))?;

    // Verifier is optional in the embedded path: degrade to no-verification
    // rather than abort the host daemon if the verifier model cannot be built.
    let verifier = if config.verification.enabled {
        let role = &config.role_models.verifier;
        match build_provider(&role.model, &role.provider, &config.openrouter_api_key).await {
            Ok(p) => Some(p),
            Err(e) => {
                warn!("failed to build verifier provider (continuing without verification): {e}");
                None
            }
        }
    } else {
        None
    };

    let search = HttpSearchClient::from_config(&config);
    let analyze = HttpAnalyzeClient::from_config(&config);

    info!(
        reviewer_model = %config.role_models.reviewer.model,
        analyzer_url = %config.analyzer_url,
        search_url = %config.search_url,
        "trusty-review embedded AppState built"
    );

    Ok(AppState::with_verifier_and_dedup(
        config,
        llm,
        verifier,
        Arc::new(search),
        Some(Arc::new(analyze)),
        None,
    ))
}

// ─── Dispatcher ──────────────────────────────────────────────────────────────

/// Translate a JSON-RPC 2.0 request into a trusty-review MCP response.
///
/// Why: decouples the dispatch logic from the I/O loop so it can be unit-tested
/// with synthetic `Request` values.
/// What: handles `initialize`, `notifications/initialized`, `tools/list`,
/// `tools/call`, and bare tool names.  Always returns a `Response`; never
/// panics.
/// Test: `dispatch_initialize_returns_server_info`,
/// `dispatch_tools_list_returns_three_tools`,
/// `dispatch_unknown_tool_returns_method_not_found`.
pub async fn dispatch(req: Request, state: &AppState) -> Response {
    let is_notification = req.id.is_none();
    let id = req.id.clone();

    if req.jsonrpc.as_deref() != Some("2.0") {
        if is_notification {
            return Response::suppressed();
        }
        return Response::err(id, error_codes::INVALID_REQUEST, "jsonrpc must be \"2.0\"");
    }

    match req.method.as_str() {
        "initialize" => {
            return Response::ok(
                id,
                initialize_response("trusty-review", env!("CARGO_PKG_VERSION"), None),
            );
        }
        "notifications/initialized" | "initialized" => {
            return Response::suppressed();
        }
        _ => {}
    }

    let params = req.params.clone().unwrap_or(Value::Null);

    // Route `tools/list` and `tools/call`; also accept bare method names for
    // ergonomics (e.g. `review_health` directly).
    let (tool, arguments, via_tools_call) = match req.method.as_str() {
        "tools/call" => {
            let name = params
                .get("name")
                .and_then(Value::as_str)
                .map(str::to_owned);
            let args = params
                .get("arguments")
                .cloned()
                .unwrap_or(Value::Object(Default::default()));
            match name {
                Some(n) => (n, args, true),
                None => {
                    return Response::err(
                        id,
                        error_codes::INVALID_PARAMS,
                        "tools/call requires a 'name' field",
                    );
                }
            }
        }
        "tools/list" => {
            return Response::ok(id, serde_json::json!({ "tools": tool_descriptors() }));
        }
        other => (other.to_string(), params, false),
    };

    debug!(tool, via_tools_call, "mcp dispatch");
    let outcome = call_tool(&tool, &arguments, state).await;

    if via_tools_call {
        // Per MCP spec: tool execution failures are `{content, isError:true}`
        // rather than JSON-RPC errors.
        match outcome {
            Ok(value) => Response::ok(id, value),
            Err(ToolError::UnknownTool) => Response::err(
                id,
                error_codes::METHOD_NOT_FOUND,
                format!("unknown tool: {tool}"),
            ),
            Err(ToolError::InvalidParams(msg)) => Response::ok(id, wrap_tool_error(&msg)),
        }
    } else {
        // Bare-method form: return JSON-RPC errors for protocol-level failures.
        match outcome {
            Ok(value) => Response::ok(id, value),
            Err(ToolError::UnknownTool) => Response::err(
                id,
                error_codes::METHOD_NOT_FOUND,
                format!("unknown tool: {tool}"),
            ),
            Err(ToolError::InvalidParams(msg)) => {
                Response::err(id, error_codes::INVALID_PARAMS, msg)
            }
        }
    }
}

// ─── Tests ────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;
    use std::sync::Arc;
    use trusty_common::mcp::error_codes;

    use crate::{
        config::ReviewConfig,
        integrations::search_client::{
            EmbedderState, HealthResponse as SearchHealth, IndexInfo, SearchClient,
            SearchClientError, SearchResult,
        },
        llm::{LlmError, LlmProvider, LlmRequest, LlmResponse},
        service::AppState,
    };
    use async_trait::async_trait;

    // ── Fake LLM ──────────────────────────────────────────────────────────────

    struct FakeLlm;

    #[async_trait]
    impl LlmProvider for FakeLlm {
        fn name(&self) -> &str {
            "fake-mcp-test"
        }

        async fn complete(&self, req: LlmRequest) -> Result<LlmResponse, LlmError> {
            Ok(LlmResponse {
                text: r#"{"verdict":"APPROVE","summary":"ok","findings":[]}"#.into(),
                model: req.model.clone(),
                input_tokens: 1,
                output_tokens: 1,
                latency_ms: 0,
                cost_usd: 0.0,
            })
        }
    }

    // ── Fake search ───────────────────────────────────────────────────────────

    struct FakeSearch;

    #[async_trait]
    impl SearchClient for FakeSearch {
        async fn health(&self) -> Result<SearchHealth, SearchClientError> {
            Ok(SearchHealth {
                status: "ok".into(),
                embedder: EmbedderState::Bool(true),
            })
        }

        async fn list_indexes(&self) -> Result<Vec<IndexInfo>, SearchClientError> {
            Ok(vec![])
        }

        async fn search(
            &self,
            _: &str,
            _: &str,
            _: Option<u32>,
        ) -> Result<Vec<SearchResult>, SearchClientError> {
            Ok(vec![])
        }
    }

    /// Build a minimal `AppState` suitable for unit tests.  Only `review_health`
    /// and protocol-level dispatch are exercised here; the FakeLlm is present to
    /// satisfy the constructor but is never called.
    fn test_state() -> AppState {
        let config = ReviewConfig::load(None);
        AppState::new(config, Arc::new(FakeLlm), Arc::new(FakeSearch), None)
    }

    fn make_req(method: &str, params: Value) -> Request {
        Request {
            jsonrpc: Some("2.0".into()),
            id: Some(json!(1)),
            method: method.into(),
            params: Some(params),
        }
    }

    #[tokio::test]
    async fn dispatch_initialize_returns_server_info() {
        let state = test_state();
        let req = make_req("initialize", json!({}));
        let resp = dispatch(req, &state).await;
        let result = resp.result.expect("expected result");
        assert_eq!(result["serverInfo"]["name"], "trusty-review");
        assert!(result["serverInfo"]["version"].is_string());
        assert_eq!(result["protocolVersion"], "2024-11-05");
    }

    #[tokio::test]
    async fn dispatch_tools_list_returns_three_tools() {
        let state = test_state();
        let req = make_req("tools/list", json!({}));
        let resp = dispatch(req, &state).await;
        let result = resp.result.expect("expected result");
        let tools = result["tools"].as_array().expect("tools must be array");
        assert_eq!(tools.len(), 3, "expected 3 tools");
    }

    #[tokio::test]
    async fn dispatch_unknown_tool_returns_method_not_found() {
        let state = test_state();
        let req = make_req("not_a_tool", json!({}));
        let resp = dispatch(req, &state).await;
        let err = resp.error.expect("expected error");
        assert_eq!(err.code, error_codes::METHOD_NOT_FOUND);
    }

    #[tokio::test]
    async fn dispatch_notification_is_suppressed() {
        let state = test_state();
        let req = Request {
            jsonrpc: Some("2.0".into()),
            id: None, // notification — no id
            method: "notifications/initialized".into(),
            params: None,
        };
        let resp = dispatch(req, &state).await;
        assert!(resp.suppress, "notification must be suppressed");
    }

    #[tokio::test]
    async fn dispatch_review_health_via_bare_method() {
        let state = test_state();
        let req = make_req("review_health", json!({}));
        let resp = dispatch(req, &state).await;
        let result = resp.result.expect("expected result");
        // review_health wraps the payload in {content:[{type:text,text:...}]}
        let text = result["content"][0]["text"].as_str().expect("text field");
        let health: Value = serde_json::from_str(text).expect("valid JSON in text");
        assert_eq!(health["status"], "ok");
        assert!(health["version"].is_string());
    }

    #[tokio::test]
    async fn dispatch_review_health_via_tools_call() {
        let state = test_state();
        let req = make_req(
            "tools/call",
            json!({ "name": "review_health", "arguments": {} }),
        );
        let resp = dispatch(req, &state).await;
        let result = resp.result.expect("expected result");
        let text = result["content"][0]["text"].as_str().expect("text field");
        let health: Value = serde_json::from_str(text).expect("valid JSON in text");
        assert_eq!(health["status"], "ok");
    }

    #[tokio::test]
    async fn dispatch_rejects_wrong_jsonrpc_version() {
        let state = test_state();
        let req = Request {
            jsonrpc: Some("1.0".into()),
            id: Some(json!(7)),
            method: "review_health".into(),
            params: None,
        };
        let resp = dispatch(req, &state).await;
        let err = resp.error.expect("expected error");
        assert_eq!(err.code, error_codes::INVALID_REQUEST);
    }

    #[tokio::test]
    async fn dispatch_tools_call_missing_name_returns_invalid_params() {
        let state = test_state();
        let req = make_req("tools/call", json!({ "arguments": {} }));
        let resp = dispatch(req, &state).await;
        let err = resp.error.expect("expected error");
        assert_eq!(err.code, error_codes::INVALID_PARAMS);
    }
}