Skip to main content

winx_code_agent/
server.rs

1//! Winx MCP Server implementation using rmcp 0.12.0
2//! Core MCP tools only - High performance shell and file management
3
4use rmcp::{
5    model::{
6        Annotated, CallToolRequestParams, CallToolResult, Content, GetPromptRequestParams,
7        GetPromptResult, Implementation, ListPromptsResult, ListResourcesResult, ListToolsResult,
8        PaginatedRequestParams, Prompt, PromptMessage, PromptMessageRole, ProtocolVersion,
9        RawResource, ReadResourceRequestParams, ReadResourceResult, ResourceContents,
10        ServerCapabilities, ServerInfo, Tool, ToolAnnotations,
11    },
12    service::{RequestContext, RoleServer},
13    transport::stdio,
14    ErrorData as McpError, ServerHandler, ServiceExt,
15};
16use schemars::schema_for;
17use serde_json::Value;
18use std::collections::HashMap;
19use std::fmt::Write as FmtWrite;
20use std::path::Path;
21use std::process::Command;
22use std::sync::atomic::{AtomicUsize, Ordering};
23use std::sync::{Arc, OnceLock};
24use std::time::Instant;
25use tokio::sync::Mutex;
26use tracing::{info, warn};
27
28use crate::errors::WinxError;
29use crate::state::bash_state::generate_thread_id;
30use crate::state::BashState;
31use crate::types::{
32    normalize_thread_id, BashCommand, ContextSave, FileWriteOrEdit, Initialize, ReadFiles,
33    ReadImage,
34};
35
36/// Map a domain [`WinxError`] to the right JSON-RPC error kind.
37///
38/// Client-caused failures (bad params, security violations, mode restrictions,
39/// state-not-initialized, ambiguous/not-found edits) become `invalid_request`
40/// so the model knows the fix is on its side; genuine server-side failures
41/// (PTY spawn, IO, lock poisoning, persistence) stay `internal_error`.
42fn to_mcp_error(tool: &str, err: &WinxError) -> McpError {
43    let msg = format!("{tool} failed: {err}");
44    // Exhaustive on purpose — NO wildcard arm. A new `WinxError` variant must be
45    // classified by hand (client vs server) or the build breaks. This is the
46    // guard that keeps the JSON-RPC error codes honest over time.
47    match err {
48        // Client-caused: the model can fix its own input or usage. -> invalid_request
49        WinxError::BashStateNotInitialized
50        | WinxError::CommandNotAllowed(_)
51        | WinxError::PathSecurityError { .. }
52        | WinxError::ThreadIdMismatch(_)
53        | WinxError::ParameterValidationError { .. }
54        | WinxError::MissingParameterError { .. }
55        | WinxError::NullValueError { .. }
56        | WinxError::ArgumentParseError(_)
57        | WinxError::JsonParseError(_)
58        | WinxError::DeserializationError(_)
59        | WinxError::WorkspacePathError(_)
60        | WinxError::InvalidInput(_)
61        | WinxError::ParseError(_)
62        | WinxError::FileAccessError { .. }
63        | WinxError::RecoverableSuggestionError { .. }
64        | WinxError::SearchReplaceSyntaxError(_)
65        | WinxError::SearchReplaceSyntaxErrorDetailed { .. }
66        | WinxError::SearchBlockNotFound(_)
67        | WinxError::SearchBlockAmbiguous { .. }
68        | WinxError::FileTooLarge { .. }
69        | WinxError::InteractiveCommandDetected { .. }
70        | WinxError::CommandAlreadyRunning { .. } => McpError::invalid_request(msg, None),
71        // Server-caused: genuine internal faults the model cannot fix. -> internal_error
72        WinxError::ShellInitializationError(_)
73        | WinxError::BashStateLockError(_)
74        | WinxError::CommandExecutionError(_)
75        | WinxError::SerializationError(_)
76        | WinxError::FileWriteError { .. }
77        | WinxError::DataLoadingError(_)
78        | WinxError::ContextSaveError(_)
79        | WinxError::CommandTimeout { .. }
80        | WinxError::ProcessCleanupError { .. }
81        | WinxError::BufferOverflow { .. }
82        | WinxError::SessionRecoveryError { .. }
83        | WinxError::ResourceAllocationError { .. }
84        | WinxError::IoError(_)
85        | WinxError::ConfigurationError(_)
86        | WinxError::FileError(_) => McpError::internal_error(msg, None),
87    }
88}
89
90/// Type alias for the shared bash state - uses `tokio::sync::Mutex` for async safety
91pub type SharedBashState = Arc<Mutex<Option<BashState>>>;
92
93/// Helper function to create JSON schema from schemars Schema
94fn schema_to_input_schema<T: schemars::JsonSchema>() -> Arc<serde_json::Map<String, Value>> {
95    let schema = schema_for!(T);
96    let mut value = serde_json::to_value(schema).unwrap_or(Value::Object(serde_json::Map::new()));
97    // schemars stamps a redundant `title` (usually just the type/field name) on
98    // every schema node; the LLM pays tokens for it on every tool call for zero
99    // signal. Strip it — context-aware, so a user data field literally named
100    // "title" is never touched.
101    strip_schema_titles(&mut value);
102    match value {
103        Value::Object(map) => Arc::new(map),
104        _ => Arc::new(serde_json::Map::new()),
105    }
106}
107
108/// Recursively remove `title` keys from JSON-Schema nodes only.
109///
110/// A dict is treated as a schema node when it carries a schema-shaped key
111/// (`type`/`$ref`/`properties`/`items`/`enum`/`const`/`anyOf`/`allOf`/`oneOf`/
112/// `additionalProperties`). This mirrors wcgw's `recursive_purge_dict_key` so a
113/// property whose *name* is "title" keeps its value.
114fn strip_schema_titles(value: &mut Value) {
115    match value {
116        Value::Object(map) => {
117            const SCHEMA_KEYS: &[&str] = &[
118                "type",
119                "$ref",
120                "properties",
121                "items",
122                "additionalProperties",
123                "enum",
124                "const",
125                "anyOf",
126                "allOf",
127                "oneOf",
128            ];
129            if SCHEMA_KEYS.iter().any(|k| map.contains_key(*k)) {
130                map.remove("title");
131            }
132            for child in map.values_mut() {
133                strip_schema_titles(child);
134            }
135        }
136        Value::Array(items) => {
137            for item in items {
138                strip_schema_titles(item);
139            }
140        }
141        _ => {}
142    }
143}
144
145fn mcp_tool<T: schemars::JsonSchema>(
146    name: &'static str,
147    description: &'static str,
148    annotations: ToolAnnotations,
149) -> Tool {
150    Tool::new(name, description, schema_to_input_schema::<T>()).with_annotations(annotations)
151}
152
153const INITIALIZE_DESCRIPTION: &str =
154    "- Always call this at the start of the conversation before using any of the shell tools from wcgw. \
155     - Use `any_workspace_path` to initialize the shell in the appropriate project directory. \
156     - If the user has mentioned a workspace or project root or any other file or folder use it to set `any_workspace_path`. \
157     - If user has mentioned any files use `initial_files_to_read` to read, use absolute paths only (~ allowed) \
158     - By default use mode \"wcgw\" \
159     - In \"code-writer\" mode, set the commands and globs which user asked to set, otherwise use 'all'. \
160     - Use type=\"first_call\" if it's the first call to this tool. \
161     - Use type=\"user_asked_mode_change\" if in a conversation user has asked to change mode. \
162     - Use type=\"reset_shell\" if in a conversation shell is not working after multiple tries. \
163     - Use type=\"user_asked_change_workspace\" if in a conversation user asked to change workspace";
164
165const BASH_COMMAND_DESCRIPTION: &str =
166    "- Execute a bash command. This is stateful (beware with subsequent calls). \
167     - Accepted payloads include action_json with an explicit type, action_json shorthand such as {\"command\":\"pwd\"}, or top-level shorthand such as {\"command\":\"pwd\"}. \
168     - Status of the command and the current working directory will always be returned at the end. \
169     - The first or the last line might be `(...truncated)` if the output is too long. \
170     - Always run `pwd` if you get any file or directory not found error to make sure you're not lost. \
171     - Do not run bg commands using \"&\", instead use this tool. \
172     - You must not use echo/cat to read/write files, use ReadFiles/FileWriteOrEdit \
173     - In order to check status of previous command, use `status_check` with empty command argument. \
174     - Only command is allowed to run at a time. You need to wait for any previous command to finish before running a new one. \
175     - Programs don't hang easily, so most likely explanation for no output is usually that the program is still running, and you need to check status again. \
176     - Do not send Ctrl-c before checking for status till 10 minutes or whatever is appropriate for the program to finish. \
177     - Only run long running commands in background. Each background command is run in a new non-reusable shell. \
178     - On running a bg command you'll get a bg command id that you should use to get status or interact. \
179     - Piloting an interactive full-screen TUI (the `claude` CLI, vim, htop, fzf, a REPL)? Run it in the background, then drive it with these two actions: \
180     - `screen` ({\"screen\":true,\"bg_command_id\":\"...\",\"lines\":N,\"diff\":true}) returns a STABLE snapshot of the live terminal screen (cursor moves, redraws, alternate-screen and synchronized-output already applied; ANSI stripped), with the cursor position in the header. Use this to read the current frame — unlike `status_check`, it never stacks redraw generations and never waits. Pass \"diff\":true to get back ONLY the lines that changed since your last `screen` look (large token savings when polling a TUI frame-by-frame; first look or a big change still returns the full frame). \
181     - `wait_for_turn` ({\"wait_for_turn\":true,\"bg_command_id\":\"...\",\"recognizer\":\"auto|claude|codex|antigravity|generic\",\"quiet_ms\":600,\"timeout_seconds\":30}) BLOCKS until the TUI finishes its turn and is ready for input, then returns the stable snapshot plus the detected state (busy / awaiting_input / awaiting_approval). Typical REPL loop: run the app in bg -> wait_for_turn -> send_text(submit:true) -> wait_for_turn -> screen, repeat.";
182
183const READ_FILES_DESCRIPTION: &str =
184    "- Read full file content of one or more files. \
185     - Prefer this over reading files with BashCommand (cat/head/tail): the output is token-budgeted and the read is recorded so FileWriteOrEdit can edit the file afterward. \
186     - Do NOT use this for binary files or images — use ReadImage for images. \
187     - Provide absolute paths only (~ allowed) \
188     - Only if the task requires line numbers understanding: \
189     - You may extract a range of lines. E.g., `/path/to/file:1-10` for lines 1-10. You can drop start or end like `/path/to/file:1-` or `/path/to/file:-10`";
190
191const FILE_WRITE_OR_EDIT_DESCRIPTION: &str =
192    "- Writes or edits a file based on the percentage of changes. \
193     - Prefer this over writing/editing files with BashCommand (echo/sed/redirects/heredocs). \
194     - For an edit, the file must have been read first with ReadFiles, otherwise the edit is rejected. \
195     - Use absolute path only (~ allowed). \
196     - First write down percentage of lines that need to be replaced in the file (between 0-100) in percentage_to_change \
197     - percentage_to_change should be low if mostly new code is to be added. It should be high if a lot of things are to be replaced. \
198     - If percentage_to_change > 50, provide full file content in text_or_search_replace_blocks \
199     - If percentage_to_change <= 50, text_or_search_replace_blocks should be search/replace blocks. \
200     \
201     Instructions for editing files. \
202     # Example \
203     ## Input file \
204     ``` \
205     import numpy as np \
206     from impls import impl1, impl2 \
207     \
208     def hello(): \
209         \"print a greeting\" \
210         print(\"hello\") \
211     \
212     def call_hello(): \
213         \"call hello\" \
214         hello() \
215         print(\"Called\") \
216         impl1() \
217         hello() \
218         impl2() \
219     ``` \
220     ## Edit format on the input file \
221     ``` \
222     <<<<<<< SEARCH \
223     from impls import impl1, impl2 \
224     ======= \
225     from impls import impl1, impl2 \
226     from hello import hello as hello_renamed \
227     >>>>>>> REPLACE \
228     <<<<<<< SEARCH \
229     def hello(): \
230         \"print a greeting\" \
231         print(\"hello\") \
232     ======= \
233     >>>>>>> REPLACE \
234     <<<<<<< SEARCH \
235     def call_hello(): \
236         \"call hello\" \
237         hello() \
238     ======= \
239     def call_hello_renamed(): \
240         \"call hello renamed\" \
241         hello_renamed() \
242     >>>>>>> REPLACE \
243     <<<<<<< SEARCH \
244     impl1() \
245     hello() \
246     impl2() \
247     ======= \
248     impl1() \
249     hello_renamed() \
250     impl2() \
251     >>>>>>> REPLACE \
252     ``` \
253     # *SEARCH/REPLACE block* Rules: \
254     Every \"<<<<<<< SEARCH\" section must *EXACTLY MATCH* the existing file content, character for character, including all comments, docstrings, whitespaces, etc. \
255     Including multiple unique *SEARCH/REPLACE* blocks if needed. \
256     Include enough and only enough lines in each SEARCH section to uniquely match each set of lines that need to change. \
257     Keep *SEARCH/REPLACE* blocks concise. \
258     Break large *SEARCH/REPLACE* blocks into a series of smaller blocks that each change a small portion of the file. \
259     Include just the changing lines, and a few surrounding lines (0-3 lines) if needed for uniqueness. \
260     Other than for uniqueness, avoid including those lines which do not change in search (and replace) blocks. Target 0-3 non trivial extra lines per block. \
261     Preserve leading spaces and indentations in both SEARCH and REPLACE blocks. \
262     If a short block would match multiple places, anchor it to a line number from ReadFiles instead of padding with context: write the marker as \"<<<<<<< SEARCH @42\" (or a range \"@42-50\") to target that 1-based location. A stale anchor falls back to the normal search, so it never makes a valid edit fail.";
263
264const CONTEXT_SAVE_DESCRIPTION: &str =
265    "Saves provided description and file contents of all the relevant file paths or globs in a single text file. \
266     - Provide random 3 word unqiue id or whatever user provided. \
267     - Leave project path as empty string if no project path";
268
269static WINX_TOOLS: OnceLock<Vec<Tool>> = OnceLock::new();
270static WINX_PROMPTS: OnceLock<Vec<Prompt>> = OnceLock::new();
271
272fn winx_tools() -> Vec<Tool> {
273    WINX_TOOLS.get_or_init(build_winx_tools).clone()
274}
275
276fn build_winx_tools() -> Vec<Tool> {
277    vec![
278        mcp_tool::<Initialize>(
279            "Initialize",
280            INITIALIZE_DESCRIPTION,
281            ToolAnnotations::new().read_only(true).open_world(false),
282        ),
283        mcp_tool::<BashCommand>(
284            "BashCommand",
285            BASH_COMMAND_DESCRIPTION,
286            ToolAnnotations::new().destructive(true).open_world(true),
287        ),
288        mcp_tool::<ReadFiles>(
289            "ReadFiles",
290            READ_FILES_DESCRIPTION,
291            ToolAnnotations::new().read_only(true).open_world(false),
292        ),
293        mcp_tool::<FileWriteOrEdit>(
294            "FileWriteOrEdit",
295            FILE_WRITE_OR_EDIT_DESCRIPTION,
296            ToolAnnotations::new().destructive(true).open_world(false),
297        ),
298        mcp_tool::<ContextSave>(
299            "ContextSave",
300            CONTEXT_SAVE_DESCRIPTION,
301            ToolAnnotations::new().destructive(false).open_world(false),
302        ),
303        mcp_tool::<ReadImage>(
304            "ReadImage",
305            "Read an image from the shell.",
306            ToolAnnotations::new().read_only(true).open_world(false),
307        ),
308    ]
309}
310
311fn winx_prompts() -> Vec<Prompt> {
312    WINX_PROMPTS
313        .get_or_init(|| {
314            vec![Prompt::new(
315                "KnowledgeTransfer",
316                Some("Summarize current Winx state, workspace context, and handoff notes."),
317                None,
318            )]
319        })
320        .clone()
321}
322
323fn append_command_section<const N: usize>(
324    output: &mut String,
325    title: &str,
326    cwd: &Path,
327    args: [&str; N],
328) {
329    let Ok(command_output) = Command::new("git").args(["-C"]).arg(cwd).args(args).output() else {
330        return;
331    };
332    if !command_output.status.success() {
333        return;
334    }
335
336    let content = String::from_utf8_lossy(&command_output.stdout);
337    if content.trim().is_empty() {
338        return;
339    }
340
341    let _ = writeln!(output, "\n# {title}\n{}", content.trim_end());
342}
343
344/// Upper bound on concurrently-live sessions. Each session owns a PTY (a real
345/// bash process), so we evict the least-recently-used one past this to avoid
346/// leaking shells across many short-lived `thread_id`s.
347const MAX_SESSIONS: usize = 32;
348
349/// Per-`thread_id` shell sessions. Each `thread_id` gets its own
350/// `BashState`/PTY, so concurrent threads (or HTTP clients sharing the service)
351/// never execute in each other's shell. Tools that don't carry a `thread_id`
352/// (legacy clients) fall back to the most recently active session.
353#[derive(Default)]
354struct SessionRegistry {
355    slots: HashMap<String, SharedBashState>,
356    /// Last-use timestamps for LRU eviction.
357    last_used: HashMap<String, Instant>,
358    /// In-flight operation count per session. A session whose count is > 0 (it
359    /// has a live [`SessionGuard`]) is never chosen as an LRU eviction victim, so
360    /// a long-running call can't have its shell pulled out from under it.
361    in_flight: HashMap<String, Arc<AtomicUsize>>,
362    /// Most recently addressed session, used as the fallback for tool calls
363    /// that omit a `thread_id`.
364    last_active: Option<String>,
365}
366
367/// RAII marker that a session has an operation in flight. Bumps the session's
368/// in-flight counter on creation and drops it on `Drop` — a plain synchronous
369/// `Drop`, so it works even though the registry behind it lives in an async
370/// `tokio::Mutex`. While any guard is alive the session is pinned against LRU
371/// eviction.
372struct SessionGuard {
373    counter: Arc<AtomicUsize>,
374}
375
376impl SessionGuard {
377    fn new(counter: Arc<AtomicUsize>) -> Self {
378        counter.fetch_add(1, Ordering::SeqCst);
379        Self { counter }
380    }
381}
382
383impl Drop for SessionGuard {
384    fn drop(&mut self) {
385        self.counter.fetch_sub(1, Ordering::SeqCst);
386    }
387}
388
389/// How an empty `thread_id` is resolved by the session registry.
390#[derive(Clone, Copy, PartialEq, Eq, Debug)]
391pub enum SessionIsolation {
392    /// Local stdio transport — a single client. An empty `thread_id` falls back
393    /// to the last-active session (legacy single-client convenience).
394    Lenient,
395    /// Remote HTTP transport — multiple clients behind one shared bearer token.
396    /// The last-active fallback is disabled, so an empty `thread_id` from one
397    /// client can never resolve to another client's shell; such calls get a
398    /// dedicated anonymous slot instead. Clients must use the `thread_id` that
399    /// `Initialize` hands back.
400    ///
401    /// Residual: two clients that deliberately send the *same* explicit
402    /// `thread_id` still share a shell. Closing that needs per-client tokens,
403    /// which the single shared-token model intentionally doesn't provide.
404    Strict,
405}
406
407/// Winx service. Holds the per-thread session registry.
408#[derive(Clone)]
409pub struct WinxService {
410    sessions: Arc<Mutex<SessionRegistry>>,
411    /// Version information for the service
412    pub version: String,
413    /// How empty `thread_id`s are resolved (see [`SessionIsolation`]).
414    isolation: SessionIsolation,
415}
416
417impl Default for WinxService {
418    fn default() -> Self {
419        Self::new()
420    }
421}
422
423impl WinxService {
424    /// Create a new `WinxService` for the local stdio transport (lenient,
425    /// single-client session isolation).
426    pub fn new() -> Self {
427        Self::with_isolation(SessionIsolation::Lenient)
428    }
429
430    /// Create a `WinxService` with an explicit session-isolation policy. The
431    /// HTTP transport uses [`SessionIsolation::Strict`].
432    pub fn with_isolation(isolation: SessionIsolation) -> Self {
433        info!(?isolation, "Creating new WinxService instance");
434        Self {
435            sessions: Arc::new(Mutex::new(SessionRegistry::default())),
436            version: env!("CARGO_PKG_VERSION").to_string(),
437            isolation,
438        }
439    }
440
441    /// Resolve the session slot for a `thread_id`, creating it if absent.
442    ///
443    /// An empty `thread_id` resolves, under [`SessionIsolation::Lenient`], to the
444    /// most recently active session (the compatibility path for tools — and older
445    /// clients — that don't send one); under [`SessionIsolation::Strict`] it gets
446    /// a dedicated anonymous slot so remote clients can't land in each other's shell.
447    /// Marks the slot as most-recently-used and evicts the LRU session when over
448    /// [`MAX_SESSIONS`].
449    async fn session_for(&self, thread_id: &str) -> (SharedBashState, SessionGuard) {
450        let mut reg = self.sessions.lock().await;
451        let key = if thread_id.is_empty() {
452            match self.isolation {
453                // Single local client: reuse the most recently active shell.
454                SessionIsolation::Lenient => {
455                    reg.last_active.clone().unwrap_or_else(|| "default".to_string())
456                }
457                // Many remote clients sharing one token: never resolve to
458                // someone else's active shell. Empty thread_id gets its own slot.
459                SessionIsolation::Strict => "anonymous".to_string(),
460            }
461        } else {
462            thread_id.to_string()
463        };
464
465        // Evict the LRU session if adding a brand-new key would exceed the cap —
466        // but never evict a session with an operation in flight (that would pull
467        // the shell out from under a concurrent long-running call). If every other
468        // session is busy we briefly exceed the cap rather than corrupt one.
469        if !reg.slots.contains_key(&key) && reg.slots.len() >= MAX_SESSIONS {
470            let victim = reg
471                .last_used
472                .iter()
473                .filter(|(k, _)| **k != key)
474                .filter(|(k, _)| {
475                    reg.in_flight.get(k.as_str()).map_or(0, |c| c.load(Ordering::SeqCst)) == 0
476                })
477                .min_by_key(|(_, t)| **t)
478                .map(|(k, _)| k.clone());
479            if let Some(victim) = victim {
480                reg.slots.remove(&victim);
481                reg.last_used.remove(&victim);
482                reg.in_flight.remove(&victim);
483                if reg.last_active.as_deref() == Some(victim.as_str()) {
484                    reg.last_active = None;
485                }
486                warn!("Evicted LRU shell session '{victim}' (session cap {MAX_SESSIONS})");
487            } else {
488                warn!(
489                    "All {MAX_SESSIONS} sessions busy; exceeding the cap rather than evicting an in-flight session"
490                );
491            }
492        }
493
494        let slot =
495            reg.slots.entry(key.clone()).or_insert_with(|| Arc::new(Mutex::new(None))).clone();
496        let counter = reg
497            .in_flight
498            .entry(key.clone())
499            .or_insert_with(|| Arc::new(AtomicUsize::new(0)))
500            .clone();
501        reg.last_used.insert(key.clone(), Instant::now());
502        if !thread_id.is_empty() {
503            reg.last_active = Some(key);
504        }
505        (slot, SessionGuard::new(counter))
506    }
507
508    /// The most recently active session slot, without creating one. Used by
509    /// session-agnostic surfaces (e.g. the handoff prompt).
510    async fn active_slot(&self) -> Option<SharedBashState> {
511        let reg = self.sessions.lock().await;
512        reg.last_active.as_ref().and_then(|key| reg.slots.get(key).cloned())
513    }
514}
515
516/// `ServerHandler` implementation
517impl ServerHandler for WinxService {
518    fn get_info(&self) -> ServerInfo {
519        ServerInfo::new(
520            ServerCapabilities::builder()
521                .enable_tools()
522                .enable_resources()
523                .enable_prompts()
524                .build(),
525        )
526        .with_server_info(
527            Implementation::new("winx-mcp-server", self.version.clone())
528                .with_title("Winx High-Performance MCP"),
529        )
530        .with_protocol_version(ProtocolVersion::V_2024_11_05)
531        .with_instructions(
532                "Winx is a high-performance Rust implementation of MCP tools for shell and file management."
533        )
534    }
535
536    async fn list_tools(
537        &self,
538        _request: Option<PaginatedRequestParams>,
539        _context: RequestContext<RoleServer>,
540    ) -> Result<ListToolsResult, McpError> {
541        Ok(ListToolsResult { tools: winx_tools(), next_cursor: None, meta: None })
542    }
543
544    async fn list_resources(
545        &self,
546        _param: Option<PaginatedRequestParams>,
547        _context: RequestContext<RoleServer>,
548    ) -> Result<ListResourcesResult, McpError> {
549        Ok(ListResourcesResult {
550            resources: vec![Annotated {
551                raw: RawResource {
552                    uri: "file://readme".into(),
553                    name: "README".into(),
554                    description: Some("Project README documentation".into()),
555                    mime_type: Some("text/markdown".into()),
556                    size: None,
557                    title: None,
558                    icons: None,
559                    meta: None,
560                },
561                annotations: None,
562            }],
563            next_cursor: None,
564            meta: None,
565        })
566    }
567
568    async fn list_prompts(
569        &self,
570        _request: Option<PaginatedRequestParams>,
571        _context: RequestContext<RoleServer>,
572    ) -> Result<ListPromptsResult, McpError> {
573        Ok(ListPromptsResult { prompts: winx_prompts(), next_cursor: None, meta: None })
574    }
575
576    async fn get_prompt(
577        &self,
578        request: GetPromptRequestParams,
579        _context: RequestContext<RoleServer>,
580    ) -> Result<GetPromptResult, McpError> {
581        if request.name != "KnowledgeTransfer" {
582            return Err(McpError::invalid_request(
583                format!("Unknown prompt: {}", request.name),
584                None,
585            ));
586        }
587
588        let text = self.knowledge_transfer_prompt_text().await;
589
590        Ok(GetPromptResult::new(vec![PromptMessage::new_text(PromptMessageRole::User, text)])
591            .with_description("Knowledge transfer handoff prompt"))
592    }
593
594    async fn read_resource(
595        &self,
596        param: ReadResourceRequestParams,
597        _context: RequestContext<RoleServer>,
598    ) -> Result<ReadResourceResult, McpError> {
599        let content = match param.uri.as_ref() {
600            "file://readme" => match tokio::fs::read_to_string("README.md").await {
601                Ok(content) => vec![ResourceContents::text(content, param.uri.clone())],
602                Err(_) => vec![ResourceContents::text(
603                    "README.md not found".to_string(),
604                    param.uri.clone(),
605                )],
606            },
607            _ => {
608                return Err(McpError::invalid_request(
609                    format!("Unknown resource URI: {}", param.uri),
610                    None,
611                ));
612            }
613        };
614
615        Ok(ReadResourceResult::new(content))
616    }
617
618    async fn call_tool(
619        &self,
620        param: CallToolRequestParams,
621        _context: RequestContext<RoleServer>,
622    ) -> Result<CallToolResult, McpError> {
623        let tool = param.name.to_string();
624        let args_value = param.arguments.map(Value::Object);
625        // Audit trail: one structured line per tool call, including the outcome
626        // and wall-clock. Successes were previously silent — only errors logged —
627        // which made debugging remote (ChatGPT) sessions guesswork.
628        let summary = audit_summary(&tool, args_value.as_ref());
629        let started = std::time::Instant::now();
630
631        let result = match tool.as_str() {
632            "Initialize" => self.handle_initialize(args_value).await,
633            "BashCommand" => self.handle_bash_command(args_value).await,
634            "ReadFiles" => self.handle_read_files(args_value).await,
635            "FileWriteOrEdit" => self.handle_file_write_or_edit(args_value).await,
636            "ContextSave" => self.handle_context_save(args_value).await,
637            "ReadImage" => self.handle_read_image(args_value).await,
638            _ => Err(McpError::invalid_request(format!("Unknown tool: {tool}"), None)),
639        };
640
641        let ms = started.elapsed().as_millis();
642        match &result {
643            Ok(_) => info!(tool = %tool, ms, "tool call ok — {summary}"),
644            Err(error) => warn!(tool = %tool, ms, "tool call error — {summary}: {}", error.message),
645        }
646        result
647    }
648}
649
650/// Build a short, non-sensitive audit summary of a tool call's arguments.
651fn audit_summary(tool: &str, args: Option<&Value>) -> String {
652    let Some(args) = args else {
653        return "(no args)".to_string();
654    };
655    let s = |key: &str| args.get(key).and_then(Value::as_str).unwrap_or("").to_string();
656    let clip = |text: String| text.chars().take(100).collect::<String>();
657    match tool {
658        "BashCommand" => {
659            let action = args.get("action_json");
660            let cmd = action
661                .and_then(|a| a.get("command"))
662                .and_then(Value::as_str)
663                .or_else(|| args.get("command").and_then(Value::as_str));
664            if let Some(cmd) = cmd {
665                format!("cmd={:?}", clip(cmd.to_string()))
666            } else {
667                let kind =
668                    action.and_then(|a| a.get("type")).and_then(Value::as_str).unwrap_or("?");
669                format!("action={kind}")
670            }
671        }
672        "FileWriteOrEdit" | "ReadImage" => format!("path={}", s("file_path")),
673        "ReadFiles" => {
674            format!(
675                "files={}",
676                args.get("file_paths").and_then(Value::as_array).map_or(0, Vec::len)
677            )
678        }
679        "Initialize" => format!("ws={} mode={}", s("any_workspace_path"), s("mode_name")),
680        "ContextSave" => format!("id={}", s("id")),
681        _ => String::new(),
682    }
683}
684
685impl WinxService {
686    async fn knowledge_transfer_prompt_text(&self) -> String {
687        let mut text = String::from(
688            "Prepare a concise handoff for another agent. Include active objective, current state, important files, changed files, blockers, validation already run, and exact next commands.\n",
689        );
690
691        let state_snapshot = if let Some(slot) = self.active_slot().await {
692            let guard = slot.lock().await;
693            guard.as_ref().map(|state| {
694                let whitelist = state
695                    .whitelist_for_overwrite
696                    .iter()
697                    .take(12)
698                    .map(|(path, data)| {
699                        format!(
700                            "- {} ({:.1}% read, {} lines)",
701                            path,
702                            data.get_percentage_read(),
703                            data.total_lines
704                        )
705                    })
706                    .collect::<Vec<_>>();
707                (
708                    state.current_thread_id.clone(),
709                    state.workspace_root.clone(),
710                    state.cwd.clone(),
711                    state.mode.to_string(),
712                    whitelist,
713                    state.whitelist_for_overwrite.len(),
714                )
715            })
716        } else {
717            None
718        };
719
720        let Some((thread_id, workspace_root, cwd, mode, whitelist, whitelist_count)) =
721            state_snapshot
722        else {
723            text.push_str("\n# Current Winx state\nWinx is not initialized.\n");
724            return text;
725        };
726
727        let _ = writeln!(
728            text,
729            "\n# Current Winx state\nThread: {thread_id}\nWorkspace: {}\nCwd: {}\nMode: {mode}\nWhitelisted files: {whitelist_count}",
730            workspace_root.display(),
731            cwd.display()
732        );
733
734        if !whitelist.is_empty() {
735            text.push_str("\n# Recently readable files\n");
736            text.push_str(&whitelist.join("\n"));
737            text.push('\n');
738        }
739
740        let active_files = crate::utils::workspace_stats::active_files(&workspace_root);
741        if !active_files.is_empty() {
742            text.push_str("\n# Active files by Winx usage\n");
743            for file in active_files.iter().take(12) {
744                let _ = writeln!(text, "- {file}");
745            }
746        }
747
748        if let Ok((repo_context, _)) = crate::utils::repo::get_repo_context(&workspace_root) {
749            let repo_excerpt = repo_context.lines().take(80).collect::<Vec<_>>().join("\n");
750            let _ = writeln!(text, "\n# Workspace context\n{repo_excerpt}");
751        }
752
753        append_command_section(&mut text, "Git status", &workspace_root, ["status", "--short"]);
754        append_command_section(
755            &mut text,
756            "Git diff stat",
757            &workspace_root,
758            ["diff", "--stat", "HEAD"],
759        );
760
761        // Sections the ContextSave `description` should contain, tailored to the
762        // mode: architect produces a plan (no edits), the others produce a status
763        // + pending-issues handoff (wcgw parity: WCGW_KT vs ARCHITECT_KT).
764        let sections = if mode == "architect" {
765            "\n# Sections for the ContextSave description (architect mode)\n\
766             - `# Objective` — project and task objective.\n\
767             - `# All user instructions` — everything the user asked, verbatim.\n\
768             - `# Designed plan` — the plan you designed, in detail.\n\
769             - Provide all relevant file paths so the next agent can resume; err toward more.\n"
770        } else {
771            "\n# Sections for the ContextSave description\n\
772             - `# Objective` — project and task objective.\n\
773             - `# All user instructions` — everything the user asked, verbatim.\n\
774             - `# Current status` — what's already done (not what's left).\n\
775             - `# Pending issues with snippets` — verbatim errors/tracebacks/commands; be verbose.\n\
776             - `# Build and development instructions` — how to build/run/test; leave empty if unknown.\n\
777             - Provide all relevant file paths so the next agent can resume; err toward more.\n"
778        };
779        text.push_str(sections);
780
781        text.push_str(
782            "\n# Handoff checklist\n- State what changed and why.\n- Include files touched and any user-owned dirty work to preserve.\n- Include validation commands already run and their result.\n- Include the next safest command to continue.\n",
783        );
784
785        text
786    }
787
788    async fn persist_state(&self, slot: &SharedBashState) {
789        let guard = slot.lock().await;
790        if let Some(state) = guard.as_ref() {
791            if let Err(error) = state.save_state_to_disk() {
792                warn!("Failed to persist bash state: {}", error);
793            }
794        }
795    }
796
797    /// Deserialize `args` into `T`, retrying once after JSON-decoding any string
798    /// field that is itself an encoded object/array. LLMs sometimes send a nested
799    /// param (e.g. `code_writer_config`) as a JSON string instead of an object;
800    /// wcgw applies the same leniency in its tool dispatch.
801    fn lenient_from_value<T: serde::de::DeserializeOwned>(
802        args: Value,
803    ) -> Result<T, serde_json::Error> {
804        match serde_json::from_value::<T>(args.clone()) {
805            Ok(value) => Ok(value),
806            Err(first_err) => {
807                let Value::Object(mut map) = args else {
808                    return Err(first_err);
809                };
810                let mut changed = false;
811                for value in map.values_mut() {
812                    if let Value::String(text) = value {
813                        if let Ok(parsed) = serde_json::from_str::<Value>(text) {
814                            if parsed.is_object() || parsed.is_array() {
815                                *value = parsed;
816                                changed = true;
817                            }
818                        }
819                    }
820                }
821                if changed {
822                    serde_json::from_value::<T>(Value::Object(map))
823                } else {
824                    Err(first_err)
825                }
826            }
827        }
828    }
829
830    async fn handle_initialize(&self, args: Option<Value>) -> Result<CallToolResult, McpError> {
831        let args = args.ok_or_else(|| McpError::invalid_request("Missing arguments", None))?;
832        let mut initialize: Initialize = Self::lenient_from_value(args).map_err(|e| {
833            McpError::invalid_request(format!("Invalid Initialize parameters: {e}"), None)
834        })?;
835
836        // Resolve the session key. A first_call may omit thread_id; generate one
837        // here and write it back so the handler and the registry agree on the id.
838        let mut thread_id = normalize_thread_id(&initialize.thread_id);
839        if thread_id.is_empty() {
840            thread_id = generate_thread_id();
841            initialize.thread_id.clone_from(&thread_id);
842        }
843        let (slot, _session_guard) = self.session_for(&thread_id).await;
844
845        match crate::tools::initialize::handle_tool_call(&slot, initialize).await {
846            Ok(result) => {
847                self.persist_state(&slot).await;
848                Ok(CallToolResult::success(vec![Content::text(result)]))
849            }
850            Err(e) => Err(to_mcp_error("Initialize", &e)),
851        }
852    }
853
854    async fn handle_bash_command(&self, args: Option<Value>) -> Result<CallToolResult, McpError> {
855        let args = args.ok_or_else(|| McpError::invalid_request("Missing arguments", None))?;
856        let bash_command: BashCommand = serde_json::from_value(args).map_err(|e| {
857            McpError::invalid_request(
858                format!(
859                    "Invalid BashCommand parameters: {e}. Accepted forms include {{\"action_json\": {{\"command\": \"pwd\"}}}}, {{\"command\": \"pwd\"}}, or {{\"action_json\": {{\"type\": \"status_check\", \"status_check\": true}}}}."
860                ),
861                None,
862            )
863        })?;
864
865        let (slot, _session_guard) =
866            self.session_for(&normalize_thread_id(&bash_command.thread_id)).await;
867        match crate::tools::bash_command::handle_tool_call(&slot, bash_command).await {
868            Ok(output) => {
869                self.persist_state(&slot).await;
870                Ok(CallToolResult::success(vec![Content::text(output)]))
871            }
872            Err(e) => Err(to_mcp_error("BashCommand", &e)),
873        }
874    }
875
876    async fn handle_read_files(&self, args: Option<Value>) -> Result<CallToolResult, McpError> {
877        let args = args.ok_or_else(|| McpError::invalid_request("Missing arguments", None))?;
878        let read_files: ReadFiles = Self::lenient_from_value(args).map_err(|e| {
879            McpError::invalid_request(format!("Invalid ReadFiles parameters: {e}"), None)
880        })?;
881
882        let (slot, _session_guard) =
883            self.session_for(&normalize_thread_id(&read_files.thread_id)).await;
884        match crate::tools::read_files::handle_tool_call(&slot, read_files).await {
885            Ok(result) => {
886                self.persist_state(&slot).await;
887                Ok(CallToolResult::success(vec![Content::text(result)]))
888            }
889            Err(e) => Err(to_mcp_error("ReadFiles", &e)),
890        }
891    }
892
893    async fn handle_file_write_or_edit(
894        &self,
895        args: Option<Value>,
896    ) -> Result<CallToolResult, McpError> {
897        let args = args.ok_or_else(|| McpError::invalid_request("Missing arguments", None))?;
898        let file_write_or_edit: FileWriteOrEdit = Self::lenient_from_value(args).map_err(|e| {
899            McpError::invalid_request(format!("Invalid FileWriteOrEdit parameters: {e}"), None)
900        })?;
901
902        let (slot, _session_guard) =
903            self.session_for(&normalize_thread_id(&file_write_or_edit.thread_id)).await;
904        match crate::tools::file_write_or_edit::handle_tool_call(&slot, file_write_or_edit).await {
905            Ok(result) => {
906                self.persist_state(&slot).await;
907                Ok(CallToolResult::success(vec![Content::text(result)]))
908            }
909            Err(e) => Err(to_mcp_error("FileWriteOrEdit", &e)),
910        }
911    }
912
913    async fn handle_context_save(&self, args: Option<Value>) -> Result<CallToolResult, McpError> {
914        let args = args.ok_or_else(|| McpError::invalid_request("Missing arguments", None))?;
915        let context_save: ContextSave = Self::lenient_from_value(args).map_err(|e| {
916            McpError::invalid_request(format!("Invalid ContextSave parameters: {e}"), None)
917        })?;
918
919        let (slot, _session_guard) =
920            self.session_for(&normalize_thread_id(&context_save.thread_id)).await;
921        match crate::tools::context_save::handle_tool_call(&slot, context_save).await {
922            Ok(result) => {
923                self.persist_state(&slot).await;
924                Ok(CallToolResult::success(vec![Content::text(result)]))
925            }
926            Err(e) => Err(to_mcp_error("ContextSave", &e)),
927        }
928    }
929
930    async fn handle_read_image(&self, args: Option<Value>) -> Result<CallToolResult, McpError> {
931        let args = args.ok_or_else(|| McpError::invalid_request("Missing arguments", None))?;
932        let read_image: ReadImage = Self::lenient_from_value(args).map_err(|e| {
933            McpError::invalid_request(format!("Invalid ReadImage parameters: {e}"), None)
934        })?;
935
936        let (slot, _session_guard) =
937            self.session_for(&normalize_thread_id(&read_image.thread_id)).await;
938        match crate::tools::read_image::handle_tool_call(&slot, read_image).await {
939            Ok((mime_type, base64_data)) => {
940                self.persist_state(&slot).await;
941                // Return a real image content block (not base64 as text) so the
942                // model can actually see the image. rmcp's `Content::image`
943                // takes (data, mime_type).
944                Ok(CallToolResult::success(vec![Content::image(base64_data, mime_type)]))
945            }
946            Err(e) => Err(to_mcp_error("ReadImage", &e)),
947        }
948    }
949}
950
951/// Create and start the Winx MCP server
952pub async fn start_winx_server() -> Result<(), Box<dyn std::error::Error>> {
953    info!("Starting Winx MCP Server");
954    let service = WinxService::new();
955    let server = service.serve(stdio()).await?;
956    server.waiting().await?;
957    Ok(())
958}
959
960#[cfg(test)]
961mod session_registry_tests {
962    use super::*;
963
964    #[tokio::test]
965    async fn distinct_threads_get_distinct_sessions() {
966        let svc = WinxService::new();
967        let (a, _) = svc.session_for("thread_a").await;
968        let (b, _) = svc.session_for("thread_b").await;
969        // Two thread_ids must own two separate slots — the whole point of the
970        // registry: thread B never executes in thread A's shell.
971        assert!(!Arc::ptr_eq(&a, &b));
972        // Same id round-trips to the same slot.
973        let (a2, _) = svc.session_for("thread_a").await;
974        assert!(Arc::ptr_eq(&a, &a2));
975    }
976
977    #[tokio::test]
978    async fn empty_thread_id_falls_back_to_last_active() {
979        let svc = WinxService::new();
980        let (_a, _) = svc.session_for("thread_a").await;
981        let (b, _) = svc.session_for("thread_b").await; // now last-active
982                                                        // A tool call without a thread_id reuses the most recently active slot.
983        let (fallback, _) = svc.session_for("").await;
984        assert!(Arc::ptr_eq(&b, &fallback));
985        assert!(svc.active_slot().await.is_some());
986    }
987
988    #[tokio::test]
989    async fn strict_isolation_empty_thread_id_does_not_steal_active_session() {
990        let svc = WinxService::with_isolation(SessionIsolation::Strict);
991        let (a, _) = svc.session_for("thread_a").await; // would be "last-active" under Lenient
992        let (anon, _) = svc.session_for("").await;
993        // Strict mode: an empty thread_id must NOT resolve to another client's shell.
994        assert!(!Arc::ptr_eq(&a, &anon));
995        // Anonymous calls share one dedicated slot rather than hijacking named ones.
996        let (anon2, _) = svc.session_for("").await;
997        assert!(Arc::ptr_eq(&anon, &anon2));
998        // Explicit thread_ids stay isolated as always.
999        let (b, _) = svc.session_for("thread_b").await;
1000        assert!(!Arc::ptr_eq(&a, &b));
1001    }
1002
1003    #[tokio::test]
1004    async fn lru_eviction_caps_live_sessions() {
1005        let svc = WinxService::new();
1006        for i in 0..(MAX_SESSIONS + 5) {
1007            let (_, _) = svc.session_for(&format!("t{i}")).await;
1008        }
1009        let reg = svc.sessions.lock().await;
1010        assert!(reg.slots.len() <= MAX_SESSIONS, "session count {} over cap", reg.slots.len());
1011    }
1012
1013    #[tokio::test]
1014    async fn in_flight_session_is_not_evicted() {
1015        let svc = WinxService::new();
1016        // "keep" is created first (so it's the LRU candidate) and held busy.
1017        let (_keep_slot, _keep_guard) = svc.session_for("keep").await;
1018        // Saturate the cap and then churn well past it; eviction must skip the
1019        // in-flight "keep" and evict idle fillers instead.
1020        for i in 0..(MAX_SESSIONS + 10) {
1021            let (_, _) = svc.session_for(&format!("filler{i}")).await;
1022        }
1023        let reg = svc.sessions.lock().await;
1024        assert!(
1025            reg.slots.contains_key("keep"),
1026            "an in-flight session must survive LRU eviction churn"
1027        );
1028    }
1029}
1030
1031#[cfg(test)]
1032mod schema_tests {
1033    use super::{schema_to_input_schema, strip_schema_titles};
1034    use serde_json::json;
1035
1036    #[test]
1037    fn strips_titles_from_schema_nodes_only() {
1038        let mut v = json!({
1039            "type": "object",
1040            "title": "ShouldGo",
1041            "properties": {
1042                // a user field literally named "title" must survive as a key,
1043                // and its inner schema's own title must be stripped.
1044                "title": { "type": "string", "title": "InnerGoes" }
1045            }
1046        });
1047        strip_schema_titles(&mut v);
1048        assert!(v.get("title").is_none(), "schema-node title not stripped");
1049        let props = v.get("properties").and_then(serde_json::Value::as_object);
1050        assert!(
1051            props.is_some_and(|p| p.contains_key("title")),
1052            "property key named 'title' must be preserved"
1053        );
1054        assert!(
1055            props.and_then(|p| p.get("title")).and_then(|t| t.get("title")).is_none(),
1056            "inner schema title not stripped"
1057        );
1058    }
1059
1060    #[test]
1061    fn real_tool_schema_carries_no_titles() {
1062        let schema = schema_to_input_schema::<crate::types::Initialize>();
1063        let blob = serde_json::to_string(&*schema).unwrap_or_default();
1064        assert!(!blob.contains("\"title\""), "tool schema still contains titles: {blob}");
1065    }
1066}
1067
1068#[cfg(test)]
1069mod error_mapping_tests {
1070    use super::*;
1071    use rmcp::model::ErrorCode;
1072    use std::path::PathBuf;
1073
1074    fn code_of(err: &WinxError) -> ErrorCode {
1075        to_mcp_error("Tool", err).code
1076    }
1077
1078    #[test]
1079    fn client_caused_errors_map_to_invalid_request() {
1080        // A validation suggestion is the model's to fix, not a server fault.
1081        assert_eq!(
1082            code_of(&WinxError::RecoverableSuggestionError {
1083                message: "bad arg".into(),
1084                suggestion: "try x".into(),
1085            }),
1086            ErrorCode::INVALID_REQUEST,
1087        );
1088        // Parse failures come from the model's input.
1089        assert_eq!(
1090            code_of(&WinxError::ParseError("unexpected token".into())),
1091            ErrorCode::INVALID_REQUEST,
1092        );
1093        // A bad path the model handed us is something it can correct.
1094        assert_eq!(
1095            code_of(&WinxError::FileAccessError {
1096                path: PathBuf::from("/nope"),
1097                message: "no such file".into(),
1098            }),
1099            ErrorCode::INVALID_REQUEST,
1100        );
1101    }
1102
1103    #[test]
1104    fn server_caused_errors_stay_internal_error() {
1105        assert_eq!(
1106            code_of(&WinxError::IoError(std::io::Error::other("disk gone"))),
1107            ErrorCode::INTERNAL_ERROR,
1108        );
1109        assert_eq!(
1110            code_of(&WinxError::BashStateLockError("poisoned".into())),
1111            ErrorCode::INTERNAL_ERROR,
1112        );
1113    }
1114}