hank 0.4.0

In-memory, multi-tenant code-analysis engine — the structural signal for the Bobbin × Quipu stack
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
//! The Hank MCP server and its tools.
//!
//! Registration mirrors Bobbin: a `#[tool_router]` impl of `#[tool]`-annotated
//! async methods taking `Parameters<Req>`, a `#[tool_handler] ServerHandler`
//! providing `get_info`, and stdio + streamable-HTTP transports.

use std::path::PathBuf;

use anyhow::Result;
use rmcp::handler::server::router::tool::ToolRouter;
use rmcp::handler::server::wrapper::Parameters;
use rmcp::model::{
    CallToolResult, Content, Implementation, ProtocolVersion, ServerCapabilities, ServerInfo,
};
use rmcp::{tool, tool_handler, tool_router, ErrorData as McpError, ServerHandler};
use serde::Serialize;

use std::collections::BTreeSet;

use super::tools::PromoteRequest;
#[cfg(feature = "quipu")]
use super::tools::PromoteResponse;
use super::tools::{
    AnalyzeRequest, AnalyzeResponse, CommunitiesRequest, CommunitiesResponse, CommunityItem,
    CommunityMemberItem, DataflowRequest, DataflowResponse, DepEdgeItem, FlowStepItem,
    ImpactRequest, ImpactResponse, NeighborsRequest, NeighborsResponse, ReachItem,
    ReconciliationItem, RefItem, ReferencesRequest, ReferencesResponse, StatusResponse, SymbolItem,
    SymbolsRequest, SymbolsResponse, VerifyRequest, VerifyResponse, ViolationItem,
};
use crate::config::HankConfig;
use crate::dataflow::{Dataflow, FlowDir};
use crate::extract::{extract_symbols, rust_files};
use crate::graph::{CodeGraph, Dir, Reached};
use crate::reconcile::reconcile;
use crate::types::Tier;

/// The provenance tier of everything the call graph and dataflow serve. The
/// graph is built entirely from tree-sitter extraction (`CodeGraph::build`), so
/// every reachability/dataflow fact is `treesitter` today — one source of truth
/// for that string rather than a literal repeated per handler, and the place to
/// propagate a real per-node tier from when the LSP/CPG tiers start resolving
/// edges (FR-3).
fn graph_tier() -> String {
    Tier::TreeSitter.as_str().to_string()
}

/// Hank's MCP server. Resolves requests against the analysis root for a tenant.
#[derive(Clone)]
pub struct HankMcpServer {
    root: PathBuf,
    tenant: Option<String>,
    /// The `--config` override the server was launched with, if any. Honoured
    /// on every config read so `hank serve --config` is not silently ignored
    /// (aegis-ll3p).
    config: Option<PathBuf>,
    tool_router: ToolRouter<Self>,
}

impl HankMcpServer {
    /// Construct a server rooted at `root` for an optional `tenant`, honouring
    /// an optional `--config` override.
    #[must_use]
    pub fn new(root: PathBuf, tenant: Option<String>, config: Option<PathBuf>) -> Self {
        Self {
            root,
            tenant,
            config,
            tool_router: Self::tool_router(),
        }
    }
}

#[tool_router]
impl HankMcpServer {
    #[tool(
        description = "Show Hank's base ref, tenant, available extraction tiers, and Quipu promotion settings."
    )]
    async fn hank_status(&self) -> Result<CallToolResult, McpError> {
        let config = HankConfig::resolve(self.config.as_deref(), &self.root).map_err(internal)?;
        let response = StatusResponse {
            base_ref: config.base_ref,
            tenant: self
                .tenant
                .clone()
                .unwrap_or_else(|| "(single-tenant)".to_string()),
            tiers: Tier::served(),
            quipu_enabled: config.quipu.enabled,
            branch_model: config.quipu.branch_model,
            tenant_layer: super::resident::tenant_layer(self.config.as_deref(), &self.root),
        };
        json_result(&response)
    }

    #[tool(
        description = "List the symbols (functions, structs, traits, ...) defined in one file. Each symbol carries a tier tag. Best for: 'what's defined in src/auth.rs?'."
    )]
    async fn hank_symbols(
        &self,
        Parameters(req): Parameters<SymbolsRequest>,
    ) -> Result<CallToolResult, McpError> {
        let file = self.root.join(&req.file);
        let source = std::fs::read_to_string(&file).map_err(internal)?;
        let symbols = extract_symbols(&source, "rust").map_err(internal)?;
        let response = SymbolsResponse {
            file: req.file.clone(),
            count: symbols.len(),
            symbols: symbols
                .iter()
                .map(|symbol| SymbolItem {
                    name: symbol.name.clone(),
                    kind: symbol.kind.as_str().to_string(),
                    start_line: symbol.start_line,
                    end_line: symbol.end_line,
                    tier: symbol.tier.as_str().to_string(),
                })
                .collect(),
        };
        json_result(&response)
    }

    #[tool(
        description = "Find the definition site(s) of a symbol by name across a subtree. Best for: 'where is authenticate defined?'."
    )]
    async fn hank_references(
        &self,
        Parameters(req): Parameters<ReferencesRequest>,
    ) -> Result<CallToolResult, McpError> {
        // A position-based request (FR-4, hank #8) needs the node SPANS, which
        // the daemon's `/references` reply does not carry — so it takes the
        // transient path, like a `path`-scoped one. Slower, and correct;
        // answering it from a name lookup would hand back every same-named
        // symbol, which is the ambiguity the position was given to resolve.
        let by_position = req.at_file.is_some() || req.at_line.is_some();
        if req.path.is_none() && !by_position {
            if let Some(symbol) = req.symbol.as_deref() {
                if let Some(response) =
                    super::resident::references(self.config.as_deref(), &self.root, symbol)
                {
                    return json_result(&response);
                }
            }
        }
        let base = req
            .path
            .as_ref()
            .map_or_else(|| self.root.clone(), |p| self.root.join(p));
        // Build the multi-language graph, exactly as the resident path above
        // resolves against one. This walked `rust_files` and parsed every hit as
        // `"rust"`, so a `path`-scoped request (which always lands here, daemon
        // or not) over a Python tree searched ZERO files and answered "no
        // definitions" — the CLI-side hank #76 bug, same cause, second surface.
        let graph = match CodeGraph::build(&base) {
            Ok(graph) => graph,
            Err(e) => return Err(McpError::internal_error(e.to_string(), None)),
        };
        let to_item = |symbol: &crate::graph::SymbolNode| RefItem {
            file: symbol.file.clone(),
            name: symbol.name.clone(),
            kind: symbol.kind.clone(),
            start_line: symbol.start_line,
            tier: symbol.tier.as_str().to_string(),
        };
        let (queried, definitions): (String, Vec<RefItem>) =
            match (&req.symbol, &req.at_file, req.at_line) {
                // Position wins when given: it is the more specific request.
                (_, Some(file), Some(line)) => {
                    let hit = graph.symbol_at(file, line);
                    (
                        hit.map_or_else(|| format!("{file}:{line}"), |n| n.name.clone()),
                        hit.into_iter().map(to_item).collect(),
                    )
                }
                // Half a position is not a position. Refuse rather than quietly
                // dropping to a name lookup the caller did not ask for — a silent
                // downgrade would answer a "which one is here" question with "all
                // of them", the exact over-connection this parameter exists to cut.
                (_, Some(_), None) | (_, None, Some(_)) => {
                    return Err(McpError::invalid_params(
                        "at_file and at_line go together: give both for a position-based lookup, \
                     or neither and use `symbol`."
                            .to_string(),
                        None,
                    ));
                }
                (Some(name), None, None) => (
                    name.clone(),
                    graph.definitions(name).into_iter().map(to_item).collect(),
                ),
                (None, None, None) => {
                    return Err(McpError::invalid_params(
                        "give `symbol`, or `at_file` + `at_line` to resolve by position."
                            .to_string(),
                        None,
                    ));
                }
            };
        let response = ReferencesResponse {
            symbol: queried,
            count: definitions.len(),
            definitions,
            searched_symbols: Some(graph.stats().0),
            tier: crate::types::Tier::TreeSitter.as_str().to_string(),
        };
        json_result(&response)
    }

    #[tool(
        description = "Summarize the structure of a subtree: how many files and symbols. Best for a quick health check of the base graph."
    )]
    async fn hank_analyze(
        &self,
        Parameters(req): Parameters<AnalyzeRequest>,
    ) -> Result<CallToolResult, McpError> {
        let base = req
            .path
            .as_ref()
            .map_or_else(|| self.root.clone(), |p| self.root.join(p));
        let mut files = 0usize;
        let mut symbols = 0usize;
        for file in rust_files(&base) {
            let Ok(source) = std::fs::read_to_string(&file) else {
                continue;
            };
            if let Ok(found) = extract_symbols(&source, "rust") {
                files += 1;
                symbols += found.len();
            }
        }
        let response = AnalyzeResponse {
            files,
            symbols,
            tier: "treesitter".to_string(),
        };
        json_result(&response)
    }

    #[tool(
        description = "List the direct callers of a symbol (who calls it). Best for: 'who calls authenticate?'."
    )]
    async fn hank_callers(
        &self,
        Parameters(req): Parameters<NeighborsRequest>,
    ) -> Result<CallToolResult, McpError> {
        self.neighbors(&req, Dir::Callers)
    }

    #[tool(
        description = "List the direct callees of a symbol (what it calls). Best for: 'what does authenticate call?'."
    )]
    async fn hank_callees(
        &self,
        Parameters(req): Parameters<NeighborsRequest>,
    ) -> Result<CallToolResult, McpError> {
        self.neighbors(&req, Dir::Callees)
    }

    #[tool(
        description = "Blast radius: the symbols transitively affected by changing a symbol (its callers, up to N hops). Best for: 'what breaks if I change authenticate?'."
    )]
    async fn hank_impact(
        &self,
        Parameters(req): Parameters<ImpactRequest>,
    ) -> Result<CallToolResult, McpError> {
        let hops = req.hops.unwrap_or(5);
        // Stage 3c: an expected, same-root resident daemon answers with no
        // per-call build — but never a `path`-scoped request (the resident
        // graph is whole-root; a subtree query is a different graph). Every
        // `None` falls through to the transient build, silently (query
        // surface, not the guard — loud-absence is the hook's contract).
        if req.path.is_none() {
            if let Some(response) = super::resident::impact(
                self.config.as_deref(),
                &self.root,
                &req.symbol,
                hops,
                req.cochange.as_deref(),
            ) {
                return json_result(&response);
            }
        }
        let base = req
            .path
            .as_ref()
            .map_or_else(|| self.root.clone(), |p| self.root.join(p));
        let graph = CodeGraph::build(&base).map_err(internal)?;
        let found = graph.has_symbol(&req.symbol);
        let reachable = graph.reachable(&req.symbol, Dir::Callers, hops);
        let structural_files: BTreeSet<String> = reachable.iter().map(|r| r.file.clone()).collect();
        let reconciliation = req.cochange.as_ref().map(|cochange| {
            let cochange_set: BTreeSet<String> = cochange.iter().cloned().collect();
            let recon = reconcile(&structural_files, &cochange_set);
            ReconciliationItem {
                corroborated: recon.corroborated,
                structural_only: recon.structural_only,
                cochange_only: recon.cochange_only,
            }
        });
        let response = ImpactResponse {
            symbol: req.symbol.clone(),
            found,
            hops,
            count: reachable.len(),
            reachable: reachable.iter().map(reach_item).collect(),
            structural_files: structural_files.into_iter().collect(),
            reconciliation,
            tier: graph_tier(),
        };
        json_result(&response)
    }

    #[tool(
        description = "Detect communities: densely-connected clusters of symbols in the call graph (deterministic Louvain). Best for: 'what are the natural modules/subsystems here?'."
    )]
    async fn hank_communities(
        &self,
        Parameters(req): Parameters<CommunitiesRequest>,
    ) -> Result<CallToolResult, McpError> {
        let base = req
            .path
            .as_ref()
            .map_or_else(|| self.root.clone(), |p| self.root.join(p));
        let graph = CodeGraph::build(&base).map_err(internal)?;
        let comms = graph.communities();
        let communities = comms
            .iter()
            .map(|c| CommunityItem {
                id: c.id,
                size: c.members.len(),
                members: c
                    .members
                    .iter()
                    .map(|m| CommunityMemberItem {
                        name: m.name.clone(),
                        kind: m.kind.clone(),
                        file: m.file.clone(),
                        start_line: m.start_line,
                        tier: m.tier.as_str().to_string(),
                    })
                    .collect(),
            })
            .collect();
        let response = CommunitiesResponse {
            count: comms.len(),
            communities,
            tier: "treesitter".to_string(),
        };
        json_result(&response)
    }

    #[tool(
        description = "Verify a PROPOSED edit buffer before you write it: returns a boolean verdict plus violations (identifier-does-not-exist, wrong-arity, unresolved-import). Best for: 'will this edit break something?'. Note the `unchecked` list — a true verdict is not a compile."
    )]
    async fn hank_verify(
        &self,
        Parameters(req): Parameters<VerifyRequest>,
    ) -> Result<CallToolResult, McpError> {
        let file = self.root.join(&req.file);
        // The file's current contents are the baseline, so violations that
        // already exist are not blamed on the proposed edit.
        let baseline = std::fs::read_to_string(&file).ok();
        let verdict =
            crate::verify::verify_buffer(&self.root, &file, &req.buffer, baseline.as_deref())
                .map_err(internal)?;

        let response = VerifyResponse {
            file: req.file,
            ok: verdict.ok,
            violations: verdict
                .violations
                .iter()
                .map(|v| ViolationItem {
                    kind: serde_json::to_value(v.kind)
                        .ok()
                        .and_then(|k| k.as_str().map(str::to_string))
                        .unwrap_or_default(),
                    symbol: v.symbol.clone(),
                    line: v.line,
                    message: v.message.clone(),
                })
                .collect(),
            unchecked: verdict.unchecked,
            tier: "treesitter".to_string(),
        };
        json_result(&response)
    }

    // Always REGISTERED (the `#[tool_router]` macro references every `#[tool]`
    // method unconditionally, so cfg-gating the whole method breaks an `mcp`-only
    // build). The BODY is feature-split: real promotion under `quipu`, an honest
    // refusal without it — the same shape the CLI's `promote` uses.
    #[tool(
        description = "Promote a subtree's structural code facts into Quipu: emits Turtle, SHACL-validates it IN-PROCESS, and writes it only if it conforms (all-or-nothing). Returns wrote + triple count on success, or violations on refusal. The write is guarded by serve.read_only. Best for: 'get this code's structure into the knowledge graph, validated'."
    )]
    async fn hank_promote(
        &self,
        Parameters(req): Parameters<PromoteRequest>,
    ) -> Result<CallToolResult, McpError> {
        handlers::promote(self, &req)
    }

    #[tool(
        description = "Intra-procedural data dependence within a function. With `var`, trace what it depends on (or, with forward=true, what it flows into); without `var`, list all dependence edges. Best for: 'where does this value come from?'."
    )]
    async fn hank_dataflow(
        &self,
        Parameters(req): Parameters<DataflowRequest>,
    ) -> Result<CallToolResult, McpError> {
        handlers::dataflow(self, &req)
    }
}

impl HankMcpServer {
    /// Shared body for `hank_callers` / `hank_callees`.
    fn neighbors(&self, req: &NeighborsRequest, dir: Dir) -> Result<CallToolResult, McpError> {
        // Stage 3c: same cutover shape as `hank_impact` — resident daemon when
        // usable and unscoped, transient fallback otherwise (see there).
        if req.path.is_none() {
            if let Some(response) =
                super::resident::neighbors(self.config.as_deref(), &self.root, &req.symbol, dir)
            {
                return json_result(&response);
            }
        }
        let base = req
            .path
            .as_ref()
            .map_or_else(|| self.root.clone(), |p| self.root.join(p));
        let graph = CodeGraph::build(&base).map_err(internal)?;
        let found = graph.has_symbol(&req.symbol);
        let neighbors = graph.direct(&req.symbol, dir);
        let response = NeighborsResponse {
            symbol: req.symbol.clone(),
            found,
            count: neighbors.len(),
            neighbors: neighbors.iter().map(reach_item).collect(),
            tier: graph_tier(),
        };
        json_result(&response)
    }
}

#[tool_handler]
impl ServerHandler for HankMcpServer {
    fn get_info(&self) -> ServerInfo {
        ServerInfo {
            protocol_version: ProtocolVersion::V_2024_11_05,
            capabilities: ServerCapabilities::builder().enable_tools().build(),
            server_info: Implementation {
                name: "hank".to_string(),
                title: Some("Hank Code Structure".to_string()),
                version: env!("CARGO_PKG_VERSION").to_string(),
                icons: None,
                website_url: None,
            },
            instructions: Some(
                "Hank serves live, per-tenant code structure. Use hank_symbols to list a \
                 file's symbols, hank_references to find where a symbol is defined, \
                 hank_analyze for a subtree summary, and hank_status for base ref and tiers. \
                 Every fact is tagged with its tier (treesitter/lsp/cpg)."
                    .to_string(),
            ),
        }
    }
}

/// Serialize a response into a successful tool result.
fn json_result<T: Serialize>(value: &T) -> Result<CallToolResult, McpError> {
    let json = serde_json::to_string_pretty(value).map_err(internal)?;
    Ok(CallToolResult::success(vec![Content::text(json)]))
}

/// Map any error into an MCP internal error.
fn internal<E: std::fmt::Display>(err: E) -> McpError {
    McpError::internal_error(err.to_string(), None)
}

/// Convert a graph `Reached` into the wire DTO.
fn reach_item(reached: &Reached) -> ReachItem {
    ReachItem {
        name: reached.name.clone(),
        file: reached.file.clone(),
        start_line: reached.start_line,
        distance: reached.distance,
        via: reached.via.to_string(),
        tier: graph_tier(),
    }
}

// The bodies of the two heaviest tool handlers (hank #83). Not test-gated —
// `hank_promote` and `hank_dataflow` call into it at runtime.
#[path = "handlers.rs"]
mod handlers;

// The FR-3 enforcement walk (aegis-8yrn) lives in a size-exempt sibling file so
// it can call the private tool handlers as a child module without pushing
// server.rs past the 500-line limit.
#[cfg(all(test, feature = "mcp"))]
#[path = "server_test.rs"]
mod server_test;