Skip to main content

powershell_mcp/
server.rs

1//! MCP server handler — the three query tools, wired to the RAG store.
2//!
3//! Tool results are returned as pretty-printed JSON in a text content
4//! block, or isError with "Error executing <name>: ..." on failure. The
5//! index is loaded once per process and cached.
6
7use std::path::PathBuf;
8use std::sync::{Arc, Mutex};
9
10use rmcp::{
11    handler::server::wrapper::Parameters,
12    model::{CallToolResult, ContentBlock, ServerCapabilities, ServerInfo},
13    schemars, tool, tool_handler, tool_router, ServerHandler,
14};
15use serde::Deserialize;
16use serde_json::{json, Value};
17
18use crate::rag::{self, LoadedRag, QueryMode};
19use crate::SERVER_NAME;
20
21/// Wrap a tool result into an MCP response: success is a pretty-printed
22/// JSON text block; failure is isError with the exact message.
23fn tool_result(name: &str, result: Result<Value, String>) -> CallToolResult {
24    match result {
25        Ok(v) => {
26            let text = serde_json::to_string_pretty(&v).unwrap_or_else(|_| "{}".into());
27            CallToolResult::success(vec![ContentBlock::text(text)])
28        }
29        Err(message) => CallToolResult::error(vec![ContentBlock::text(format!(
30            "Error executing {}: {}",
31            name, message
32        ))]),
33    }
34}
35
36/// MCP server. Holds the resolved RAG data directory and a lazily-loaded
37/// index cache.
38pub struct PwshServer {
39    rag_root: PathBuf,
40    rag_cache: Arc<Mutex<Option<Arc<LoadedRag>>>>,
41}
42
43impl PwshServer {
44    pub fn new() -> anyhow::Result<Self> {
45        Ok(Self {
46            rag_root: rag::rag_dir(),
47            rag_cache: Arc::new(Mutex::new(None)),
48        })
49    }
50
51    /// Load (once) and return the semantic index, erroring when it has not
52    /// been built yet.
53    fn loaded_rag(&self) -> Result<Arc<LoadedRag>, String> {
54        let mut cache = self.rag_cache.lock().unwrap_or_else(|e| e.into_inner());
55        if let Some(loaded) = cache.as_ref() {
56            return Ok(loaded.clone());
57        }
58        let loaded = rag::load(&self.rag_root).map_err(|e| e.to_string())?;
59        let arc = Arc::new(loaded);
60        *cache = Some(arc.clone());
61        Ok(arc)
62    }
63
64    fn do_search(&self, query: &str, mode: QueryMode, k: usize) -> Result<Value, String> {
65        let loaded = self.loaded_rag()?;
66        let query_embedding: Option<Vec<f32>> = match mode {
67            QueryMode::Bm25 => None,
68            QueryMode::Vector | QueryMode::Hybrid => {
69                rag::ensure_model_matches(&loaded).map_err(|e| e.to_string())?;
70                let model = crate::embed::current_model();
71                let prefix = if model.uses_prefixes() {
72                    crate::embed::QUERY_PREFIX
73                } else {
74                    ""
75                };
76                let texts = vec![format!("{prefix}{query}")];
77                let embedded = crate::embed::embed_texts(&texts).map_err(|e| e.to_string())?;
78                embedded.first().cloned()
79            }
80        };
81        let hits = rag::retrieve(
82            &loaded,
83            &self.rag_root,
84            query,
85            mode,
86            k,
87            query_embedding.as_deref(),
88        )
89        .map_err(|e| e.to_string())?;
90        Ok(json!(hits
91            .iter()
92            .map(rag::scored_chunk_to_json)
93            .collect::<Vec<_>>()))
94    }
95
96    fn do_file_context(&self, file: &str) -> Result<Value, String> {
97        let loaded = self.loaded_rag()?;
98        let chunks: Vec<Value> = rag::file_context(&loaded, file)
99            .iter()
100            .map(|c| {
101                json!({
102                    "i": c.i,
103                    "file": c.file,
104                    "line_start": c.line_start,
105                    "line_end": c.line_end,
106                    "text": c.text,
107                })
108            })
109            .collect();
110        Ok(json!(chunks))
111    }
112
113    fn do_index_info(&self) -> Result<Value, String> {
114        let loaded = self.loaded_rag()?;
115        Ok(json!({
116            "root": self.rag_root.display().to_string(),
117            "version": loaded.manifest.version,
118            "model": loaded.manifest.model,
119            "dim": loaded.manifest.dim,
120            "chunk_count": loaded.manifest.chunk_count,
121            "file_count": loaded.manifest.file_count,
122            "built_at": loaded.manifest.built_at,
123            "project_root": loaded.manifest.project_root,
124            "source_fingerprint": loaded.manifest.source_fingerprint,
125        }))
126    }
127}
128
129// ---------------------------------------------------------------------------
130// Request types (serde + schemars, doc comments on every field)
131// ---------------------------------------------------------------------------
132
133#[derive(Debug, Deserialize, schemars::JsonSchema)]
134struct SearchRequest {
135    /// The question or keywords to search the PowerShell documentation for.
136    query: String,
137    /// hybrid (default, BM25 + vector fused), vector (semantic only), or
138    /// bm25 (exact keyword, no model needed).
139    mode: Option<String>,
140    /// Number of results to return, default 5, max 20.
141    k: Option<u32>,
142}
143
144#[derive(Debug, Deserialize, schemars::JsonSchema)]
145struct FileContextRequest {
146    /// Path relative to the corpus root, exactly as returned by search
147    /// results (forward slashes).
148    file: String,
149}
150
151#[derive(Debug, Deserialize, schemars::JsonSchema)]
152struct NoParams {}
153
154// ---------------------------------------------------------------------------
155// Tools
156// ---------------------------------------------------------------------------
157
158#[tool_router]
159impl PwshServer {
160    #[tool(
161        description = "Search the PowerShell documentation corpus (cmdlet reference, about topics, and conceptual guides from MicrosoftDocs/PowerShell-Docs) with a hybrid BM25 + vector index and return the most relevant chunks with file and line provenance. mode: hybrid (default), vector, or bm25. k: number of results, default 5, max 20. Use for questions about PowerShell cmdlets, syntax, parameters, concepts, or behavior."
162    )]
163    async fn search(
164        &self,
165        Parameters(SearchRequest { query, mode, k }): Parameters<SearchRequest>,
166    ) -> CallToolResult {
167        let mode = mode
168            .as_deref()
169            .map(QueryMode::parse)
170            .unwrap_or(QueryMode::Hybrid);
171        let k = k.map(|v| v as usize).unwrap_or(rag::DEFAULT_K);
172        tool_result("search", self.do_search(&query, mode, k))
173    }
174
175    #[tool(
176        description = "Return every indexed chunk of one documentation file, in source order, with line ranges. file is the path relative to the corpus root, exactly as returned by search results (for example reference/7.4/Microsoft.PowerShell.Core/Get-Command.md)."
177    )]
178    async fn file_context(
179        &self,
180        Parameters(FileContextRequest { file }): Parameters<FileContextRequest>,
181    ) -> CallToolResult {
182        tool_result("file_context", self.do_file_context(&file))
183    }
184
185    #[tool(
186        description = "Report the state of the semantic index this server serves: model, dimensions, chunk and file counts, built-at time, corpus root, and source fingerprint. Errors clearly when no index has been built yet."
187    )]
188    async fn index_info(&self, Parameters(NoParams {}): Parameters<NoParams>) -> CallToolResult {
189        tool_result("index_info", self.do_index_info())
190    }
191}
192
193// ---------------------------------------------------------------------------
194// Handler
195// ---------------------------------------------------------------------------
196
197#[tool_handler]
198impl ServerHandler for PwshServer {
199    fn get_info(&self) -> ServerInfo {
200        ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
201            .with_server_info(rmcp::model::Implementation::new(
202                SERVER_NAME,
203                env!("CARGO_PKG_VERSION"),
204            ))
205            .with_instructions(
206                "Hybrid RAG over the official PowerShell documentation: search returns the \
207                 most relevant chunks (BM25 + vector fused) with file and line provenance, \
208                 file_context returns every chunk of one file, index_info reports the index \
209                 state. Run `powershell-mcp build-index <corpus-root>` first if search errors.",
210            )
211    }
212}