Skip to main content

aptu_coder/
lib.rs

1// SPDX-FileCopyrightText: 2026 aptu-coder contributors
2// SPDX-License-Identifier: Apache-2.0
3//! Rust MCP server for code structure analysis using tree-sitter.
4//!
5//! This crate exposes seven MCP tools for multiple programming languages:
6//!
7//! **Analyze family:**
8//! - **`analyze_directory`**: Directory tree with file counts and structure
9//! - **`analyze_file`**: Semantic extraction (functions, classes, imports)
10//! - **`analyze_symbol`**: Call graph analysis (callers and callees)
11//! - **`analyze_module`**: Lightweight function and import index
12//!
13//! **Edit family:**
14//! - **`edit_overwrite`**: Create or overwrite files
15//! - **`edit_replace`**: Replace text blocks in files
16//!
17//! **Exec family:**
18//! - **`exec_command`**: Run shell commands with progress notifications
19//!
20//! Key entry points:
21//! - [`analyze::analyze_directory`]: Analyze entire directory tree
22//! - [`analyze::analyze_file`]: Analyze single file
23//!
24//! Languages supported: Astro, C/C++, C#, CSS, Fortran, Go, HTML, Java, JavaScript, JSON, Kotlin, Markdown, Python, Rust, TOML, TSX, TypeScript, YAML.
25
26#![cfg_attr(test, allow(clippy::unwrap_used))]
27#![cfg_attr(test, allow(clippy::expect_used))]
28
29mod filters;
30pub(crate) mod heredoc_validation;
31pub(crate) mod metrics;
32pub(crate) mod metrics_export;
33pub(crate) mod otel;
34pub(crate) mod shell;
35pub(crate) mod shell_scan;
36/// Heredoc and shell file-write pattern detection (pre-spawn guard for exec_command).
37pub(crate) mod shell_write;
38pub(crate) mod tools;
39pub(crate) mod validation;
40
41pub use metrics::{MetricEvent, MetricsSender, MetricsWriter, migrate_legacy_metrics_dir};
42pub use otel::{
43    ClientMetadata, extract_and_set_trace_context, init_log_appender, init_meter, init_otel,
44};
45
46use aptu_coder_core::analyze;
47use aptu_coder_core::{cache, completion, types};
48use validation::validate_path;
49
50use crate::tools::common::{err_to_tool_result, no_cache_meta};
51
52pub const STDIN_MAX_BYTES: usize = 1_048_576;
53
54#[non_exhaustive]
55#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
56pub struct ExecCommandParams {
57    /// Shell command to execute via sh -c (or $SHELL if set).
58    pub command: String,
59    /// Working directory for the command. Set this instead of prepending cd to the command string. Validated against path traversal; does not sandbox the process.
60    pub working_dir: Option<String>,
61    /// UTF-8 content to pipe into the process stdin (max `STDIN_MAX_BYTES` = 1 MB). When None, stdin is closed (null).
62    pub stdin: Option<String>,
63    /// Maximum execution time in seconds. When the command exceeds this limit, the
64    /// child process is killed and the response indicates `timed_out: true`.
65    /// A value of 0 or None means no timeout (unlimited execution).
66    #[serde(default)]
67    pub timeout_secs: Option<i64>,
68    /// Drain timeout in milliseconds after the child process exits. When the child
69    /// exits but a background subprocess holds pipes open, the drain collects
70    /// buffered output for this many milliseconds before returning
71    /// `output_truncated: true`. Default: 500ms when omitted or 0.
72    /// Positive values override the default. Negative values are rejected with
73    /// INVALID_PARAMS.
74    #[serde(default)]
75    pub drain_timeout_secs: Option<i64>,
76}
77
78impl ExecCommandParams {
79    /// Creates a new ExecCommandParams with the given command.
80    #[must_use]
81    pub fn new(command: String, working_dir: Option<String>) -> Self {
82        Self {
83            command,
84            working_dir,
85            ..Default::default()
86        }
87    }
88}
89
90#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
91pub struct ShellOutput {
92    /// Standard output from the command.
93    pub stdout: String,
94    /// Standard error from the command.
95    pub stderr: String,
96    /// Stdout and stderr interleaved in arrival order.
97    pub interleaved: String,
98    /// Exit code; null if the process could not be waited on (e.g. drain timeout from a background process holding pipes).
99    pub exit_code: Option<i32>,
100    /// True if the post-exit drain timed out (backgrounded process kept pipes open).
101    /// When true, any available output is still included; use the overflow file path
102    /// from the truncation notice Content block to recover the full output.
103    pub output_truncated: bool,
104    /// Set when the post-exit drain timed out because a background process held the
105    /// pipes open. Distinct from `output_truncated` (size cap) -- this indicates a
106    /// drain timeout rather than a size overflow.
107    pub output_collection_error: Option<String>,
108    /// Path to the slot file containing full stdout (if output was persisted).
109    #[serde(skip_serializing_if = "Option::is_none")]
110    pub stdout_path: Option<String>,
111    /// Path to the slot file containing full stderr (if output was persisted).
112    #[serde(skip_serializing_if = "Option::is_none")]
113    pub stderr_path: Option<String>,
114    /// Path to the slot file containing full interleaved output (if output was persisted).
115    #[serde(skip_serializing_if = "Option::is_none")]
116    pub interleaved_path: Option<String>,
117    /// Description of the filter applied to stdout (if any).
118    #[serde(skip_serializing_if = "Option::is_none")]
119    pub filter_applied: Option<String>,
120    /// True when the command was killed due to exceeding `timeout_secs`.
121    /// When true, exit_code is None and no partial output is available.
122    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
123    pub timed_out: bool,
124}
125
126impl ShellOutput {
127    /// Creates a new ShellOutput with the given parameters.
128    #[must_use]
129    pub fn new(
130        stdout: String,
131        stderr: String,
132        interleaved: String,
133        exit_code: Option<i32>,
134        output_truncated: bool,
135    ) -> Self {
136        Self {
137            stdout,
138            stderr,
139            interleaved,
140            exit_code,
141            output_truncated,
142            output_collection_error: None,
143            stdout_path: None,
144            stderr_path: None,
145            interleaved_path: None,
146            filter_applied: None,
147            timed_out: false,
148        }
149    }
150}
151
152#[cfg(test)]
153use aptu_coder_core::cache::CacheTier;
154use aptu_coder_core::cache::{AnalysisCache, CallGraphCache};
155use aptu_coder_core::types::{
156    AnalyzeDirectoryParams, AnalyzeFileParams, AnalyzeModuleParams, AnalyzeSymbolParams,
157    EditOverwriteOutput, EditOverwriteParams, EditReplaceOutput, EditReplaceParams,
158};
159use filters::CompiledRule;
160
161use rmcp::handler::server::tool::{ToolRouter, schema_for_type};
162use rmcp::handler::server::wrapper::Parameters;
163use rmcp::model::{
164    CallToolResponse, CallToolResult, CancelledNotificationParam, CompleteRequestParams,
165    CompleteResult, CompletionInfo, ContentBlock, DiscoverResult, ErrorData, Implementation,
166    InitializeRequestParams, InitializeResult, ServerCapabilities,
167};
168use rmcp::service::{NotificationContext, RequestContext};
169use rmcp::{Peer, RoleServer, ServerHandler, tool, tool_handler, tool_router};
170
171use std::collections::HashMap;
172use std::path::Path;
173use std::sync::{Arc, Mutex};
174use tokio::sync::{Mutex as TokioMutex, RwLock};
175use tracing::instrument;
176
177static GLOBAL_SESSION_COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
178
179// 5_000 chars fires at ~150-180 files at depth=2 (~28-33 chars/file).
180// Empirical data (684 calls, Jun 2026): max observed output was 4,882 chars; the old
181// 50_000 threshold never triggered once. At 5_000, auto-summary engages for repos that
182// would otherwise produce an overwhelming flat response.
183pub(crate) const SIZE_LIMIT: usize = 5_000;
184
185pub(crate) fn err_to_tool_result_from_pagination(
186    e: aptu_coder_core::pagination::PaginationError,
187) -> CallToolResult {
188    let msg = format!("Pagination error: {}", e);
189    CallToolResult::error(vec![ContentBlock::text(msg)]).with_meta(Some(no_cache_meta()))
190}
191
192/// MCP server handler that wires the four analysis tools to the rmcp transport.
193///
194/// Holds shared state: tool router, analysis cache, peer connection, log-level filter,
195/// log event channel, metrics sender, and per-session sequence tracking.
196#[derive(Clone)]
197pub struct CodeAnalyzer {
198    // Read lock acquired by list_tools/call_tool; write lock acquired during on_initialized
199    // for bind_peer_notifier.
200    // IMPORTANT: Do not perform long-running I/O while holding the write lock.
201    pub(crate) tool_router: Arc<RwLock<ToolRouter<Self>>>,
202    cache: AnalysisCache,
203    disk_cache: std::sync::Arc<cache::DiskCache>,
204    peer: Arc<TokioMutex<Option<Peer<RoleServer>>>>,
205    metrics_tx: crate::metrics::MetricsSender,
206    session_call_seq: Arc<std::sync::atomic::AtomicU32>,
207    session_id: Arc<TokioMutex<Option<String>>>,
208    client_name: Arc<TokioMutex<Option<String>>>,
209    client_version: Arc<TokioMutex<Option<String>>>,
210    // Resolved login shell PATH, captured once at startup via login shell invocation.
211    // Arc<Option<String>> is immutable after init; no lock needed.
212    resolved_path: Arc<Option<String>>,
213    // Compiled filter rules table (built-in + project-local from .aptu/filters.toml).
214    // Immutable after init; no lock needed.
215    filter_table: Arc<Vec<CompiledRule>>,
216    // L1 in-memory LRU cache for call graph results (analyze_symbol).
217    // Capacity controlled by APTU_CODER_SYMBOL_CACHE_CAPACITY env var (default 32).
218    call_graph_cache: CallGraphCache,
219    // Per-(session_id, canonical_path) consecutive edit_replace failure counter.
220    // Used to detect stale LLM context and return a directive error instead of
221    // repeatedly trying an old_text that no longer matches the file content.
222    edit_failure_counts: Arc<Mutex<HashMap<(String, String), u8>>>,
223}
224
225#[tool_router]
226impl CodeAnalyzer {
227    #[must_use]
228    pub fn list_tools() -> Vec<rmcp::model::Tool> {
229        Self::tool_router().list_all()
230    }
231
232    pub fn new(
233        peer: Arc<TokioMutex<Option<Peer<RoleServer>>>>,
234        metrics_tx: crate::metrics::MetricsSender,
235    ) -> Self {
236        crate::tools::server::build_analyzer(peer, metrics_tx)
237    }
238
239    /// Emit a "received" metric event for the given tool name.
240    /// Increments the session call sequence, locks the session ID, and sends
241    /// the metric event via the channel. Returns the (seq, sid) pair for use
242    /// by the caller in exit metrics, preserving per-call seq uniqueness.
243    async fn emit_received_metric(&self, tool: &'static str) -> (u32, Option<String>) {
244        crate::tools::server::emit_received_metric(
245            &self.metrics_tx,
246            &self.session_id,
247            &self.session_call_seq,
248            tool,
249        )
250        .await
251    }
252
253    /// Delegates to [`tools::server::handle_overview_mode`].
254    /// Kept for test access; production path goes through `analyze_directory` shim.
255    #[cfg(test)]
256    pub(crate) async fn handle_overview_mode(
257        &self,
258        params: &AnalyzeDirectoryParams,
259        ct: tokio_util::sync::CancellationToken,
260    ) -> Result<(std::sync::Arc<analyze::AnalysisOutput>, CacheTier), ErrorData> {
261        let ctx = crate::tools::AnalyzeDirectoryContext {
262            cache: self.cache.clone(),
263            disk_cache: self.disk_cache.clone(),
264            metrics_tx: self.metrics_tx.clone(),
265            peer: self.peer.clone(),
266            sid: self.session_id.lock().await.clone(),
267        };
268        crate::tools::server::handle_overview_mode(&ctx, params, ct).await
269    }
270
271    /// Delegates to [`tools::server::handle_file_details_mode`].
272    /// Kept for test access; production path goes through `analyze_file` shim.
273    #[cfg(test)]
274    pub(crate) async fn handle_file_details_mode(
275        &self,
276        params: &aptu_coder_core::types::AnalyzeFileParams,
277    ) -> Result<(std::sync::Arc<analyze::FileAnalysisOutput>, CacheTier), ErrorData> {
278        crate::tools::server::handle_file_details_mode(
279            self.cache.clone(),
280            self.disk_cache.clone(),
281            self.metrics_tx.clone(),
282            self.session_id.lock().await.clone(),
283            params,
284        )
285        .await
286    }
287
288    #[instrument(skip(self, context), fields(gen_ai.system = tracing::field::Empty, gen_ai.operation.name = tracing::field::Empty, gen_ai.tool.name = tracing::field::Empty, error = tracing::field::Empty, error.type = tracing::field::Empty, path = tracing::field::Empty, mcp.session.id = tracing::field::Empty, client.name = tracing::field::Empty, client.version = tracing::field::Empty, mcp.client.session.id = tracing::field::Empty, cache_tier = tracing::field::Empty))]
289    #[tool(
290        name = "analyze_directory",
291        title = "Analyze Directory",
292        description = "Tree-view of directory with LOC, function/class counts, test markers. Respects .gitignore. Paginates with next_cursor. Default max_depth=3; pass 0 for unlimited. Large dirs (1000+ files) auto-compact to summary; pass summary=false for per-file list (summary and cursor are mutually exclusive). git_ref restricts to files changed since a branch/tag/commit. Empty directories return zero counts.",
293        output_schema = schema_for_type::<analyze::AnalysisOutput>(),
294        annotations(
295            title = "Analyze Directory",
296            read_only_hint = true,
297            destructive_hint = false,
298            idempotent_hint = true,
299            open_world_hint = false
300        )
301    )]
302    async fn analyze_directory(
303        &self,
304        params: Parameters<AnalyzeDirectoryParams>,
305        context: RequestContext<RoleServer>,
306    ) -> Result<CallToolResult, ErrorData> {
307        let mut params = params.0;
308        params.max_depth = params.max_depth.or(Some(3));
309        let t_start = std::time::Instant::now();
310        let (seq, sid) = self.emit_received_metric("analyze_directory").await;
311        let session_id = self.session_id.lock().await.clone();
312        let client_name = self.client_name.lock().await.clone();
313        let client_version = self.client_version.lock().await.clone();
314        extract_and_set_trace_context(
315            Some(&context.meta),
316            ClientMetadata {
317                session_id,
318                client_name,
319                client_version,
320            },
321        );
322        let span = tracing::Span::current();
323        span.record("gen_ai.system", "mcp");
324        span.record("gen_ai.operation.name", "execute_tool");
325        span.record("gen_ai.tool.name", "analyze_directory");
326        span.record("path", &params.path);
327        let _validated_path = match validate_path(&params.path, true) {
328            Ok(p) => p,
329            Err(e) => {
330                span.record("error", true);
331                span.record("error.type", "invalid_params");
332                return Ok(err_to_tool_result(e));
333            }
334        };
335        let ct = context.ct.clone();
336        let param_path = params.path.clone();
337        let max_depth_val = params.max_depth;
338        let ctx = tools::AnalyzeDirectoryContext {
339            cache: self.cache.clone(),
340            disk_cache: self.disk_cache.clone(),
341            metrics_tx: self.metrics_tx.clone(),
342            peer: self.peer.clone(),
343            sid: sid.clone(),
344        };
345        tools::analyze_directory::analyze_directory_handler(
346            &ctx,
347            params,
348            tools::DirectoryHandlerCall {
349                seq,
350                sid,
351                t_start,
352                param_path,
353                max_depth_val,
354                ct,
355            },
356            &span,
357        )
358        .await
359    }
360
361    #[instrument(skip(self, context), fields(gen_ai.system = tracing::field::Empty, gen_ai.operation.name = tracing::field::Empty, gen_ai.tool.name = tracing::field::Empty, error = tracing::field::Empty, error.type = tracing::field::Empty, path = tracing::field::Empty, mcp.session.id = tracing::field::Empty, client.name = tracing::field::Empty, client.version = tracing::field::Empty, mcp.client.session.id = tracing::field::Empty, cache_tier = tracing::field::Empty))]
362    #[tool(
363        name = "analyze_file",
364        title = "Analyze File",
365        description = "Functions, types, classes, and imports from a single source file. Fails if directory path supplied; use analyze_directory instead. Paginates with cursor/page_size; use fields=[\"functions\",\"classes\",\"imports\"] to limit sections. summary=true and cursor are mutually exclusive. git_ref not supported. Use analyze_module for a lightweight function/import index (~75% smaller). Supported: Astro, C/C++, C#, CSS, Fortran, Go, HTML, Java, JavaScript, JSON, Kotlin, Markdown, Python, Rust, TOML, TSX, TypeScript, YAML.",
366        output_schema = schema_for_type::<analyze::FileAnalysisOutput>(),
367        annotations(
368            title = "Analyze File",
369            read_only_hint = true,
370            destructive_hint = false,
371            idempotent_hint = true,
372            open_world_hint = false
373        )
374    )]
375    async fn analyze_file(
376        &self,
377        params: Parameters<AnalyzeFileParams>,
378        context: RequestContext<RoleServer>,
379    ) -> Result<CallToolResult, ErrorData> {
380        let params = params.0;
381        let t_start = std::time::Instant::now();
382        let (seq, sid) = self.emit_received_metric("analyze_file").await;
383        let session_id = self.session_id.lock().await.clone();
384        let client_name = self.client_name.lock().await.clone();
385        let client_version = self.client_version.lock().await.clone();
386        extract_and_set_trace_context(
387            Some(&context.meta),
388            ClientMetadata {
389                session_id,
390                client_name,
391                client_version,
392            },
393        );
394        let span = tracing::Span::current();
395        span.record("gen_ai.system", "mcp");
396        span.record("gen_ai.operation.name", "execute_tool");
397        span.record("gen_ai.tool.name", "analyze_file");
398        span.record("path", &params.path);
399        let _validated_path = match validate_path(&params.path, true) {
400            Ok(p) => p,
401            Err(e) => {
402                span.record("error", true);
403                span.record("error.type", "invalid_params");
404                return Ok(err_to_tool_result(e));
405            }
406        };
407        let param_path = params.path.clone();
408        let ctx = tools::AnalyzeFileContext {
409            cache: self.cache.clone(),
410            disk_cache: self.disk_cache.clone(),
411            metrics_tx: self.metrics_tx.clone(),
412            sid: sid.clone(),
413        };
414        tools::analyze_file::analyze_file_handler(
415            &ctx, params, seq, sid, t_start, param_path, &span,
416        )
417        .await
418    }
419
420    #[instrument(skip(self, context), fields(gen_ai.system = tracing::field::Empty, gen_ai.operation.name = tracing::field::Empty, gen_ai.tool.name = tracing::field::Empty, error = tracing::field::Empty, error.type = tracing::field::Empty, symbol = tracing::field::Empty, mcp.session.id = tracing::field::Empty, client.name = tracing::field::Empty, client.version = tracing::field::Empty, mcp.client.session.id = tracing::field::Empty, cache_tier = tracing::field::Empty))]
421    #[tool(
422        name = "analyze_symbol",
423        title = "Analyze Symbol",
424        description = "Call graph for a named symbol across all files in a directory. Use for \"who calls X\", transitive chains, or files importing a module path. Prefer over analyze_file when the question is \"who calls X\" or \"what does X call\" rather than \"what is in this file\". Modes: call graph (default), import_lookup (files importing a module path), def_use (write/read sites). Fails if file path supplied; fails if impl_only=true on non-Rust directory; fails if import_lookup=true with empty symbol; fails if summary=true and cursor. match_mode controls name matching (exact/insensitive/prefix/contains). git_ref restricts to changed files.",
425        output_schema = schema_for_type::<analyze::FocusedAnalysisOutput>(),
426        annotations(
427            title = "Analyze Symbol",
428            read_only_hint = true,
429            destructive_hint = false,
430            idempotent_hint = true,
431            open_world_hint = false
432        )
433    )]
434    async fn analyze_symbol(
435        &self,
436        params: Parameters<AnalyzeSymbolParams>,
437        context: RequestContext<RoleServer>,
438    ) -> Result<CallToolResult, ErrorData> {
439        let params = params.0;
440        let t_start = std::time::Instant::now();
441        let (seq, sid) = self.emit_received_metric("analyze_symbol").await;
442        let session_id = self.session_id.lock().await.clone();
443        let client_name = self.client_name.lock().await.clone();
444        let client_version = self.client_version.lock().await.clone();
445        extract_and_set_trace_context(
446            Some(&context.meta),
447            ClientMetadata {
448                session_id,
449                client_name,
450                client_version,
451            },
452        );
453        let span = tracing::Span::current();
454        span.record("gen_ai.system", "mcp");
455        span.record("gen_ai.operation.name", "execute_tool");
456        span.record("gen_ai.tool.name", "analyze_symbol");
457        span.record("symbol", &params.symbol);
458        let _validated_path = match validate_path(&params.path, true) {
459            Ok(p) => p,
460            Err(e) => {
461                span.record("error", true);
462                span.record("error.type", "invalid_params");
463                return Ok(err_to_tool_result(e));
464            }
465        };
466        let ct = context.ct.clone();
467        let param_path = params.path.clone();
468        let max_depth_val = params.follow_depth;
469        let ctx = tools::AnalyzeSymbolContext {
470            metrics_tx: self.metrics_tx.clone(),
471            call_graph_cache: self.call_graph_cache.clone(),
472            disk_cache: self.disk_cache.clone(),
473            sid: sid.clone(),
474            seq,
475        };
476        let call = tools::AnalyzeSymbolCall {
477            ct,
478            param_path,
479            max_depth_val,
480            span,
481            t_start,
482        };
483        tools::analyze_symbol::analyze_symbol_handler(ctx, params, call).await
484    }
485
486    #[instrument(skip(self, context), fields(gen_ai.system = tracing::field::Empty, gen_ai.operation.name = tracing::field::Empty, gen_ai.tool.name = tracing::field::Empty, error = tracing::field::Empty, error.type = tracing::field::Empty, path = tracing::field::Empty, mcp.session.id = tracing::field::Empty, client.name = tracing::field::Empty, client.version = tracing::field::Empty, mcp.client.session.id = tracing::field::Empty, cache_tier = tracing::field::Empty))]
487    #[tool(
488        name = "analyze_module",
489        title = "Analyze Module",
490        description = "Lightweight function and import index for a single source file with minimal token cost: name, line_count, language, function names with line numbers, import list only (~75% smaller than analyze_file). Fails if directory path supplied. Pagination and git_ref not supported. Use analyze_file for signatures, types, or class details. Supported: Astro, C/C++, C#, CSS, Fortran, Go, HTML, Java, JavaScript, JSON, Kotlin, Markdown, Python, Rust, TOML, TSX, TypeScript, YAML.",
491        output_schema = schema_for_type::<types::ModuleInfo>(),
492        annotations(
493            title = "Analyze Module",
494            read_only_hint = true,
495            destructive_hint = false,
496            idempotent_hint = true,
497            open_world_hint = false
498        )
499    )]
500    async fn analyze_module(
501        &self,
502        params: Parameters<AnalyzeModuleParams>,
503        context: RequestContext<RoleServer>,
504    ) -> Result<CallToolResult, ErrorData> {
505        let params = params.0;
506        let t_start = std::time::Instant::now();
507        let (seq, sid) = self.emit_received_metric("analyze_module").await;
508        let session_id = self.session_id.lock().await.clone();
509        let client_name = self.client_name.lock().await.clone();
510        let client_version = self.client_version.lock().await.clone();
511        extract_and_set_trace_context(
512            Some(&context.meta),
513            ClientMetadata {
514                session_id,
515                client_name,
516                client_version,
517            },
518        );
519        let span = tracing::Span::current();
520        span.record("gen_ai.system", "mcp");
521        span.record("gen_ai.operation.name", "execute_tool");
522        span.record("gen_ai.tool.name", "analyze_module");
523        span.record("path", &params.path);
524        let _validated_path = match validate_path(&params.path, true) {
525            Ok(p) => p,
526            Err(e) => {
527                span.record("error", true);
528                span.record("error.type", "invalid_params");
529                return Ok(err_to_tool_result(e));
530            }
531        };
532        let param_path = params.path.clone();
533        let ctx = tools::AnalyzeModuleContext {
534            disk_cache: self.disk_cache.clone(),
535            metrics_tx: self.metrics_tx.clone(),
536            sid: sid.clone(),
537            seq,
538        };
539        tools::analyze_module::analyze_module_handler(ctx, params, param_path, &span, t_start).await
540    }
541
542    #[instrument(skip(self, context), fields(gen_ai.system = tracing::field::Empty, gen_ai.operation.name = tracing::field::Empty, gen_ai.tool.name = tracing::field::Empty, error = tracing::field::Empty, error.type = tracing::field::Empty, path = tracing::field::Empty, mcp.session.id = tracing::field::Empty, client.name = tracing::field::Empty, client.version = tracing::field::Empty, mcp.client.session.id = tracing::field::Empty))]
543    #[tool(
544        name = "edit_overwrite",
545        title = "Edit Overwrite",
546        description = "Creates or overwrites a file with UTF-8 content; creates parent directories if needed. Works on any file type. Use edit_replace for targeted single-block edits. working_dir sets the base directory for path resolution (default: server CWD).",
547        output_schema = schema_for_type::<EditOverwriteOutput>(),
548        annotations(
549            title = "Edit Overwrite",
550            read_only_hint = false,
551            destructive_hint = true,
552            idempotent_hint = false,
553            open_world_hint = false
554        )
555    )]
556    async fn edit_overwrite(
557        &self,
558        params: Parameters<EditOverwriteParams>,
559        context: RequestContext<RoleServer>,
560    ) -> Result<CallToolResult, ErrorData> {
561        let params = params.0;
562        let t_start = std::time::Instant::now();
563        let (seq, sid) = self.emit_received_metric("edit_overwrite").await;
564        // Extract W3C Trace Context from request _meta if present
565        let session_id = self.session_id.lock().await.clone();
566        let client_name = self.client_name.lock().await.clone();
567        let client_version = self.client_version.lock().await.clone();
568        extract_and_set_trace_context(
569            Some(&context.meta),
570            ClientMetadata {
571                session_id,
572                client_name,
573                client_version,
574            },
575        );
576        let span = tracing::Span::current();
577        span.record("gen_ai.system", "mcp");
578        span.record("gen_ai.operation.name", "execute_tool");
579        tools::edit_overwrite::edit_overwrite(
580            params,
581            tools::EditHandlerContext {
582                sid,
583                seq,
584                cache: &self.cache,
585                metrics_tx: &self.metrics_tx,
586                edit_failure_counts: &self.edit_failure_counts,
587            },
588            &span,
589            t_start,
590        )
591        .await
592    }
593
594    #[instrument(skip(self, context), fields(gen_ai.system = tracing::field::Empty, gen_ai.operation.name = tracing::field::Empty, gen_ai.tool.name = tracing::field::Empty, error = tracing::field::Empty, error.type = tracing::field::Empty, path = tracing::field::Empty, mcp.session.id = tracing::field::Empty, client.name = tracing::field::Empty, client.version = tracing::field::Empty, mcp.client.session.id = tracing::field::Empty))]
595    #[tool(
596        name = "edit_replace",
597        title = "Edit Replace",
598        description = "Replaces an exact text block; old_text must appear exactly once. Fails if zero or multiple matches (extend old_text to disambiguate). Set replace_all=true to replace every non-overlapping occurrence; old_text must be non-empty. Pass empty new_text to delete. CRLF in old_text normalized to LF; all other whitespace matched exactly. If invalid_params, re-read the file with analyze_file or analyze_module before retrying. Use edit_overwrite to replace the whole file. working_dir sets the base directory for path resolution (default: server CWD).",
599        output_schema = schema_for_type::<EditReplaceOutput>(),
600        annotations(
601            title = "Edit Replace",
602            read_only_hint = false,
603            destructive_hint = true,
604            idempotent_hint = false,
605            open_world_hint = false
606        )
607    )]
608    async fn edit_replace(
609        &self,
610        params: Parameters<EditReplaceParams>,
611        context: RequestContext<RoleServer>,
612    ) -> Result<CallToolResult, ErrorData> {
613        let params = params.0;
614        let t_start = std::time::Instant::now();
615        let (seq, sid) = self.emit_received_metric("edit_replace").await;
616        // Extract W3C Trace Context from request _meta if present
617        let session_id = self.session_id.lock().await.clone();
618        let client_name = self.client_name.lock().await.clone();
619        let client_version = self.client_version.lock().await.clone();
620        extract_and_set_trace_context(
621            Some(&context.meta),
622            ClientMetadata {
623                session_id,
624                client_name,
625                client_version,
626            },
627        );
628        let span = tracing::Span::current();
629        span.record("gen_ai.system", "mcp");
630        span.record("gen_ai.operation.name", "execute_tool");
631        tools::edit_replace::edit_replace(
632            params,
633            tools::EditHandlerContext {
634                sid,
635                seq,
636                cache: &self.cache,
637                metrics_tx: &self.metrics_tx,
638                edit_failure_counts: &self.edit_failure_counts,
639            },
640            &span,
641            t_start,
642        )
643        .await
644    }
645
646    #[tool(
647        name = "exec_command",
648        title = "Exec Command",
649        description = "Execute shell command via sh -c (or $SHELL if set). Output capped at 30 KB stdout / 10 KB stderr / 2000 lines. Set working_dir to the target directory; write commands with relative paths only. Pass stdin to pipe UTF-8 content (max 1 MB); heredoc syntax is rejected. For file writes use edit_overwrite or edit_replace. Prefer machine-readable output flags (e.g. --json) to reduce tokens.",
650        output_schema = schema_for_type::<ShellOutput>(),
651        annotations(
652            title = "Exec Command",
653            read_only_hint = false,
654            destructive_hint = true,
655            idempotent_hint = false,
656            open_world_hint = true
657        )
658    )]
659    #[instrument(skip(self, context), fields(gen_ai.system = tracing::field::Empty, gen_ai.operation.name = tracing::field::Empty, gen_ai.tool.name = tracing::field::Empty, error = tracing::field::Empty, error.type = tracing::field::Empty, command = tracing::field::Empty, exit_code = tracing::field::Empty, output_truncated = tracing::field::Empty, mcp.session.id = tracing::field::Empty, client.name = tracing::field::Empty, client.version = tracing::field::Empty, mcp.client.session.id = tracing::field::Empty))]
660    pub async fn exec_command(
661        &self,
662        params: Parameters<ExecCommandParams>,
663        context: RequestContext<RoleServer>,
664    ) -> Result<CallToolResult, ErrorData> {
665        let t_start = std::time::Instant::now();
666        let (seq, sid) = self.emit_received_metric("exec_command").await;
667        let params = params.0;
668        let session_id = self.session_id.lock().await.clone();
669        let client_name = self.client_name.lock().await.clone();
670        let client_version = self.client_version.lock().await.clone();
671        let ctx = crate::tools::exec_command::ExecContext {
672            seq,
673            sid,
674            session_id,
675            client_name,
676            client_version,
677            resolved_path: self.resolved_path.as_ref().as_deref().map(str::to_owned),
678            filter_table: self.filter_table.clone(),
679            metrics_tx: self.metrics_tx.clone(),
680            t_start,
681        };
682        crate::tools::exec_command::exec_command_impl(params, context, ctx).await
683    }
684}
685
686#[tool_handler]
687impl ServerHandler for CodeAnalyzer {
688    #[instrument(skip(self, _context), fields(service.name = tracing::field::Empty, service.version = tracing::field::Empty))]
689    async fn initialize(
690        &self,
691        request: InitializeRequestParams,
692        _context: RequestContext<RoleServer>,
693    ) -> Result<InitializeResult, ErrorData> {
694        let span = tracing::Span::current();
695        span.record("service.name", "aptu-coder");
696        span.record("service.version", env!("CARGO_PKG_VERSION"));
697
698        // Store client_info from the initialize request
699        {
700            let mut client_name_lock = self.client_name.lock().await;
701            *client_name_lock = Some(request.client_info.name.clone());
702        }
703        {
704            let mut client_version_lock = self.client_version.lock().await;
705            *client_version_lock = Some(request.client_info.version.clone());
706        }
707        Ok(self.get_info())
708    }
709
710    /// Returns server discovery information including supported protocol versions
711    /// and capabilities.
712    async fn discover(
713        &self,
714        _context: RequestContext<RoleServer>,
715    ) -> Result<DiscoverResult, ErrorData> {
716        Ok(DiscoverResult::from_server_info(
717            self.supported_protocol_versions().into_owned(),
718            self.get_info(),
719        ))
720    }
721
722    fn get_info(&self) -> InitializeResult {
723        let excluded = aptu_coder_core::EXCLUDED_DIRS.join(", ");
724        let instructions = format!(
725            "Recommended workflow:\n\
726            1. Start with analyze_directory(path=<repo_root>, max_depth=2, summary=true) to identify source package (largest by file count; exclude {excluded}).\n\
727            2. Re-run analyze_directory(path=<source_package>, max_depth=2, summary=true) for module map. Include test directories (tests/, *_test.go, test_*.py, test_*.rs, *.spec.ts, *.spec.js).\n\
728            3. For key files, prefer analyze_module for function/import index; use analyze_file for signatures and types.\n\
729            4. Use analyze_symbol to trace call graphs.\n\
730            Prefer summary=true on 1000+ files. Set max_depth=2; increase if packages too large. Paginate with cursor/page_size. For subagents: DISABLE_PROMPT_CACHING=1.\n\
731            JSONL metrics at $HOME/.local/share/aptu-coder/ (or $XDG_DATA_HOME/aptu-coder/). Always cd there before jq glob queries."
732        );
733        let capabilities = ServerCapabilities::builder()
734            .enable_tools()
735            .enable_tool_list_changed()
736            .enable_completions()
737            .build();
738        let server_info = Implementation::new("aptu-coder", env!("CARGO_PKG_VERSION"))
739            .with_title("Aptu Coder")
740            .with_description("MCP server for code structure analysis using tree-sitter");
741        InitializeResult::new(capabilities)
742            .with_server_info(server_info)
743            .with_instructions(&instructions)
744    }
745
746    async fn list_tools(
747        &self,
748        _request: Option<rmcp::model::PaginatedRequestParams>,
749        _context: RequestContext<RoleServer>,
750    ) -> Result<rmcp::model::ListToolsResult, ErrorData> {
751        let router = self.tool_router.read().await;
752        Ok(rmcp::model::ListToolsResult::with_all_items(
753            router.list_all(),
754        ))
755    }
756
757    async fn call_tool(
758        &self,
759        request: rmcp::model::CallToolRequestParams,
760        context: RequestContext<RoleServer>,
761    ) -> Result<CallToolResponse, ErrorData> {
762        let tcc = rmcp::handler::server::tool::ToolCallContext::new(self, request, context);
763        let router = self.tool_router.read().await;
764        router.call(tcc).await
765    }
766
767    async fn on_initialized(&self, context: NotificationContext<RoleServer>) {
768        crate::tools::server::on_initialized_impl(
769            self.peer.clone(),
770            self.session_id.clone(),
771            self.session_call_seq.clone(),
772            self.tool_router.clone(),
773            &context.peer,
774        )
775        .await;
776    }
777
778    #[instrument(skip(self, _context))]
779    async fn on_cancelled(
780        &self,
781        notification: CancelledNotificationParam,
782        _context: NotificationContext<RoleServer>,
783    ) {
784        tracing::info!(
785            request_id = ?notification.request_id,
786            reason = ?notification.reason,
787            "Received cancellation notification"
788        );
789    }
790
791    #[instrument(skip(self, _context))]
792    async fn complete(
793        &self,
794        request: CompleteRequestParams,
795        _context: RequestContext<RoleServer>,
796    ) -> Result<CompleteResult, ErrorData> {
797        // Dispatch on argument name: "path" or "symbol"
798        let argument_name = &request.argument.name;
799        let argument_value = &request.argument.value;
800
801        let completions = match argument_name.as_str() {
802            "path" => {
803                // Path completions: use current directory as root
804                let root = Path::new(".");
805                completion::path_completions(root, argument_value)
806            }
807            "symbol" => {
808                // Symbol completions: need the path argument from context
809                let path_arg = request
810                    .context
811                    .as_ref()
812                    .and_then(|ctx| ctx.get_argument("path"));
813
814                match path_arg {
815                    Some(path_str) => {
816                        let path = Path::new(path_str);
817                        completion::symbol_completions(&self.cache, path, argument_value)
818                    }
819                    None => Vec::new(),
820                }
821            }
822            _ => Vec::new(),
823        };
824
825        // Create CompletionInfo with has_more flag if >100 results
826        let total_count = u32::try_from(completions.len()).unwrap_or(u32::MAX);
827        let (values, has_more) = if completions.len() > 100 {
828            (completions.into_iter().take(100).collect(), true)
829        } else {
830            (completions, false)
831        };
832
833        let completion_info =
834            match CompletionInfo::with_pagination(values, Some(total_count), has_more) {
835                Ok(info) => info,
836                Err(_) => {
837                    // Graceful degradation: return empty on error
838                    CompletionInfo::with_all_values(Vec::new())
839                        .unwrap_or_else(|_| CompletionInfo::new(Vec::new()).unwrap())
840                }
841            };
842
843        Ok(CompleteResult::new(completion_info))
844    }
845}
846
847#[cfg(test)]
848mod tests;