Skip to main content

mq_mcp/
server.rs

1use crate::{
2    check::{self, DRY_RUN_SAMPLES, DryRun, QueryCheck},
3    files::FileAccess,
4    outline::{self, FrontmatterResult, Outline},
5    output::{self, DEFAULT_MAX_OUTPUT_CHARS, MIN_OUTPUT_CHARS, OutputOptions},
6};
7use miette::miette;
8use rmcp::{
9    ErrorData, ServerHandler, ServiceExt,
10    handler::server::{tool::ToolRouter, wrapper::Parameters},
11    model::{CallToolResult, ContentBlock, ProtocolVersion, ServerCapabilities, ServerConfig},
12    schemars, tool, tool_handler, tool_router,
13    transport::streamable_http_server::{
14        StreamableHttpServerConfig, StreamableHttpService, session::local::LocalSessionManager,
15    },
16};
17use std::{sync::Arc, time::Duration};
18use tokio::io::{stdin, stdout};
19type McpResult = Result<CallToolResult, ErrorData>;
20
21/// Default per-query timeout, applied when neither the CLI nor the tool call
22/// overrides it.
23pub const DEFAULT_TIMEOUT_MS: u64 = 10_000;
24/// Default upper bound for a per-call `timeout_ms`, so a client can't lift the
25/// server's limit arbitrarily.
26pub const DEFAULT_MAX_TIMEOUT_MS: u64 = 60_000;
27
28/// Extensions `list_files` looks for when the caller doesn't ask for others.
29const DEFAULT_LIST_EXTENSIONS: &[&str] = &["md", "markdown", "mdx"];
30/// Entries `list_files` returns when the caller doesn't set a limit, and the most it ever returns.
31const DEFAULT_LIST_LIMIT: usize = 200;
32const MAX_LIST_LIMIT: usize = 1000;
33
34/// Limits applied to every mq engine and every tool result the server produces.
35#[derive(Debug, Clone)]
36pub struct EngineConfig {
37    /// Timeout used when a tool call doesn't pass `timeout_ms`.
38    pub timeout: Duration,
39    /// Largest timeout a tool call may request; larger values are clamped.
40    pub max_timeout: Duration,
41    /// Maximum call stack depth for the mq evaluator (`None` = mq-lang default).
42    pub max_call_stack_depth: Option<u32>,
43    /// Most characters a single tool call returns; a call may ask for less via `max_output_chars`.
44    pub max_output_chars: usize,
45    /// Directories the `path` parameter may read from. No roots disables file access.
46    pub files: FileAccess,
47}
48
49impl Default for EngineConfig {
50    fn default() -> Self {
51        Self {
52            timeout: Duration::from_millis(DEFAULT_TIMEOUT_MS),
53            max_timeout: Duration::from_millis(DEFAULT_MAX_TIMEOUT_MS),
54            max_call_stack_depth: None,
55            max_output_chars: DEFAULT_MAX_OUTPUT_CHARS,
56            files: FileAccess::default(),
57        }
58    }
59}
60
61#[derive(Clone, Default)]
62pub struct Server {
63    pub tool_router: ToolRouter<Self>,
64    config: EngineConfig,
65}
66
67/// A Markdown document, given inline or as a file under an allowed directory.
68#[derive(Debug, Default, rmcp::serde::Deserialize, schemars::JsonSchema)]
69struct DocumentInput {
70    #[schemars(description = "The markdown content to process. Give either `markdown` or `path`.")]
71    markdown: Option<String>,
72    #[schemars(
73        description = "Path of a Markdown file to read instead of passing `markdown`; avoids sending large documents through the conversation. Must be inside a directory the server allows (see list_files); relative paths are resolved against those directories."
74    )]
75    path: Option<String>,
76}
77
78#[derive(Debug, rmcp::serde::Deserialize, schemars::JsonSchema)]
79struct QueryForHtml {
80    #[schemars(description = "The HTML to process. Give either `html` or `path`.")]
81    html: Option<String>,
82    #[schemars(
83        description = "Path of an HTML file to read instead of passing `html`. Must be inside a directory the server allows (see list_files)."
84    )]
85    path: Option<String>,
86    #[schemars(
87        description = "The mq query to execute. Selectors and functions listed in the available_selectors and available_functions tools can be used."
88    )]
89    query: Option<String>,
90    #[schemars(
91        description = "Optional timeout for this query in milliseconds. Defaults to the server's configured timeout and is capped at the server's maximum."
92    )]
93    timeout_ms: Option<u64>,
94    #[serde(flatten)]
95    output: OutputOptions,
96}
97
98#[derive(Debug, rmcp::serde::Deserialize, schemars::JsonSchema)]
99struct QueryForMarkdown {
100    #[serde(flatten)]
101    doc: DocumentInput,
102    #[schemars(
103        description = "The mq query to execute. Selectors and functions listed in the available_selectors and available_functions tools can be used ."
104    )]
105    query: String,
106    #[schemars(
107        description = "Optional timeout for this query in milliseconds. Defaults to the server's configured timeout and is capped at the server's maximum."
108    )]
109    timeout_ms: Option<u64>,
110    #[serde(flatten)]
111    output: OutputOptions,
112}
113
114#[derive(Debug, rmcp::serde::Deserialize, schemars::JsonSchema)]
115struct MarkdownInput {
116    #[serde(flatten)]
117    doc: DocumentInput,
118    #[serde(flatten)]
119    output: OutputOptions,
120}
121
122#[derive(Debug, rmcp::serde::Deserialize, schemars::JsonSchema)]
123struct BatchDocument {
124    #[schemars(
125        description = "Optional identifier for this document (e.g. a file path), echoed back in its result. Defaults to `path` when that is given."
126    )]
127    id: Option<String>,
128    #[serde(flatten)]
129    doc: DocumentInput,
130}
131
132#[derive(Debug, rmcp::serde::Deserialize, schemars::JsonSchema)]
133struct QueryForMarkdownBatch {
134    #[schemars(description = "Documents to run the same query against")]
135    documents: Vec<BatchDocument>,
136    #[schemars(
137        description = "The mq query to execute against every document. Selectors and functions listed in the available_selectors and available_functions tools can be used."
138    )]
139    query: String,
140    #[schemars(
141        description = "Optional timeout for this query in milliseconds. Defaults to the server's configured timeout and is capped at the server's maximum."
142    )]
143    timeout_ms: Option<u64>,
144    #[schemars(
145        description = "Return at most this many results per document. A document with more reports `next_offset`."
146    )]
147    limit: Option<usize>,
148    #[schemars(
149        description = "Cap the total characters returned across all documents. Capped at the server's maximum; documents that no longer fit are returned without results."
150    )]
151    max_output_chars: Option<usize>,
152}
153
154#[derive(Debug, rmcp::serde::Serialize, schemars::JsonSchema)]
155struct BatchDocumentResult {
156    /// Position of this document in the `documents` array that was passed in.
157    index: usize,
158    #[serde(skip_serializing_if = "Option::is_none")]
159    id: Option<String>,
160    results: Vec<String>,
161    /// Number of results the query produced, including any not returned.
162    total: usize,
163    /// Set when results were left out because of `limit` or `max_output_chars`.
164    #[serde(skip_serializing_if = "Option::is_none")]
165    next_offset: Option<usize>,
166    #[serde(skip_serializing_if = "Option::is_none")]
167    error: Option<String>,
168}
169
170#[derive(Debug, rmcp::serde::Serialize, schemars::JsonSchema)]
171struct BatchOutput {
172    documents: Vec<BatchDocumentResult>,
173}
174
175#[derive(Debug, rmcp::serde::Deserialize, schemars::JsonSchema)]
176struct ExtractSectionInput {
177    #[serde(flatten)]
178    doc: DocumentInput,
179    #[schemars(description = "The section title to extract (partial match)")]
180    title: String,
181    #[serde(flatten)]
182    output: OutputOptions,
183}
184
185#[derive(Debug, rmcp::serde::Deserialize, schemars::JsonSchema)]
186struct OutlineInput {
187    #[serde(flatten)]
188    doc: DocumentInput,
189    #[schemars(
190        description = "List only headings up to this depth (1-6). The counts in `stats` still cover the whole document."
191    )]
192    max_depth: Option<u8>,
193}
194
195#[derive(Debug, rmcp::serde::Deserialize, schemars::JsonSchema)]
196struct ValidateQueryInput {
197    #[schemars(description = "The mq query to check.")]
198    query: String,
199    #[serde(flatten)]
200    sample: DocumentInput,
201    #[schemars(
202        description = "Optional timeout for the dry run in milliseconds. Defaults to the server's configured timeout and is capped at the server's maximum."
203    )]
204    timeout_ms: Option<u64>,
205}
206
207#[derive(Debug, Default, rmcp::serde::Deserialize, schemars::JsonSchema)]
208struct ListFilesInput {
209    #[schemars(
210        description = "Directory to list, inside an allowed directory. Defaults to all allowed directories."
211    )]
212    directory: Option<String>,
213    #[schemars(
214        description = "File extensions to include, without the dot. Default: md, markdown, mdx."
215    )]
216    extensions: Option<Vec<String>>,
217    #[schemars(description = "Return at most this many files (default 200, maximum 1000).")]
218    limit: Option<usize>,
219}
220
221#[derive(Debug, rmcp::serde::Serialize, schemars::JsonSchema)]
222struct FileEntry {
223    /// Absolute path; pass it as `path` to the other tools.
224    path: String,
225    size_bytes: u64,
226}
227
228#[derive(Debug, rmcp::serde::Serialize, schemars::JsonSchema)]
229struct FileList {
230    /// The directories the server allows reading from.
231    roots: Vec<String>,
232    files: Vec<FileEntry>,
233    /// True if more files exist than were returned.
234    truncated: bool,
235}
236
237/// Which markdown-to-mq input shape a query runs against.
238#[derive(Clone, Copy)]
239enum Input {
240    /// Each top-level node is a separate input (`.h`, `.code`, ...).
241    PerNode,
242    /// All nodes as a single array input (section functions).
243    Aggregate,
244}
245
246impl Server {
247    fn engine(&self, timeout_ms: Option<u64>) -> mq_lang::DefaultEngine {
248        let mut engine = mq_lang::DefaultEngine::default();
249        engine.load_builtin_module();
250        let timeout = timeout_ms
251            .map(Duration::from_millis)
252            .unwrap_or(self.config.timeout)
253            .min(self.config.max_timeout);
254        engine.set_timeout(timeout);
255        if let Some(depth) = self.config.max_call_stack_depth {
256            engine.set_max_call_stack_depth(depth);
257        }
258        engine
259    }
260
261    /// Returns inline `content`, or the contents of `path`; exactly one must be given.
262    fn load(
263        &self,
264        content: Option<String>,
265        path: Option<&str>,
266        inline_name: &str,
267    ) -> Result<String, String> {
268        match (content, path) {
269            (Some(_), Some(_)) => Err(format!("Pass either `{inline_name}` or `path`, not both.")),
270            (Some(content), None) => Ok(content),
271            (None, Some(path)) => self.config.files.read(path),
272            (None, None) => Err(format!(
273                "Pass `{inline_name}` with the content, or `path` with a file to read."
274            )),
275        }
276    }
277
278    fn load_markdown(&self, doc: DocumentInput) -> Result<String, String> {
279        self.load(doc.markdown, doc.path.as_deref(), "markdown")
280    }
281
282    /// Runs `query` and returns the non-empty results, or a plain message
283    /// describing what went wrong and how to fix it.
284    fn run(
285        &self,
286        nodes: Vec<mq_markdown::Node>,
287        query: &str,
288        input: Input,
289        timeout_ms: Option<u64>,
290    ) -> Result<Vec<mq_lang::RuntimeValue>, String> {
291        let mut engine = self.engine(timeout_ms);
292        let values: Vec<mq_lang::RuntimeValue> =
293            nodes.into_iter().map(mq_lang::RuntimeValue::from).collect();
294        let output = match input {
295            Input::PerNode => engine.eval(query, values.into_iter()),
296            Input::Aggregate => engine.eval(
297                query,
298                std::iter::once(mq_lang::RuntimeValue::Array(values.into())),
299            ),
300        }
301        .map_err(|e| {
302            format!(
303                "Failed to query: {e}\nHint: run validate_query to locate the problem, and check names with available_functions / available_selectors; selectors start with '.', e.g. `.h1`, `.code`, `select(.code.lang == \"rust\")`."
304            )
305        })?;
306
307        Ok(output
308            .into_iter()
309            .flat_map(|value| match (input, value) {
310                (Input::Aggregate, mq_lang::RuntimeValue::Array(arr)) => {
311                    arr.iter().cloned().collect()
312                }
313                (_, v) => vec![v],
314            })
315            .filter(|v| !v.is_none() && !v.is_empty())
316            .collect())
317    }
318
319    /// Tool-level failures are returned as `is_error` results (not protocol
320    /// errors) so the calling model sees the message and can fix its query.
321    fn finish(
322        &self,
323        result: Result<Vec<mq_lang::RuntimeValue>, String>,
324        output: &OutputOptions,
325    ) -> McpResult {
326        Ok(match result {
327            Ok(values) => output::render(&values, output, self.config.max_output_chars),
328            Err(message) => CallToolResult::error(vec![ContentBlock::text(message)]),
329        })
330    }
331
332    fn parse_markdown(markdown: &str) -> Result<Vec<mq_markdown::Node>, String> {
333        mq_markdown::Markdown::from_markdown_str(markdown)
334            .map(|m| m.nodes)
335            .map_err(|e| format!("Failed to parse markdown: {e}"))
336    }
337
338    fn eval_markdown(
339        &self,
340        doc: DocumentInput,
341        query: &str,
342        input: Input,
343        timeout_ms: Option<u64>,
344        output: &OutputOptions,
345    ) -> McpResult {
346        self.finish(
347            self.load_markdown(doc)
348                .and_then(|markdown| Self::parse_markdown(&markdown))
349                .and_then(|nodes| self.run(nodes, query, input, timeout_ms)),
350            output,
351        )
352    }
353
354    fn eval_query(
355        &self,
356        doc: DocumentInput,
357        query: &str,
358        timeout_ms: Option<u64>,
359        output: &OutputOptions,
360    ) -> McpResult {
361        self.eval_markdown(doc, query, Input::PerNode, timeout_ms, output)
362    }
363
364    fn eval_aggregate(&self, doc: DocumentInput, query: &str, output: &OutputOptions) -> McpResult {
365        self.eval_markdown(doc, query, Input::Aggregate, None, output)
366    }
367
368    fn eval_selector(&self, input: MarkdownInput, selector: &str) -> McpResult {
369        self.eval_query(input.doc, selector, None, &input.output)
370    }
371
372    /// A successful result carrying `value` as structured content (and as text, for clients that ignore it).
373    fn structured<T: rmcp::serde::Serialize>(value: &T) -> McpResult {
374        serde_json::to_value(value)
375            .map(CallToolResult::structured)
376            .map_err(|e| {
377                ErrorData::internal_error(
378                    "Failed to serialize structured result",
379                    Some(serde_json::Value::String(e.to_string())),
380                )
381            })
382    }
383
384    fn failure(message: String) -> McpResult {
385        Ok(CallToolResult::error(vec![ContentBlock::text(message)]))
386    }
387}
388
389#[derive(Debug, rmcp::serde::Serialize, rmcp::serde::Deserialize, schemars::JsonSchema)]
390struct FunctionInfo {
391    #[schemars(description = "The function name")]
392    name: String,
393    #[schemars(description = "The function description")]
394    description: String,
395    #[schemars(description = "The function parameters")]
396    params: Vec<String>,
397    #[schemars(description = "Whether this is a built-in function")]
398    is_builtin: bool,
399}
400
401#[derive(Debug, rmcp::serde::Serialize, rmcp::serde::Deserialize, schemars::JsonSchema)]
402struct SelectorInfo {
403    #[schemars(description = "The function name")]
404    name: String,
405    #[schemars(description = "The function description")]
406    description: String,
407    #[schemars(description = "The function parameters")]
408    params: Vec<String>,
409}
410
411#[derive(Debug, Default, rmcp::serde::Deserialize, schemars::JsonSchema)]
412struct FunctionFilter {
413    #[schemars(
414        description = "Case-insensitive substring matched against function names and descriptions"
415    )]
416    filter: Option<String>,
417}
418
419#[tool_router]
420impl Server {
421    pub fn new(mut config: EngineConfig) -> Self {
422        config.max_output_chars = config.max_output_chars.max(MIN_OUTPUT_CHARS);
423        Self {
424            tool_router: Self::tool_router(),
425            config,
426        }
427    }
428
429    #[tool(
430        description = "Executes an mq query on the provided HTML content (inline or from a file) and returns the result as Markdown. Selectors and functions listed in the available_selectors and available_functions tools can be used. Use `limit`/`offset` to page through long results and `format: \"json\"` for structured results."
431    )]
432    fn html_to_markdown(
433        &self,
434        Parameters(QueryForHtml {
435            html,
436            path,
437            query,
438            timeout_ms,
439            output,
440        }): Parameters<QueryForHtml>,
441    ) -> McpResult {
442        let result = self
443            .load(html, path.as_deref(), "html")
444            .and_then(|html| {
445                mq_markdown::Markdown::from_html_str(&html)
446                    .map_err(|e| format!("Failed to parse html: {e}"))
447            })
448            .and_then(|m| {
449                self.run(
450                    m.nodes,
451                    query.as_deref().unwrap_or("identity()"),
452                    Input::PerNode,
453                    timeout_ms,
454                )
455            });
456        self.finish(result, &output)
457    }
458
459    #[tool(
460        description = "Run a custom mq query on markdown content (inline `markdown` or a file `path`). Prefer the dedicated extract_* tools for simple cases. Examples: `.h2` (all h2 headings), `select(.code.lang == \"rust\")` (rust code blocks), `.link | to_text()` (link texts), `select(contains(\"TODO\"))`. On a syntax error, use validate_query, or check available_functions / available_selectors. Queries exceeding the timeout fail; pass timeout_ms to adjust (capped by the server). Long results are cut at max_output_chars; use limit/offset to page, and format: \"json\" for types, attributes and line positions."
461    )]
462    fn extract_markdown(
463        &self,
464        Parameters(QueryForMarkdown {
465            doc,
466            query,
467            timeout_ms,
468            output,
469        }): Parameters<QueryForMarkdown>,
470    ) -> McpResult {
471        self.eval_query(doc, &query, timeout_ms, &output)
472    }
473
474    #[tool(
475        description = "Run the same mq query against multiple markdown documents (inline or by file path) in one call, instead of one extract_markdown call per document. Returns one object per document (index, optional id, results, total, and error if that document's query failed) — a failure in one document does not abort the rest.",
476        output_schema = rmcp::handler::server::tool::schema_for_output::<BatchOutput>()
477    )]
478    fn extract_markdown_batch(
479        &self,
480        Parameters(QueryForMarkdownBatch {
481            documents,
482            query,
483            timeout_ms,
484            limit,
485            max_output_chars,
486        }): Parameters<QueryForMarkdownBatch>,
487    ) -> McpResult {
488        let options = OutputOptions {
489            max_output_chars,
490            ..OutputOptions::default()
491        };
492        let mut remaining = options.budget(self.config.max_output_chars);
493
494        let documents: Vec<BatchDocumentResult> = documents
495            .into_iter()
496            .enumerate()
497            .map(|(index, document)| {
498                let id = document.id.or_else(|| document.doc.path.clone());
499                let outcome = self
500                    .load_markdown(document.doc)
501                    .and_then(|markdown| Self::parse_markdown(&markdown))
502                    .and_then(|nodes| self.run(nodes, &query, Input::PerNode, timeout_ms));
503
504                match outcome {
505                    Ok(values) => {
506                        let texts: Vec<String> = values.iter().map(|v| v.to_string()).collect();
507                        let sizes: Vec<usize> = texts.iter().map(|t| t.chars().count()).collect();
508                        let page = output::paginate(&sizes, 0, limit, remaining);
509                        let results: Vec<String> = (page.start..page.end)
510                            .map(|i| match page.cut_to {
511                                Some(max) => output::truncate_chars(&texts[i], max),
512                                None => texts[i].clone(),
513                            })
514                            .collect();
515                        remaining = remaining
516                            .saturating_sub(results.iter().map(|r| r.chars().count()).sum());
517
518                        BatchDocumentResult {
519                            index,
520                            id,
521                            results,
522                            total: page.total,
523                            next_offset: page.next_offset,
524                            error: None,
525                        }
526                    }
527                    Err(error) => BatchDocumentResult {
528                        index,
529                        id,
530                        results: Vec::new(),
531                        total: 0,
532                        next_offset: None,
533                        error: Some(error),
534                    },
535                }
536            })
537            .collect();
538
539        Self::structured(&BatchOutput { documents })
540    }
541
542    #[tool(description = "Extract all headings (h1–h6) from markdown content.")]
543    fn extract_headings(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
544        self.eval_selector(input, ".h")
545    }
546
547    #[tool(description = "Extract all fenced code blocks from markdown content.")]
548    fn extract_code_blocks(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
549        self.eval_selector(input, ".code")
550    }
551
552    #[tool(description = "Extract all unchecked task list items (todos) from markdown content.")]
553    fn extract_todos(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
554        self.eval_selector(input, ".todo")
555    }
556
557    #[tool(description = "Extract all checked task list items (done tasks) from markdown content.")]
558    fn extract_done_tasks(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
559        self.eval_selector(input, ".done")
560    }
561
562    #[tool(description = "Extract all links from markdown content.")]
563    fn extract_links(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
564        self.eval_selector(input, ".link")
565    }
566
567    #[tool(description = "Extract all images from markdown content.")]
568    fn extract_images(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
569        self.eval_selector(input, ".image")
570    }
571
572    #[tool(description = "Extract all tables from markdown content.")]
573    fn extract_tables(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
574        self.eval_selector(input, ".table")
575    }
576
577    #[tool(description = "Extract all paragraph text nodes from markdown content.")]
578    fn extract_text(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
579        self.eval_selector(input, ".text")
580    }
581
582    #[tool(description = "Extract all blockquotes from markdown content.")]
583    fn extract_blockquotes(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
584        self.eval_selector(input, ".blockquote")
585    }
586
587    #[tool(
588        description = "Split markdown content into sections (heading + body) and return all of them as markdown."
589    )]
590    fn extract_sections(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
591        self.eval_aggregate(
592            input.doc,
593            r#"import "section" | section::sections() | section::collect()"#,
594            &input.output,
595        )
596    }
597
598    #[tool(
599        description = "Extract a specific section (heading + body) from markdown content by title. Performs a partial, case-sensitive match on the heading text."
600    )]
601    fn extract_section(
602        &self,
603        Parameters(ExtractSectionInput { doc, title, output }): Parameters<ExtractSectionInput>,
604    ) -> McpResult {
605        let escaped = title.replace('\\', r"\\").replace('"', r#"\""#);
606        let query =
607            format!(r#"import "section" | section::section("{escaped}") | section::collect()"#);
608        self.eval_aggregate(doc, &query, &output)
609    }
610
611    #[tool(
612        description = "Generate a table of contents from the headings in markdown content. Returns a list of indented entries."
613    )]
614    fn extract_toc(&self, Parameters(input): Parameters<MarkdownInput>) -> McpResult {
615        self.eval_aggregate(
616            input.doc,
617            r#"import "section" | section::sections() | section::toc()"#,
618            &input.output,
619        )
620    }
621
622    #[tool(
623        description = "Summarise a markdown document's structure without returning its content: totals (characters, lines, code blocks by language, tables, links, images, todos), whether it has front matter, and every heading with its line range, size in characters and number of subsections. Use it first on large documents to decide which section to fetch with extract_section.",
624        output_schema = rmcp::handler::server::tool::schema_for_output::<Outline>()
625    )]
626    fn document_outline(
627        &self,
628        Parameters(OutlineInput { doc, max_depth }): Parameters<OutlineInput>,
629    ) -> McpResult {
630        match self
631            .load_markdown(doc)
632            .and_then(|markdown| Self::parse_markdown(&markdown).map(|nodes| (markdown, nodes)))
633        {
634            Ok((markdown, nodes)) => {
635                Self::structured(&outline::outline(&markdown, &nodes, max_depth))
636            }
637            Err(message) => Self::failure(message),
638        }
639    }
640
641    #[tool(
642        description = "Extract a document's YAML or TOML front matter as parsed JSON, along with its raw text. Reports found: false when the document has none.",
643        output_schema = rmcp::handler::server::tool::schema_for_output::<FrontmatterResult>()
644    )]
645    fn extract_frontmatter(&self, Parameters(doc): Parameters<DocumentInput>) -> McpResult {
646        match self
647            .load_markdown(doc)
648            .and_then(|markdown| Self::parse_markdown(&markdown))
649        {
650            Ok(nodes) => Self::structured(&outline::parse_frontmatter(&nodes)),
651            Err(message) => Self::failure(message),
652        }
653    }
654
655    #[tool(
656        description = "Check an mq query before running it: reports syntax errors and unknown functions/selectors with line and column and a \"did you mean\" suggestion. Optionally pass a sample (`markdown` or `path`) to also dry-run the query and see the match count and the first few results.",
657        output_schema = rmcp::handler::server::tool::schema_for_output::<QueryCheck>()
658    )]
659    fn validate_query(
660        &self,
661        Parameters(ValidateQueryInput {
662            query,
663            sample,
664            timeout_ms,
665        }): Parameters<ValidateQueryInput>,
666    ) -> McpResult {
667        let has_sample = sample.markdown.is_some() || sample.path.is_some();
668        let sample = if has_sample {
669            match self.load_markdown(sample) {
670                Ok(markdown) => Some(markdown),
671                Err(message) => return Self::failure(message),
672            }
673        } else {
674            None
675        };
676
677        let issues = check::check_query(&mut self.engine(timeout_ms), &query);
678        let dry_run = sample.filter(|_| issues.is_empty()).map(|markdown| {
679            match Self::parse_markdown(&markdown)
680                .and_then(|nodes| self.run(nodes, &query, Input::PerNode, timeout_ms))
681            {
682                Ok(values) => DryRun {
683                    match_count: values.len(),
684                    samples: values
685                        .iter()
686                        .take(DRY_RUN_SAMPLES)
687                        .map(|v| check::shorten(&v.to_string()))
688                        .collect(),
689                    error: None,
690                },
691                Err(error) => DryRun {
692                    match_count: 0,
693                    samples: Vec::new(),
694                    error: Some(error),
695                },
696            }
697        });
698
699        Self::structured(&QueryCheck {
700            valid: issues.is_empty(),
701            issues,
702            dry_run,
703        })
704    }
705
706    #[tool(
707        description = "List the files the server may read through the `path` parameter, sorted by path. Defaults to Markdown files (md, markdown, mdx) in all allowed directories; pass `directory` and `extensions` to narrow or widen the search.",
708        output_schema = rmcp::handler::server::tool::schema_for_output::<FileList>()
709    )]
710    fn list_files(&self, Parameters(input): Parameters<ListFilesInput>) -> McpResult {
711        let extensions = input.extensions.unwrap_or_else(|| {
712            DEFAULT_LIST_EXTENSIONS
713                .iter()
714                .map(|ext| ext.to_string())
715                .collect()
716        });
717        let extensions: Vec<String> = extensions
718            .into_iter()
719            .map(|ext| ext.trim_start_matches('.').to_string())
720            .collect();
721        let limit = input
722            .limit
723            .unwrap_or(DEFAULT_LIST_LIMIT)
724            .clamp(1, MAX_LIST_LIMIT);
725
726        match self
727            .config
728            .files
729            .list(input.directory.as_deref(), &extensions, limit)
730        {
731            Ok((files, truncated)) => Self::structured(&FileList {
732                roots: self
733                    .config
734                    .files
735                    .roots()
736                    .iter()
737                    .map(|root| root.display().to_string())
738                    .collect(),
739                files: files
740                    .into_iter()
741                    .map(|(path, size_bytes)| FileEntry {
742                        path: path.display().to_string(),
743                        size_bytes,
744                    })
745                    .collect(),
746                truncated,
747            }),
748            Err(message) => Self::failure(message),
749        }
750    }
751
752    #[tool(
753        description = "List mq functions usable in queries (name, description, params). Pass `filter` to match names/descriptions case-insensitively and keep the output small."
754    )]
755    fn available_functions(
756        &self,
757        Parameters(FunctionFilter { filter }): Parameters<FunctionFilter>,
758    ) -> McpResult {
759        let hir = mq_hir::Hir::default();
760        let mut functions = Vec::with_capacity(256);
761
762        // Get built-in functions
763        for builtin_doc in hir.builtin.docs.functions() {
764            functions.push(FunctionInfo {
765                name: builtin_doc.name.to_string(),
766                description: builtin_doc.description.to_string(),
767                params: builtin_doc.params.iter().map(|p| p.to_string()).collect(),
768                is_builtin: true,
769            });
770        }
771
772        // Get internal functions
773        for builtin_doc in hir.builtin.docs.internal_functions() {
774            functions.push(FunctionInfo {
775                name: builtin_doc.name.to_string(),
776                description: builtin_doc.description.to_string(),
777                params: builtin_doc.params.iter().map(|p| p.to_string()).collect(),
778                is_builtin: true,
779            });
780        }
781
782        if let Some(filter) = filter.as_deref().map(str::to_lowercase) {
783            functions.retain(|f| {
784                f.name.to_lowercase().contains(&filter)
785                    || f.description.to_lowercase().contains(&filter)
786            });
787        }
788
789        let output = serde_json::json!({
790            "functions": functions,
791            "examples": vec![
792                r#"select(or(.[], .code, .h)) | upcase() | add(" Hello World")"#.to_string(),
793                r#"select(not(.code))"#.to_string(),
794                r#"select(.code.lang == "js")"#.to_string(),
795            ],
796        });
797        let functions_json = serde_json::to_string(&output).expect("Failed to serialize functions");
798
799        Ok(CallToolResult::success(vec![ContentBlock::text(
800            functions_json,
801        )]))
802    }
803
804    #[tool(description = "Get available selectors that can be used in mq query.")]
805    fn available_selectors(&self) -> McpResult {
806        let hir = mq_hir::Hir::default();
807        let mut selectors = Vec::with_capacity(256);
808
809        // Get selectors
810        for selector_doc in hir.builtin.docs.selectors() {
811            selectors.push(SelectorInfo {
812                name: selector_doc.name.to_string(),
813                description: selector_doc.description.to_string(),
814                params: selector_doc.params.iter().map(|p| p.to_string()).collect(),
815            });
816        }
817
818        let output = serde_json::json!({
819            "selectors": selectors,
820        });
821        let selectors_json = serde_json::to_string(&output).expect("Failed to serialize selectors");
822
823        Ok(CallToolResult::success(vec![ContentBlock::text(
824            selectors_json,
825        )]))
826    }
827}
828
829#[tool_handler]
830impl ServerHandler for Server {
831    fn get_info(&self) -> ServerConfig {
832        let mut instructions = String::from(
833            "mq is a tool for processing markdown content with a jq-like syntax. \
834             For a large document, start with document_outline to see its structure, then fetch only what you need. \
835             Use the dedicated extract_* tools (headings, code blocks, links, sections, toc, frontmatter...) for common cases. \
836             For anything else use extract_markdown (or extract_markdown_batch for many documents, html_to_markdown for HTML) with an mq query such as `.h2` or `select(.code.lang == \"rust\")`. \
837             If a query fails, the error explains why; validate_query checks a query without running it, and available_functions (use `filter`) and available_selectors list valid names. \
838             Queries have a timeout; pass `timeout_ms` to raise it up to the server's maximum. \
839             Long results are cut at a character limit and say how to continue: use `limit` and `offset` to page, or `format: \"json\"` for result types, attributes and line positions.",
840        );
841        if self.config.files.is_enabled() {
842            let roots = self
843                .config
844                .files
845                .roots()
846                .iter()
847                .map(|root| root.display().to_string())
848                .collect::<Vec<_>>()
849                .join(", ");
850            instructions.push_str(&format!(
851                " Instead of sending a document's content, pass `path` to read a file under: {roots}. list_files shows what is available."
852            ));
853        }
854
855        ServerConfig::new(
856            ServerCapabilities::builder()
857                .enable_tools()
858                .enable_tool_list_changed()
859                .build(),
860        )
861        .with_protocol_version(ProtocolVersion::V_2025_06_18)
862        .with_instructions(instructions)
863    }
864}
865
866pub async fn start(config: EngineConfig) -> miette::Result<()> {
867    let transport = (stdin(), stdout());
868    let server = Server::new(config);
869
870    let service = server.serve(transport).await.map_err(|e| miette!(e))?;
871    service.waiting().await.map_err(|e| miette!(e))?;
872
873    Ok(())
874}
875
876/// Configuration for the remote (Streamable HTTP) MCP transport.
877pub struct HttpConfig {
878    /// Address to bind the HTTP listener to, e.g. `127.0.0.1:8080`.
879    pub bind: String,
880    /// Additional `Host` header values to accept, on top of the loopback
881    /// defaults. Required when the server sits behind a reverse proxy or is
882    /// otherwise reachable under a non-loopback hostname, since Streamable
883    /// HTTP rejects unrecognized hosts to guard against DNS rebinding.
884    pub allowed_hosts: Vec<String>,
885    /// If set, every request to `/mcp` must carry `Authorization: Bearer
886    /// <token>` matching this value, or it's rejected with 401.
887    pub bearer_token: Option<String>,
888}
889
890fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
891    if a.len() != b.len() {
892        return false;
893    }
894    a.iter().zip(b).fold(0u8, |acc, (x, y)| acc | (x ^ y)) == 0
895}
896
897async fn require_bearer_token(
898    axum::extract::State(expected): axum::extract::State<Arc<str>>,
899    req: axum::extract::Request,
900    next: axum::middleware::Next,
901) -> axum::response::Response {
902    use axum::response::IntoResponse;
903
904    let authorized = req
905        .headers()
906        .get(axum::http::header::AUTHORIZATION)
907        .and_then(|v| v.to_str().ok())
908        .and_then(|v| v.strip_prefix("Bearer "))
909        .is_some_and(|token| constant_time_eq(token.as_bytes(), expected.as_bytes()));
910
911    if authorized {
912        next.run(req).await
913    } else {
914        (axum::http::StatusCode::UNAUTHORIZED, "Unauthorized").into_response()
915    }
916}
917
918pub async fn start_http(config: HttpConfig, engine: EngineConfig) -> miette::Result<()> {
919    let mut server_config = StreamableHttpServerConfig::default();
920    if !config.allowed_hosts.is_empty() {
921        server_config.allowed_hosts.extend(config.allowed_hosts);
922    }
923
924    let service = StreamableHttpService::new(
925        move || Ok(Server::new(engine.clone())),
926        Arc::new(LocalSessionManager::default()),
927        server_config,
928    );
929
930    let router = if let Some(token) = &config.bearer_token {
931        axum::Router::new().nest_service("/mcp", service).layer(
932            axum::middleware::from_fn_with_state(
933                Arc::<str>::from(token.as_str()),
934                require_bearer_token,
935            ),
936        )
937    } else {
938        axum::Router::new().nest_service("/mcp", service)
939    };
940    let listener = tokio::net::TcpListener::bind(&config.bind)
941        .await
942        .map_err(|e| miette!(e))?;
943
944    tracing::info!("mq-mcp listening on http://{}/mcp", config.bind);
945
946    axum::serve(listener, router)
947        .with_graceful_shutdown(async {
948            let _ = tokio::signal::ctrl_c().await;
949        })
950        .await
951        .map_err(|e| miette!(e))?;
952
953    Ok(())
954}
955
956#[cfg(test)]
957mod tests {
958    use super::*;
959    use crate::output::OutputFormat;
960    use rstest::rstest;
961    use serde_json::{Value, json};
962    use tempfile::TempDir;
963
964    impl DocumentInput {
965        fn inline(markdown: &str) -> Self {
966            Self {
967                markdown: Some(markdown.to_string()),
968                path: None,
969            }
970        }
971
972        fn file(path: &str) -> Self {
973            Self {
974                markdown: None,
975                path: Some(path.to_string()),
976            }
977        }
978    }
979
980    fn md(markdown: &str) -> MarkdownInput {
981        MarkdownInput {
982            doc: DocumentInput::inline(markdown),
983            output: OutputOptions::default(),
984        }
985    }
986
987    fn md_with(markdown: &str, output: OutputOptions) -> MarkdownInput {
988        MarkdownInput {
989            doc: DocumentInput::inline(markdown),
990            output,
991        }
992    }
993
994    fn query_for(markdown: &str, query: &str) -> QueryForMarkdown {
995        QueryForMarkdown {
996            doc: DocumentInput::inline(markdown),
997            query: query.to_string(),
998            timeout_ms: None,
999            output: OutputOptions::default(),
1000        }
1001    }
1002
1003    /// A server that may read `root/`, plus a sibling `outside/` it must not reach.
1004    fn server_with_files(files: &[(&str, &str)]) -> (TempDir, Server) {
1005        let tmp = TempDir::new().unwrap();
1006        let root = tmp.path().join("root");
1007        std::fs::create_dir_all(&root).unwrap();
1008        std::fs::create_dir_all(tmp.path().join("outside")).unwrap();
1009        std::fs::write(tmp.path().join("outside/secret.md"), "# Secret").unwrap();
1010        for (name, content) in files {
1011            let path = root.join(name);
1012            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1013            std::fs::write(path, content).unwrap();
1014        }
1015
1016        let server = Server::new(EngineConfig {
1017            files: FileAccess::new([root], 1024 * 1024).unwrap(),
1018            ..EngineConfig::default()
1019        });
1020        (tmp, server)
1021    }
1022
1023    fn error_text(result: CallToolResult) -> String {
1024        assert!(
1025            result.is_error.unwrap_or_default(),
1026            "expected an error result"
1027        );
1028        result
1029            .content
1030            .iter()
1031            .filter_map(|c| c.as_text().map(|t| t.text.clone()))
1032            .collect()
1033    }
1034
1035    fn structured(result: CallToolResult) -> Value {
1036        assert!(!result.is_error.unwrap_or_default(), "{:?}", result.content);
1037        result.structured_content.expect("structured content")
1038    }
1039
1040    fn ok_texts(result: CallToolResult) -> Vec<String> {
1041        assert!(!result.is_error.unwrap_or_default());
1042        result
1043            .content
1044            .into_iter()
1045            .map(|c| c.as_text().map(|t| t.text.clone()).unwrap_or_default())
1046            .collect()
1047    }
1048
1049    #[rstest]
1050    #[case(
1051        QueryForHtml {
1052            html: Some("<h1>Test Heading</h1><p>This is a test paragraph.</p>".to_string()),
1053            path: None,
1054            query: Some(".h1".to_string()),
1055            timeout_ms: None,
1056            output: OutputOptions::default(),
1057        },
1058        Ok("# Test Heading")
1059    )]
1060    #[case(
1061        QueryForHtml {
1062            html: Some("<h1>Test Heading</h1><p>This is a test paragraph.</p>".to_string()),
1063            path: None,
1064            query: Some(".text".to_string()),
1065            timeout_ms: None,
1066            output: OutputOptions::default(),
1067        },
1068        Ok("Test Heading\n\nThis is a test paragraph.")
1069    )]
1070    #[case(
1071        QueryForHtml {
1072            html: Some("<h1>Test Heading</h1><p>This is a test paragraph.</p>".to_string()),
1073            path: None,
1074            query: None,
1075            timeout_ms: None,
1076            output: OutputOptions::default(),
1077        },
1078        Ok("# Test Heading\n\nThis is a test paragraph.")
1079    )]
1080    #[case(
1081        QueryForHtml {
1082            html: Some("<h1>Test Heading".to_string()), // malformed HTML
1083            path: None,
1084            query: Some(".h1".to_string()),
1085            timeout_ms: None,
1086            output: OutputOptions::default(),
1087        },
1088        Ok("# Test Heading")
1089    )]
1090    #[case(
1091        QueryForHtml {
1092            html: Some("<h1>Test Heading</h1>".to_string()),
1093            path: None,
1094            query: Some("not_a_function(".to_string()), // invalid query
1095            timeout_ms: None,
1096            output: OutputOptions::default(),
1097        },
1098        Err("Failed to query")
1099    )]
1100    fn test_html_to_markdown(
1101        #[case] query: QueryForHtml,
1102        #[case] expected: Result<&'static str, &'static str>,
1103    ) {
1104        let server = Server::new(EngineConfig::default());
1105        let result = server.html_to_markdown(Parameters(query));
1106        match expected {
1107            Ok(expected_text) => {
1108                let result = result.expect("Expected Ok result");
1109                assert_eq!(ok_texts(result).join("\n\n"), expected_text);
1110            }
1111            Err(expected_err) => {
1112                let msg = error_text(result.expect("tool errors are returned as is_error results"));
1113                assert!(
1114                    msg.contains(expected_err),
1115                    "Error message '{msg}' does not contain expected '{expected_err}'"
1116                );
1117            }
1118        }
1119    }
1120
1121    #[test]
1122    fn test_html_to_markdown_reads_html_file() {
1123        let (_tmp, server) = server_with_files(&[("page.html", "<h1>From file</h1>")]);
1124        let result = server
1125            .html_to_markdown(Parameters(QueryForHtml {
1126                html: None,
1127                path: Some("page.html".to_string()),
1128                query: Some(".h1".to_string()),
1129                timeout_ms: None,
1130                output: OutputOptions::default(),
1131            }))
1132            .unwrap();
1133        assert_eq!(ok_texts(result), ["# From file"]);
1134    }
1135
1136    #[rstest]
1137    #[case(query_for("# Test Heading", ".h1"), Ok("# Test Heading"))]
1138    #[case(
1139        query_for("# Test Heading\n\nThis is a test paragraph.", ".text"),
1140        Ok("Test Heading\n\nThis is a test paragraph.")
1141    )]
1142    #[case(
1143        query_for("# Test Heading\n\nThis is a test paragraph.", "identity()"),
1144        Ok("# Test Heading\n\nThis is a test paragraph.")
1145    )]
1146    #[case(query_for("# Test Heading", "not_a_function("), Err("Failed to query"))]
1147    #[case(query_for("", ".h1"), Ok(""))]
1148    fn test_extract_markdown(
1149        #[case] query: QueryForMarkdown,
1150        #[case] expected: Result<&'static str, &'static str>,
1151    ) {
1152        let server = Server::new(EngineConfig::default());
1153        let result = server.extract_markdown(Parameters(query));
1154        match expected {
1155            Ok(expected_text) => {
1156                let result = result.expect("Expected Ok result");
1157                assert_eq!(ok_texts(result).join("\n\n"), expected_text);
1158            }
1159            Err(expected_err) => {
1160                let msg = error_text(result.expect("tool errors are returned as is_error results"));
1161                assert!(
1162                    msg.contains(expected_err),
1163                    "Error message '{msg}' does not contain expected '{expected_err}'"
1164                );
1165            }
1166        }
1167    }
1168
1169    #[test]
1170    fn test_query_error_points_to_validate_query() {
1171        let server = Server::new(EngineConfig::default());
1172        let msg = error_text(
1173            server
1174                .extract_markdown(Parameters(query_for("# a", "not_a_function(")))
1175                .unwrap(),
1176        );
1177        assert!(msg.contains("validate_query"), "{msg}");
1178    }
1179
1180    #[derive(Debug, rmcp::serde::Deserialize)]
1181    struct BatchOutputForTest {
1182        documents: Vec<BatchDocumentResultForTest>,
1183    }
1184
1185    #[derive(Debug, rmcp::serde::Deserialize)]
1186    struct BatchDocumentResultForTest {
1187        index: usize,
1188        #[serde(default)]
1189        id: Option<String>,
1190        #[serde(default)]
1191        results: Vec<String>,
1192        #[serde(default)]
1193        total: usize,
1194        #[serde(default)]
1195        next_offset: Option<usize>,
1196        #[serde(default)]
1197        error: Option<String>,
1198    }
1199
1200    fn batch_doc(id: Option<&str>, markdown: &str) -> BatchDocument {
1201        BatchDocument {
1202            id: id.map(str::to_string),
1203            doc: DocumentInput::inline(markdown),
1204        }
1205    }
1206
1207    fn batch(
1208        documents: Vec<BatchDocument>,
1209        query: &str,
1210        limit: Option<usize>,
1211        max_output_chars: Option<usize>,
1212    ) -> McpResult {
1213        Server::new(EngineConfig::default()).extract_markdown_batch(Parameters(
1214            QueryForMarkdownBatch {
1215                documents,
1216                query: query.to_string(),
1217                timeout_ms: None,
1218                limit,
1219                max_output_chars,
1220            },
1221        ))
1222    }
1223
1224    fn batch_output(result: CallToolResult) -> Vec<BatchDocumentResultForTest> {
1225        let parsed: BatchOutputForTest = serde_json::from_value(structured(result)).unwrap();
1226        parsed.documents
1227    }
1228
1229    #[test]
1230    fn test_extract_markdown_batch_mixes_success_and_per_document_error() {
1231        let result = batch(
1232            vec![
1233                batch_doc(Some("a.md"), "# Title A"),
1234                batch_doc(Some("b.md"), "# Title B"),
1235            ],
1236            ".h1",
1237            None,
1238            None,
1239        )
1240        .expect("batch call should succeed even if a document's query fails");
1241
1242        // The text content mirrors the structured content, for clients that ignore the latter.
1243        assert!(
1244            result.content[0]
1245                .as_text()
1246                .unwrap()
1247                .text
1248                .contains("Title A")
1249        );
1250        let parsed = batch_output(result);
1251
1252        assert_eq!(parsed.len(), 2);
1253        assert_eq!(parsed[0].index, 0);
1254        assert_eq!(parsed[0].id.as_deref(), Some("a.md"));
1255        assert_eq!(parsed[0].results, vec!["# Title A".to_string()]);
1256        assert_eq!(parsed[0].total, 1);
1257        assert!(parsed[0].error.is_none());
1258        assert_eq!(parsed[1].id.as_deref(), Some("b.md"));
1259        assert_eq!(parsed[1].results, vec!["# Title B".to_string()]);
1260    }
1261
1262    #[test]
1263    fn test_extract_markdown_batch_reports_error_without_aborting_other_documents() {
1264        let parsed = batch_output(
1265            batch(
1266                vec![
1267                    batch_doc(None, "not valid because "),
1268                    batch_doc(None, "# Fine"),
1269                ],
1270                "not_a_function(",
1271                None,
1272                None,
1273            )
1274            .expect("batch call itself should still succeed"),
1275        );
1276
1277        assert_eq!(parsed.len(), 2);
1278        assert!(parsed[0].results.is_empty());
1279        assert!(
1280            parsed[0]
1281                .error
1282                .as_deref()
1283                .unwrap()
1284                .contains("Failed to query")
1285        );
1286        assert!(parsed[1].results.is_empty());
1287        assert!(
1288            parsed[1]
1289                .error
1290                .as_deref()
1291                .unwrap()
1292                .contains("Failed to query")
1293        );
1294    }
1295
1296    #[test]
1297    fn test_extract_markdown_batch_reads_files_and_reports_file_errors_per_document() {
1298        let (_tmp, server) = server_with_files(&[("a.md", "# From file")]);
1299        let result = server
1300            .extract_markdown_batch(Parameters(QueryForMarkdownBatch {
1301                documents: vec![
1302                    BatchDocument {
1303                        id: None,
1304                        doc: DocumentInput::file("a.md"),
1305                    },
1306                    BatchDocument {
1307                        id: None,
1308                        doc: DocumentInput::file("../outside/secret.md"),
1309                    },
1310                    batch_doc(Some("inline"), "# Inline"),
1311                ],
1312                query: ".h1".to_string(),
1313                timeout_ms: None,
1314                limit: None,
1315                max_output_chars: None,
1316            }))
1317            .unwrap();
1318        let parsed = batch_output(result);
1319
1320        assert_eq!(
1321            parsed[0].id.as_deref(),
1322            Some("a.md"),
1323            "id defaults to the path"
1324        );
1325        assert_eq!(parsed[0].results, ["# From file"]);
1326        assert!(
1327            parsed[1]
1328                .error
1329                .as_deref()
1330                .unwrap()
1331                .contains("outside the allowed directories")
1332        );
1333        assert!(parsed[1].results.is_empty());
1334        assert_eq!(parsed[2].results, ["# Inline"]);
1335    }
1336
1337    #[test]
1338    fn test_extract_markdown_batch_limit_and_output_budget() {
1339        let headings = "# One\n\n# Two\n\n# Three\n";
1340        let parsed = batch_output(
1341            batch(
1342                vec![batch_doc(None, headings), batch_doc(None, headings)],
1343                ".h1",
1344                Some(2),
1345                None,
1346            )
1347            .unwrap(),
1348        );
1349        assert_eq!(parsed[0].results.len(), 2);
1350        assert_eq!(parsed[0].total, 3);
1351        assert_eq!(parsed[0].next_offset, Some(2));
1352
1353        // A budget that only the first document fits in: the second comes back empty but flagged.
1354        let long = format!("# {}\n", "x".repeat(300));
1355        let parsed = batch_output(
1356            batch(
1357                vec![batch_doc(None, &long), batch_doc(None, &long)],
1358                ".h1",
1359                None,
1360                Some(400),
1361            )
1362            .unwrap(),
1363        );
1364        assert_eq!(parsed[0].results.len(), 1);
1365        assert!(parsed[1].results.is_empty());
1366        assert_eq!(parsed[1].total, 1);
1367        assert_eq!(parsed[1].next_offset, Some(0));
1368    }
1369
1370    #[rstest]
1371    #[case("# H1\n\n## H2\n\n### H3", vec!["# H1", "## H2", "### H3"])]
1372    #[case("No headings here.", vec![])]
1373    fn test_extract_headings(#[case] markdown: &str, #[case] expected: Vec<&str>) {
1374        let server = Server::new(EngineConfig::default());
1375        let result = server.extract_headings(Parameters(md(markdown))).unwrap();
1376        assert_eq!(ok_texts(result), expected);
1377    }
1378
1379    #[rstest]
1380    #[case("```rust\nfn main() {}\n```\n\n```python\nprint(\"hi\")\n```", 2)]
1381    #[case("No code blocks.", 0)]
1382    fn test_extract_code_blocks(#[case] markdown: &str, #[case] count: usize) {
1383        let server = Server::new(EngineConfig::default());
1384        let result = server
1385            .extract_code_blocks(Parameters(md(markdown)))
1386            .unwrap();
1387        assert_eq!(ok_texts(result).len(), count);
1388    }
1389
1390    #[rstest]
1391    #[case("- [ ] Buy milk\n- [x] Buy eggs\n- [ ] Buy bread", vec!["- [ ] Buy milk", "- [ ] Buy bread"])]
1392    #[case("- [x] Done task", vec![])]
1393    #[case("No list.", vec![])]
1394    fn test_extract_todos(#[case] markdown: &str, #[case] expected: Vec<&str>) {
1395        let server = Server::new(EngineConfig::default());
1396        let result = server.extract_todos(Parameters(md(markdown))).unwrap();
1397        assert_eq!(ok_texts(result), expected);
1398    }
1399
1400    #[rstest]
1401    #[case("- [ ] Todo\n- [x] Done", vec!["- [x] Done"])]
1402    #[case("- [ ] Only todo", vec![])]
1403    fn test_extract_done_tasks(#[case] markdown: &str, #[case] expected: Vec<&str>) {
1404        let server = Server::new(EngineConfig::default());
1405        let result = server.extract_done_tasks(Parameters(md(markdown))).unwrap();
1406        assert_eq!(ok_texts(result), expected);
1407    }
1408
1409    #[rstest]
1410    #[case("[Google](https://google.com) and [Rust](https://rust-lang.org)", 2)]
1411    #[case("No links here.", 0)]
1412    fn test_extract_links(#[case] markdown: &str, #[case] count: usize) {
1413        let server = Server::new(EngineConfig::default());
1414        let result = server.extract_links(Parameters(md(markdown))).unwrap();
1415        assert_eq!(ok_texts(result).len(), count);
1416    }
1417
1418    #[rstest]
1419    #[case("![Alt](img.png) and ![Logo](logo.svg)", 2)]
1420    #[case("No images.", 0)]
1421    fn test_extract_images(#[case] markdown: &str, #[case] count: usize) {
1422        let server = Server::new(EngineConfig::default());
1423        let result = server.extract_images(Parameters(md(markdown))).unwrap();
1424        assert_eq!(ok_texts(result).len(), count);
1425    }
1426
1427    #[rstest]
1428    // .table returns individual table cells; a 2-column × 2-row table (header + data) = 4 cells
1429    #[case("| A | B |\n|---|---|\n| 1 | 2 |", 4)]
1430    #[case("No tables.", 0)]
1431    fn test_extract_tables(#[case] markdown: &str, #[case] count: usize) {
1432        let server = Server::new(EngineConfig::default());
1433        let result = server.extract_tables(Parameters(md(markdown))).unwrap();
1434        assert_eq!(ok_texts(result).len(), count);
1435    }
1436
1437    #[rstest]
1438    #[case("Hello world.\n\nSecond paragraph.", 2)]
1439    // from_html_str treats bare "# Only heading" as a single text paragraph (not a heading)
1440    #[case("# Only heading", 1)]
1441    fn test_extract_text(#[case] markdown: &str, #[case] count: usize) {
1442        let server = Server::new(EngineConfig::default());
1443        let result = server.extract_text(Parameters(md(markdown))).unwrap();
1444        assert_eq!(ok_texts(result).len(), count);
1445    }
1446
1447    #[rstest]
1448    #[case("> A quote.\n\n> Another quote.", 2)]
1449    #[case("No blockquotes.", 0)]
1450    fn test_extract_blockquotes(#[case] markdown: &str, #[case] count: usize) {
1451        let server = Server::new(EngineConfig::default());
1452        let result = server
1453            .extract_blockquotes(Parameters(md(markdown)))
1454            .unwrap();
1455        assert_eq!(ok_texts(result).len(), count);
1456    }
1457
1458    const SECTION_MD: &str = "\
1459# Introduction\n\
1460\n\
1461Welcome.\n\
1462\n\
1463## Installation\n\
1464\n\
1465Run the command.\n\
1466\n\
1467## Usage\n\
1468\n\
1469Use it like this.\n";
1470
1471    #[test]
1472    fn test_extract_sections() {
1473        let server = Server::new(EngineConfig::default());
1474        let result = server.extract_sections(Parameters(md(SECTION_MD))).unwrap();
1475        let texts = ok_texts(result);
1476        assert!(!texts.is_empty());
1477        let joined = texts.join("\n");
1478        assert!(joined.contains("Introduction"));
1479        assert!(joined.contains("Installation"));
1480        assert!(joined.contains("Usage"));
1481    }
1482
1483    fn section_input(markdown: &str, title: &str) -> ExtractSectionInput {
1484        ExtractSectionInput {
1485            doc: DocumentInput::inline(markdown),
1486            title: title.to_string(),
1487            output: OutputOptions::default(),
1488        }
1489    }
1490
1491    #[rstest]
1492    #[case("Installation", true)]
1493    #[case("Nonexistent", false)]
1494    fn test_extract_section(#[case] title: &str, #[case] should_have_content: bool) {
1495        let server = Server::new(EngineConfig::default());
1496        let result = server
1497            .extract_section(Parameters(section_input(SECTION_MD, title)))
1498            .unwrap();
1499        let texts = ok_texts(result);
1500        assert_eq!(!texts.is_empty(), should_have_content);
1501        if should_have_content {
1502            assert!(texts.join("\n").contains(title));
1503        }
1504    }
1505
1506    #[test]
1507    fn test_extract_section_title_with_special_chars() {
1508        let md = "## Section \"quoted\"\n\nContent.";
1509        let server = Server::new(EngineConfig::default());
1510        let result = server
1511            .extract_section(Parameters(section_input(md, "Section \"quoted\"")))
1512            .unwrap();
1513        let texts = ok_texts(result);
1514        assert!(!texts.is_empty());
1515    }
1516
1517    #[test]
1518    fn test_extract_toc() {
1519        let server = Server::new(EngineConfig::default());
1520        let result = server.extract_toc(Parameters(md(SECTION_MD))).unwrap();
1521        let texts = ok_texts(result);
1522        assert!(!texts.is_empty());
1523        let joined = texts.join("\n");
1524        assert!(joined.contains("Introduction"));
1525        assert!(joined.contains("Installation"));
1526        assert!(joined.contains("Usage"));
1527    }
1528
1529    #[test]
1530    fn test_available_functions() {
1531        let server = Server::new(EngineConfig::default());
1532        let result = server
1533            .available_functions(Parameters(FunctionFilter::default()))
1534            .unwrap();
1535        assert!(!result.is_error.unwrap_or_default());
1536        assert_eq!(result.content.into_iter().len(), 1);
1537    }
1538
1539    #[test]
1540    fn test_available_selectors() {
1541        let server = Server::new(EngineConfig::default());
1542        let result = server.available_selectors().unwrap();
1543        assert!(!result.is_error.unwrap_or_default());
1544        assert_eq!(result.content.into_iter().len(), 1);
1545    }
1546
1547    #[test]
1548    fn test_get_info() {
1549        let server = Server::new(EngineConfig::default());
1550        let info = server.get_info();
1551        assert_eq!(info.protocol_version, ProtocolVersion::V_2025_06_18);
1552        assert!(info.instructions.is_some());
1553        let instructions = info.instructions.unwrap();
1554        assert!(
1555            instructions.contains("mq is a tool for processing markdown content"),
1556            "Instructions should mention mq"
1557        );
1558        assert!(
1559            !instructions.contains("pass `path`"),
1560            "file access is off, so `path` shouldn't be advertised"
1561        );
1562    }
1563
1564    #[test]
1565    fn test_get_info_advertises_roots_when_file_access_is_enabled() {
1566        let (_tmp, server) = server_with_files(&[]);
1567        let instructions = server.get_info().instructions.unwrap();
1568        assert!(
1569            instructions.contains("pass `path`") && instructions.contains("root"),
1570            "{instructions}"
1571        );
1572    }
1573
1574    #[test]
1575    fn test_available_functions_filter() {
1576        let server = Server::new(EngineConfig::default());
1577        let result = server
1578            .available_functions(Parameters(FunctionFilter {
1579                filter: Some("upcase".to_string()),
1580            }))
1581            .unwrap();
1582        let json: serde_json::Value = serde_json::from_str(&ok_texts(result)[0]).unwrap();
1583        let functions = json["functions"].as_array().unwrap();
1584        assert!(!functions.is_empty());
1585        assert!(functions.len() < 20);
1586    }
1587
1588    #[test]
1589    fn test_timeout_is_enforced_and_clamped() {
1590        let server = Server::new(EngineConfig {
1591            max_timeout: Duration::from_millis(50),
1592            ..EngineConfig::default()
1593        });
1594        // Requested 1h, clamped to 50ms: an endless loop must be cut off.
1595        let result = server
1596            .extract_markdown(Parameters(QueryForMarkdown {
1597                timeout_ms: Some(3_600_000),
1598                ..query_for("# a", "while(true): 1 end")
1599            }))
1600            .unwrap();
1601        assert!(result.is_error.unwrap_or_default());
1602        let msg = result.content[0].as_text().unwrap().text.to_lowercase();
1603        assert!(msg.contains("timed out"), "unexpected error: {msg}");
1604    }
1605
1606    // --- reading files through `path` ---
1607
1608    #[test]
1609    fn test_path_reads_file_inside_root() {
1610        let (_tmp, server) = server_with_files(&[("docs/guide.md", "# Guide\n\n## Part")]);
1611        let result = server
1612            .extract_headings(Parameters(MarkdownInput {
1613                doc: DocumentInput::file("docs/guide.md"),
1614                output: OutputOptions::default(),
1615            }))
1616            .unwrap();
1617        assert_eq!(ok_texts(result), ["# Guide", "## Part"]);
1618    }
1619
1620    #[rstest]
1621    #[case::parent_traversal("../outside/secret.md")]
1622    #[case::nested_traversal("docs/../../outside/secret.md")]
1623    fn test_path_outside_root_is_rejected(#[case] path: &str) {
1624        let (_tmp, server) = server_with_files(&[("docs/guide.md", "# Guide")]);
1625        let result = server
1626            .extract_headings(Parameters(MarkdownInput {
1627                doc: DocumentInput::file(path),
1628                output: OutputOptions::default(),
1629            }))
1630            .unwrap();
1631        let msg = error_text(result);
1632        assert!(msg.contains("outside the allowed directories"), "{msg}");
1633        assert!(!msg.contains("Secret"), "file content must not leak: {msg}");
1634    }
1635
1636    #[test]
1637    fn test_path_is_rejected_when_file_access_is_disabled() {
1638        let server = Server::new(EngineConfig::default());
1639        let result = server
1640            .extract_headings(Parameters(MarkdownInput {
1641                doc: DocumentInput::file("/etc/hosts"),
1642                output: OutputOptions::default(),
1643            }))
1644            .unwrap();
1645        assert!(error_text(result).contains("disabled"));
1646    }
1647
1648    #[rstest]
1649    #[case::both(DocumentInput { markdown: Some("# a".to_string()), path: Some("a.md".to_string()) }, "not both")]
1650    #[case::neither(DocumentInput::default(), "`path`")]
1651    fn test_markdown_and_path_are_exclusive(#[case] doc: DocumentInput, #[case] expected: &str) {
1652        let (_tmp, server) = server_with_files(&[("a.md", "# a")]);
1653        let result = server
1654            .extract_headings(Parameters(MarkdownInput {
1655                doc,
1656                output: OutputOptions::default(),
1657            }))
1658            .unwrap();
1659        let msg = error_text(result);
1660        assert!(msg.contains(expected), "{msg}");
1661    }
1662
1663    #[test]
1664    fn test_mq_builtins_cannot_bypass_the_allowed_directories() {
1665        let (tmp, server) = server_with_files(&[("inside.md", "# Inside")]);
1666        let secret = tmp.path().join("outside/secret.md");
1667        let inside = tmp.path().join("root/inside.md");
1668
1669        for query in [
1670            format!(r#"read_file("{}")"#, secret.display()),
1671            format!(r#"read_file("{}")"#, inside.display()),
1672            format!(r#"file_exists("{}")"#, secret.display()),
1673            r#"env("HOME")"#.to_string(),
1674        ] {
1675            let result = server
1676                .extract_markdown(Parameters(query_for("# a", &query)))
1677                .unwrap();
1678            let outcome = if result.is_error.unwrap_or_default() {
1679                error_text(result)
1680            } else {
1681                ok_texts(result).join("\n")
1682            };
1683            assert!(
1684                !outcome.contains("Secret") && !outcome.contains("Inside"),
1685                "`{query}` reached the filesystem: {outcome}"
1686            );
1687            assert!(
1688                outcome.is_empty() || outcome.contains("Failed") || outcome.contains("false"),
1689                "`{query}` unexpectedly succeeded: {outcome}"
1690            );
1691        }
1692    }
1693
1694    // --- paging, limits and formats ---
1695
1696    const FIVE_HEADINGS: &str = "# One\n\n# Two\n\n# Three\n\n# Four\n\n# Five\n";
1697
1698    #[test]
1699    fn test_limit_and_offset_page_through_results() {
1700        let server = Server::new(EngineConfig::default());
1701        let page = |offset, limit| {
1702            ok_texts(
1703                server
1704                    .extract_headings(Parameters(md_with(
1705                        FIVE_HEADINGS,
1706                        OutputOptions {
1707                            offset,
1708                            limit,
1709                            ..OutputOptions::default()
1710                        },
1711                    )))
1712                    .unwrap(),
1713            )
1714        };
1715
1716        let first = page(None, Some(2));
1717        assert_eq!(&first[..2], ["# One", "# Two"]);
1718        assert_eq!(first.len(), 3, "two results plus the continuation note");
1719        assert!(
1720            first[2].contains("1-2 of 5") && first[2].contains("offset=2"),
1721            "{}",
1722            first[2]
1723        );
1724
1725        let last = page(Some(3), None);
1726        assert_eq!(
1727            last,
1728            ["# Four", "# Five"],
1729            "no note when nothing is left out"
1730        );
1731
1732        let past_end = page(Some(9), None);
1733        assert_eq!(past_end.len(), 1);
1734        assert!(past_end[0].contains("past the end"), "{}", past_end[0]);
1735    }
1736
1737    #[test]
1738    fn test_output_is_cut_at_max_output_chars_and_says_how_to_continue() {
1739        let paragraphs = (0..10)
1740            .map(|i| format!("# H{i} {}", "x".repeat(80)))
1741            .collect::<Vec<_>>()
1742            .join("\n\n");
1743        let server = Server::new(EngineConfig {
1744            max_output_chars: 500,
1745            ..EngineConfig::default()
1746        });
1747        let texts = ok_texts(
1748            server
1749                .extract_headings(Parameters(md(&paragraphs)))
1750                .unwrap(),
1751        );
1752
1753        let (note, results) = texts.split_last().unwrap();
1754        assert!(results.len() < 10 && !results.is_empty());
1755        assert!(results.iter().map(|r| r.chars().count()).sum::<usize>() <= 500);
1756        assert!(
1757            note.contains(&format!("offset={}", results.len())),
1758            "{note}"
1759        );
1760
1761        // A caller can't lift the server's cap.
1762        let greedy = ok_texts(
1763            server
1764                .extract_headings(Parameters(md_with(
1765                    &paragraphs,
1766                    OutputOptions {
1767                        max_output_chars: Some(1_000_000),
1768                        ..OutputOptions::default()
1769                    },
1770                )))
1771                .unwrap(),
1772        );
1773        assert_eq!(greedy.len(), texts.len());
1774    }
1775
1776    #[test]
1777    fn test_a_single_oversized_result_is_cut() {
1778        let big = format!("# {}", "y".repeat(5000));
1779        let server = Server::new(EngineConfig {
1780            max_output_chars: 300,
1781            ..EngineConfig::default()
1782        });
1783        let texts = ok_texts(server.extract_headings(Parameters(md(&big))).unwrap());
1784        assert_eq!(
1785            texts.len(),
1786            2,
1787            "the cut result and a note about it: {texts:?}"
1788        );
1789        assert!(texts[0].ends_with("[truncated]"));
1790        assert!(texts[0].chars().count() < 400);
1791        assert!(texts[1].contains("cut to 300 characters"), "{}", texts[1]);
1792    }
1793
1794    #[test]
1795    fn test_json_format_describes_nodes_with_attributes_and_positions() {
1796        let markdown = "# Title\n\n```rust\nfn main() {}\n```\n\n[Rust](https://rust-lang.org)\n";
1797        let server = Server::new(EngineConfig::default());
1798        let json = OutputOptions {
1799            format: Some(OutputFormat::Json),
1800            ..OutputOptions::default()
1801        };
1802
1803        let code = structured(
1804            server
1805                .extract_code_blocks(Parameters(md_with(markdown, json.clone())))
1806                .unwrap(),
1807        );
1808        let block = &code["results"][0];
1809        assert_eq!(block["type"], "code");
1810        assert_eq!(block["lang"], "rust");
1811        assert_eq!(block["value"], "fn main() {}");
1812        assert!(block["text"].as_str().unwrap().starts_with("```rust"));
1813        assert_eq!(block["position"]["start"]["line"], 3);
1814        assert_eq!(block["position"]["end"]["line"], 5);
1815
1816        let heading = structured(
1817            server
1818                .extract_headings(Parameters(md_with(markdown, json.clone())))
1819                .unwrap(),
1820        );
1821        assert_eq!(heading["results"][0]["type"], "h1");
1822        assert_eq!(heading["results"][0]["depth"], 1);
1823        assert_eq!(heading["results"][0]["position"]["start"]["line"], 1);
1824
1825        let links = structured(
1826            server
1827                .extract_links(Parameters(md_with(markdown, json)))
1828                .unwrap(),
1829        );
1830        assert_eq!(links["results"][0]["type"], "link");
1831        assert_eq!(links["results"][0]["url"], "https://rust-lang.org");
1832        assert_eq!(links["total"], 1);
1833        assert_eq!(links["returned"], 1);
1834        assert!(links["next_offset"].is_null());
1835    }
1836
1837    #[test]
1838    fn test_json_format_pages_results() {
1839        let server = Server::new(EngineConfig::default());
1840        let json = |offset, limit| OutputOptions {
1841            format: Some(OutputFormat::Json),
1842            offset,
1843            limit,
1844            ..OutputOptions::default()
1845        };
1846
1847        let page = structured(
1848            server
1849                .extract_headings(Parameters(md_with(FIVE_HEADINGS, json(Some(1), Some(2)))))
1850                .unwrap(),
1851        );
1852        assert_eq!(page["total"], 5);
1853        assert_eq!(page["offset"], 1);
1854        assert_eq!(page["returned"], 2);
1855        assert_eq!(page["next_offset"], 3);
1856        assert_eq!(page["results"][0]["text"], "# Two");
1857
1858        // Computed results come back as nodes too, with their text.
1859        let result = server
1860            .extract_markdown(Parameters(QueryForMarkdown {
1861                output: json(None, None),
1862                ..query_for("# Title", r#""abc" | upcase()"#)
1863            }))
1864            .unwrap();
1865        let value = structured(result);
1866        assert_eq!(value["results"][0]["type"], "text");
1867        assert_eq!(value["results"][0]["text"], "ABC");
1868    }
1869
1870    // --- new tools ---
1871
1872    #[test]
1873    fn test_document_outline() {
1874        let (_tmp, server) = server_with_files(&[("doc.md", SECTION_MD)]);
1875        let outline = structured(
1876            server
1877                .document_outline(Parameters(OutlineInput {
1878                    doc: DocumentInput::file("doc.md"),
1879                    max_depth: None,
1880                }))
1881                .unwrap(),
1882        );
1883
1884        assert_eq!(outline["stats"]["headings"], 3);
1885        let headings = outline["headings"].as_array().unwrap();
1886        assert_eq!(headings.len(), 3);
1887        assert_eq!(headings[0]["title"], "Introduction");
1888        assert_eq!(headings[0]["subsections"], 2);
1889        assert_eq!(headings[1]["title"], "Installation");
1890        assert_eq!(headings[1]["line"], 5);
1891        assert_eq!(headings[1]["end_line"], 8);
1892    }
1893
1894    #[test]
1895    fn test_document_outline_reports_input_errors() {
1896        let server = Server::new(EngineConfig::default());
1897        let result = server
1898            .document_outline(Parameters(OutlineInput {
1899                doc: DocumentInput::default(),
1900                max_depth: None,
1901            }))
1902            .unwrap();
1903        assert!(error_text(result).contains("markdown"));
1904    }
1905
1906    #[test]
1907    fn test_extract_frontmatter() {
1908        let server = Server::new(EngineConfig::default());
1909        let found = structured(
1910            server
1911                .extract_frontmatter(Parameters(DocumentInput::inline(
1912                    "---\ntitle: Hello\ntags: [a, b]\n---\n\n# Body\n",
1913                )))
1914                .unwrap(),
1915        );
1916        assert_eq!(found["found"], true);
1917        assert_eq!(found["format"], "yaml");
1918        assert_eq!(
1919            found["data"],
1920            json!({ "title": "Hello", "tags": ["a", "b"] })
1921        );
1922
1923        let none = structured(
1924            server
1925                .extract_frontmatter(Parameters(DocumentInput::inline("# Body\n")))
1926                .unwrap(),
1927        );
1928        assert_eq!(none["found"], false);
1929    }
1930
1931    fn validate(query: &str, sample: Option<&str>) -> Value {
1932        let server = Server::new(EngineConfig::default());
1933        structured(
1934            server
1935                .validate_query(Parameters(ValidateQueryInput {
1936                    query: query.to_string(),
1937                    sample: sample.map_or_else(DocumentInput::default, DocumentInput::inline),
1938                    timeout_ms: None,
1939                }))
1940                .unwrap(),
1941        )
1942    }
1943
1944    #[test]
1945    fn test_validate_query_accepts_a_good_query() {
1946        let result = validate(".h2", None);
1947        assert_eq!(result["valid"], true);
1948        assert_eq!(result["issues"], json!([]));
1949        assert!(result.get("dry_run").is_none_or(Value::is_null));
1950    }
1951
1952    #[test]
1953    fn test_validate_query_reports_syntax_errors_and_unknown_functions() {
1954        let syntax = validate("select(.code | upcase(", None);
1955        assert_eq!(syntax["valid"], false);
1956        assert_eq!(syntax["issues"][0]["kind"], "syntax");
1957        assert!(syntax["issues"][0]["line"].is_number());
1958
1959        let unknown = validate("upcasee()", None);
1960        assert_eq!(unknown["valid"], false);
1961        assert_eq!(unknown["issues"][0]["kind"], "unresolved");
1962        assert!(
1963            unknown["issues"][0]["message"]
1964                .as_str()
1965                .unwrap()
1966                .contains("upcase")
1967        );
1968    }
1969
1970    #[test]
1971    fn test_validate_query_dry_run() {
1972        let ok = validate(".h", Some(FIVE_HEADINGS));
1973        assert_eq!(ok["valid"], true);
1974        assert_eq!(ok["dry_run"]["match_count"], 5);
1975        assert_eq!(ok["dry_run"]["samples"].as_array().unwrap().len(), 3);
1976        assert_eq!(ok["dry_run"]["samples"][0], "# One");
1977
1978        // A query that parses but fails at runtime is still "valid"; the failure is in dry_run.
1979        let runtime = validate("1 / 0", Some("# a"));
1980        assert_eq!(runtime["valid"], true);
1981        assert!(runtime["dry_run"]["error"].is_string(), "{runtime}");
1982
1983        // No dry run when the query is already known to be broken.
1984        let broken = validate("upcasee()", Some("# a"));
1985        assert!(broken.get("dry_run").is_none_or(Value::is_null));
1986    }
1987
1988    #[test]
1989    fn test_list_files() {
1990        let (_tmp, server) = server_with_files(&[
1991            ("a.md", ""),
1992            ("docs/b.md", "# b"),
1993            ("docs/page.html", "<p>x</p>"),
1994            (".hidden/c.md", ""),
1995        ]);
1996
1997        let list =
1998            |input: ListFilesInput| structured(server.list_files(Parameters(input)).unwrap());
1999        let names = |value: &Value| -> Vec<String> {
2000            value["files"]
2001                .as_array()
2002                .unwrap()
2003                .iter()
2004                .map(|f| {
2005                    std::path::Path::new(f["path"].as_str().unwrap())
2006                        .file_name()
2007                        .unwrap()
2008                        .to_string_lossy()
2009                        .to_string()
2010                })
2011                .collect()
2012        };
2013
2014        let all = list(ListFilesInput::default());
2015        assert_eq!(names(&all), ["a.md", "b.md"]);
2016        assert_eq!(all["truncated"], false);
2017        assert_eq!(all["roots"].as_array().unwrap().len(), 1);
2018        assert_eq!(all["files"][1]["size_bytes"], 3);
2019
2020        let html = list(ListFilesInput {
2021            directory: Some("docs".to_string()),
2022            extensions: Some(vec![".html".to_string()]),
2023            limit: None,
2024        });
2025        assert_eq!(names(&html), ["page.html"]);
2026
2027        let limited = list(ListFilesInput {
2028            limit: Some(1),
2029            ..ListFilesInput::default()
2030        });
2031        assert_eq!(limited["truncated"], true);
2032
2033        // Every listed path is accepted by the other tools.
2034        let path = all["files"][1]["path"].as_str().unwrap();
2035        let headings = server
2036            .extract_headings(Parameters(MarkdownInput {
2037                doc: DocumentInput::file(path),
2038                output: OutputOptions::default(),
2039            }))
2040            .unwrap();
2041        assert_eq!(ok_texts(headings), ["# b"]);
2042    }
2043
2044    #[test]
2045    fn test_list_files_rejects_outside_directory_and_disabled_access() {
2046        let (_tmp, server) = server_with_files(&[]);
2047        let result = server
2048            .list_files(Parameters(ListFilesInput {
2049                directory: Some("../outside".to_string()),
2050                ..ListFilesInput::default()
2051            }))
2052            .unwrap();
2053        assert!(error_text(result).contains("outside the allowed directories"));
2054
2055        let disabled = Server::new(EngineConfig::default())
2056            .list_files(Parameters(ListFilesInput::default()))
2057            .unwrap();
2058        assert!(error_text(disabled).contains("disabled"));
2059    }
2060
2061    #[test]
2062    fn test_tools_with_structured_output_declare_a_schema() {
2063        let server = Server::new(EngineConfig::default());
2064        let tools = server.tool_router.list_all();
2065        let has_schema = |name: &str| {
2066            tools
2067                .iter()
2068                .find(|t| t.name == name)
2069                .unwrap_or_else(|| panic!("missing tool {name}"))
2070                .output_schema
2071                .is_some()
2072        };
2073
2074        for name in [
2075            "document_outline",
2076            "extract_frontmatter",
2077            "validate_query",
2078            "list_files",
2079            "extract_markdown_batch",
2080        ] {
2081            assert!(has_schema(name), "{name} should declare an output schema");
2082        }
2083        // These return text or JSON depending on `format`, so they can't promise one shape.
2084        for name in ["extract_markdown", "extract_headings", "html_to_markdown"] {
2085            assert!(
2086                !has_schema(name),
2087                "{name} must not declare an output schema"
2088            );
2089        }
2090    }
2091
2092    #[test]
2093    fn test_inputs_accept_the_wire_format_of_flattened_parameters() {
2094        // MCP clients send flat JSON objects; flattened structs must accept them.
2095        let input: QueryForMarkdown = serde_json::from_value(json!({
2096            "path": "docs/a.md",
2097            "query": ".h",
2098            "format": "json",
2099            "limit": 5,
2100            "offset": 2,
2101            "max_output_chars": 1000,
2102            "timeout_ms": 500,
2103        }))
2104        .unwrap();
2105        assert_eq!(input.doc.path.as_deref(), Some("docs/a.md"));
2106        assert_eq!(input.output.format, Some(OutputFormat::Json));
2107        assert_eq!(input.output.limit, Some(5));
2108        assert_eq!(input.output.offset, Some(2));
2109        assert_eq!(input.output.max_output_chars, Some(1000));
2110        assert_eq!(input.timeout_ms, Some(500));
2111
2112        let inline: MarkdownInput = serde_json::from_value(json!({ "markdown": "# a" })).unwrap();
2113        assert_eq!(inline.doc.markdown.as_deref(), Some("# a"));
2114        assert_eq!(inline.output.format, None);
2115    }
2116}