scryer-mcp 0.2.1

Model Context Protocol (MCP) server for Scryer code intelligence
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
use gray_matter::engine::YAML;
use gray_matter::{Matter, Pod};
use pulldown_cmark::{Event, Parser, Tag, TagEnd};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::{Path, PathBuf};

use rmcp::model::Tool;
use scryer_db::ArchitecturalDecision;
use scryer_engine::EngineService;

use super::admin::{destructive, make_tool, mutating, read_only};
use super::adr_rank::{
    AdrCorpus, AdrSource, RankedAdr, invalidate_adr_corpus, load_corpus, rank_query,
};
use crate::context::ProjectContextResolver;

// --- Models ---

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct ParsedAdr {
    pub file_path: String,
    pub adr_number: Option<u32>,
    pub title: String,
    pub status: String,
    pub context: String,
    pub decision: String,
    pub consequences: String,
    /// Text outside the Context/Decision/Consequences sections.
    #[serde(default)]
    pub body: String,
    pub affected_paths: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct QueryAdrsParams {
    /// Keyword or query string to search ADRs and learnings.
    pub query: String,
    /// Keep only documents with this status: proposed, accepted, deprecated or superseded (case-insensitive).
    pub status: Option<String>,
    /// Zero-based offset for paginating matches.
    pub offset: Option<usize>,
    /// Maximum number of matches to return.
    pub limit: Option<usize>,
    /// If true, omits detailed matched_section text to save tokens.
    pub compact: Option<bool>,
    /// Custom token budget for this response.
    pub max_tokens: Option<usize>,
    /// If true, bypasses token budget truncation.
    pub no_truncate: Option<bool>,
    /// Optional project slug or ID override.
    pub project: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct AdrMatch {
    pub title: String,
    pub status: String,
    pub file_path: String,
    pub decision_summary: String,
    pub affected_paths: Vec<String>,
    pub matched_section: String,
    /// Integer relevance (rounded `score`, at least 1), kept for backward compatibility.
    pub relevance_score: usize,
    /// Ranking score (BM25 text match plus path/structural boosts), 2 decimal places.
    pub score: f64,
    /// Why this entry ranked, e.g. "affected_path 'crates/x/**' covers symbol file ...".
    pub match_reasons: Vec<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct QueryAdrsResult {
    pub query: String,
    pub total_matches: usize,
    pub returned_matches: usize,
    pub offset: usize,
    pub limit: Option<usize>,
    pub has_more: bool,
    pub matches: Vec<AdrMatch>,
    /// Why nothing matched, when a filter is the reason.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub notes: Vec<String>,
}

#[derive(Debug, Clone, Deserialize, JsonSchema)]
pub struct RecordAdrParams {
    /// Title of the architectural decision (e.g. "Use SQLite WAL Mode").
    pub title: String,
    /// Context and problem statement.
    pub context: String,
    /// The architectural decision taken.
    pub decision: String,
    /// Optional consequences (trade-offs, positive/negative outcomes).
    pub consequences: Option<String>,
    /// Optional affected path globs or prefixes (e.g. ["crates/scryer-db/**"]).
    pub affected_paths: Option<Vec<String>>,
    /// Status of the ADR (default: accepted).
    pub status: Option<super::enums::AdrStatus>,
    /// Custom token budget for this response.
    pub max_tokens: Option<usize>,
    /// If true, bypasses token budget truncation.
    pub no_truncate: Option<bool>,
    /// Optional project slug or ID override.
    pub project: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct RecordAdrResult {
    pub adr_number: u32,
    pub title: String,
    pub status: String,
    pub file_path: String,
    pub affected_paths: Vec<String>,
    pub message: String,
}

#[derive(Debug, Clone, Default, Deserialize, JsonSchema)]
pub struct DeleteAdrParams {
    /// Number of the ADR to delete (e.g. 7). Pass exactly one of adr_number, file_path or title.
    pub adr_number: Option<u32>,
    /// Path to the ADR file, which must be a .md file in the project's docs/adr directory.
    pub file_path: Option<String>,
    /// Exact title of the ADR (case-insensitive); an error if several ADRs share it.
    pub title: Option<String>,
    /// Custom token budget for this response.
    pub max_tokens: Option<usize>,
    /// If true, bypasses token budget truncation.
    pub no_truncate: Option<bool>,
    /// Optional project slug or ID override.
    pub project: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
pub struct DeleteAdrResult {
    pub success: bool,
    pub removed_file: Option<String>,
    pub removed_db_records: usize,
    pub message: String,
}

// --- Markdown Parser with Frontmatter & AST ---

pub fn parse_adr_markdown(file_path: &Path, content: &str) -> ParsedAdr {
    let matter = Matter::<YAML>::new();
    let (matter_data, markdown_content) = match matter.parse::<Pod>(content) {
        Ok(entity) => (entity.data, entity.content),
        Err(_) => (None, content.to_string()),
    };

    let mut title = file_path
        .file_stem()
        .and_then(|s| s.to_str())
        .unwrap_or("Untitled")
        .to_string();
    let mut status = "accepted".to_string();
    let mut affected_paths = Vec::new();
    let mut adr_number = None;

    if let Some(data) = matter_data
        && let Ok(val) = data.as_hashmap()
    {
        if let Some(Ok(t)) = val.get("title").map(|v| v.as_string()) {
            title = t;
        }
        if let Some(Ok(s)) = val.get("status").map(|v| v.as_string()) {
            status = s;
        }
        if let Some(Ok(num)) = val.get("number").map(|v| v.as_i64()) {
            adr_number = u32::try_from(num).ok();
        }
        if let Some(Ok(paths)) = val.get("affected_paths").map(|v| v.as_vec()) {
            for p in paths {
                if let Ok(s) = p.as_string() {
                    affected_paths.push(s);
                }
            }
        }
    }

    // Parse sections using pulldown-cmark AST
    let parser = Parser::new(&markdown_content);
    let mut current_heading = String::new();
    let mut in_heading = false;

    let mut context_text = String::new();
    let mut decision_text = String::new();
    let mut consequences_text = String::new();
    let mut general_text = String::new();

    for event in parser {
        match event {
            Event::Start(Tag::Heading { .. }) => {
                in_heading = true;
                current_heading.clear();
            }
            Event::End(TagEnd::Heading(_)) => {
                in_heading = false;
                let h_lower = current_heading.trim().to_lowercase();
                if title == "Untitled" || title.is_empty() {
                    title = current_heading.trim().to_string();
                }
                current_heading = h_lower;
            }
            // Inline code spans carry most identifiers in docs; index them like text.
            Event::Text(text) | Event::Code(text) => {
                if in_heading {
                    current_heading.push_str(&text);
                } else if current_heading.contains("context") {
                    context_text.push_str(&text);
                } else if current_heading.contains("decision") {
                    decision_text.push_str(&text);
                } else if current_heading.contains("consequence") {
                    consequences_text.push_str(&text);
                } else {
                    general_text.push_str(&text);
                }
            }
            _ => {}
        }
    }

    if context_text.is_empty() && decision_text.is_empty() {
        decision_text = std::mem::take(&mut general_text);
    }

    ParsedAdr {
        file_path: file_path.to_string_lossy().to_string(),
        adr_number,
        title,
        status,
        context: context_text.trim().to_string(),
        decision: decision_text.trim().to_string(),
        consequences: consequences_text.trim().to_string(),
        body: general_text.trim().to_string(),
        affected_paths,
    }
}

// --- Handlers ---

pub async fn handle_query_adrs(
    context: &ProjectContextResolver,
    engine: &EngineService,
    params: QueryAdrsParams,
) -> anyhow::Result<QueryAdrsResult> {
    let (project, _) = context
        .resolve_project(None, params.project.as_deref())
        .await?;
    let root = PathBuf::from(&project.root_path);
    let corpus = load_corpus(engine, project.id, &root).await?;
    let compact = params.compact.unwrap_or(false);

    // A status nothing has can only be a typo: say so instead of returning an empty list.
    if let Some(wanted) = params.status.as_deref() {
        let mut known: Vec<String> = ["proposed", "accepted", "deprecated", "superseded"]
            .iter()
            .map(|s| s.to_string())
            .collect();
        known.extend(corpus.entries.iter().map(|e| e.adr.status.to_lowercase()));
        known.sort();
        known.dedup();
        anyhow::ensure!(
            known.iter().any(|k| k.eq_ignore_ascii_case(wanted)),
            "Unknown status '{wanted}'; valid values: {}",
            known.join(", ")
        );
    }

    let ranked = rank_query(&corpus, &params.query, &root);
    let ranked_total = ranked.len();
    let matches: Vec<AdrMatch> = ranked
        .into_iter()
        .filter(|r| status_matches(&corpus, r, params.status.as_deref()))
        .map(|r| to_adr_match(&corpus, r, compact))
        .collect();
    let mut notes = Vec::new();
    if matches.is_empty()
        && ranked_total > 0
        && let Some(status) = &params.status
    {
        notes.push(format!(
            "{ranked_total} document(s) match the query but none has status '{status}'; drop `status` to see them"
        ));
    }
    let (paginated_matches, total_matches, offset, has_more) =
        paginate(matches, params.offset, params.limit);

    Ok(QueryAdrsResult {
        query: params.query,
        total_matches,
        returned_matches: paginated_matches.len(),
        offset,
        limit: params.limit,
        has_more,
        matches: paginated_matches,
        notes,
    })
}

fn status_matches(corpus: &AdrCorpus, ranked: &RankedAdr, status: Option<&str>) -> bool {
    status.is_none_or(|s| {
        corpus.entries[ranked.idx]
            .adr
            .status
            .eq_ignore_ascii_case(s)
    })
}

fn to_adr_match(corpus: &AdrCorpus, ranked: RankedAdr, compact: bool) -> AdrMatch {
    let entry = &corpus.entries[ranked.idx];
    let adr = &entry.adr;
    let matched_section = if compact {
        String::new()
    } else if entry.source == AdrSource::Db {
        "ArchitecturalDecision (Turso)".to_string()
    } else if !adr.context.is_empty() {
        "Context & Decision".to_string()
    } else {
        "Body".to_string()
    };
    AdrMatch {
        title: adr.title.clone(),
        status: adr.status.clone(),
        file_path: adr.file_path.clone(),
        decision_summary: truncate_string(&adr.decision, 200),
        affected_paths: adr.affected_paths.clone(),
        matched_section,
        relevance_score: (ranked.score.round() as usize).max(1),
        score: (ranked.score * 100.0).round() / 100.0,
        match_reasons: ranked.match_reasons,
    }
}

/// Returns `(page, total, offset, has_more)`.
fn paginate<T>(
    items: Vec<T>,
    offset: Option<usize>,
    limit: Option<usize>,
) -> (Vec<T>, usize, usize, bool) {
    let total = items.len();
    let offset = offset.unwrap_or(0);
    let page: Vec<T> = items
        .into_iter()
        .skip(offset)
        .take(limit.unwrap_or(usize::MAX))
        .collect();
    let has_more = offset + page.len() < total;
    (page, total, offset, has_more)
}

fn truncate_string(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        s.to_string()
    } else {
        let mut truncated: String = s.chars().take(max_len).collect();
        truncated.push_str("...");
        truncated
    }
}

pub async fn handle_record_adr(
    context: &ProjectContextResolver,
    engine: &EngineService,
    params: RecordAdrParams,
) -> anyhow::Result<RecordAdrResult> {
    let (project, _) = context
        .resolve_project(None, params.project.as_deref())
        .await?;
    let root = PathBuf::from(&project.root_path);
    let adr_dir = root.join("docs").join("adr");
    fs::create_dir_all(&adr_dir)?;

    // A title is one line: it lands in YAML frontmatter and a Markdown heading.
    let mut params = params;
    params.title = params
        .title
        .split_whitespace()
        .collect::<Vec<_>>()
        .join(" ");
    if params.title.is_empty() {
        anyhow::bail!("ADR title must not be empty");
    }

    // Determine next ADR number by checking disk and Turso
    let mut highest_num = 0u32;
    if let Ok(entries) = fs::read_dir(&adr_dir) {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file()
                && path.extension().and_then(|s| s.to_str()) == Some("md")
                && let Ok(content) = fs::read_to_string(&path)
            {
                let parsed = parse_adr_markdown(&path, &content);
                if let Some(num) = parsed.adr_number {
                    highest_num = highest_num.max(num);
                }
            }
        }
    }

    let mut guard = engine.db().lock().await;
    let db_adrs =
        ArchitecturalDecision::filter(ArchitecturalDecision::fields().project_id().eq(project.id))
            .exec(&mut *guard)
            .await?;
    for adr in &db_adrs {
        highest_num = highest_num.max(adr.adr_number);
    }

    let adr_number = highest_num + 1;
    let slug = slugify(&params.title);
    let filename = format!("{:04}-{}.md", adr_number, slug);
    let file_path = adr_dir.join(&filename);

    let status = params
        .status
        .unwrap_or(super::enums::AdrStatus::Accepted)
        .as_str()
        .to_string();
    let consequences = params.consequences.unwrap_or_default();
    let affected_paths = params.affected_paths.unwrap_or_default();

    // 1. Write Markdown file with frontmatter
    // JSON string escaping is valid YAML double-quoted escaping, so quotes and newlines in
    // user text can't break or forge the frontmatter.
    let quote = |s: &str| serde_json::to_string(s).unwrap_or_else(|_| "\"\"".to_string());
    let mut yaml_frontmatter = format!(
        "---\nnumber: {}\ntitle: {}\nstatus: {}\n",
        adr_number,
        quote(&params.title),
        quote(&status)
    );
    if !affected_paths.is_empty() {
        yaml_frontmatter.push_str("affected_paths:\n");
        for p in &affected_paths {
            yaml_frontmatter.push_str(&format!("  - {}\n", quote(p)));
        }
    }
    yaml_frontmatter.push_str("---\n\n");

    let body = format!(
        "# {}. {}\n\n## Context\n{}\n\n## Decision\n{}\n\n## Consequences\n{}\n",
        adr_number, params.title, params.context, params.decision, consequences
    );

    let full_content = format!("{}{}", yaml_frontmatter, body);

    // Database first, then the file, so a failed write can be rolled back: the DB row is
    // removed again and no orphan file is left behind. The DB guard stays held, so
    // concurrent calls can't pick the same number.
    let affected_paths_json = serde_json::to_string(&affected_paths)?;
    let created = ArchitecturalDecision::create()
        .project_id(project.id)
        .adr_number(adr_number)
        .title(params.title.clone())
        .status(status.clone())
        .context(params.context.clone())
        .decision(params.decision.clone())
        .consequences(consequences)
        .affected_paths(affected_paths_json)
        .exec(&mut *guard)
        .await?;

    let write_result = fs::OpenOptions::new()
        .write(true)
        .create_new(true)
        .open(&file_path)
        .and_then(|mut f| std::io::Write::write_all(&mut f, full_content.as_bytes()));
    if let Err(e) = write_result {
        let del_stmt = format!(
            "DELETE FROM architectural_decision WHERE project_id = {} AND id = {};",
            project.id, created.id
        );
        if let Err(del_err) = toasty::sql::statement(&del_stmt).exec(&mut *guard).await {
            tracing::warn!("Could not roll back ADR {adr_number} after write failure: {del_err}");
        }
        drop(guard);
        invalidate_adr_corpus(project.id);
        anyhow::bail!("Failed to write {}: {e}", file_path.display());
    }

    drop(guard);
    invalidate_adr_corpus(project.id);

    Ok(RecordAdrResult {
        adr_number,
        title: params.title,
        status,
        file_path: file_path.to_string_lossy().to_string(),
        affected_paths,
        message: format!(
            "ADR recorded successfully as #{:04} at {}",
            adr_number,
            file_path.display()
        ),
    })
}

pub async fn handle_delete_adr(
    context: &ProjectContextResolver,
    engine: &EngineService,
    params: DeleteAdrParams,
) -> anyhow::Result<DeleteAdrResult> {
    if params.adr_number.is_none() && params.file_path.is_none() && params.title.is_none() {
        anyhow::bail!(
            "At least one of 'adr_number', 'file_path', or 'title' must be specified to delete an ADR."
        );
    }

    let (project, _) = context
        .resolve_project(None, params.project.as_deref())
        .await?;
    let root = PathBuf::from(&project.root_path);
    let adr_dir = root.join("docs").join("adr");

    let mut removed_file = None;
    let mut target_number = params.adr_number;

    // 1. If explicit file_path provided
    if let Some(fp) = &params.file_path {
        let path = if Path::new(fp).is_absolute() {
            PathBuf::from(fp)
        } else {
            root.join(fp)
        };
        if path.exists() {
            // Only ADR markdown files inside <root>/docs/adr may be deleted.
            let canonical = path.canonicalize()?;
            let canonical_adr_dir = adr_dir.canonicalize().map_err(|_| {
                anyhow::anyhow!("ADR directory {} does not exist", adr_dir.display())
            })?;
            if !canonical.starts_with(&canonical_adr_dir)
                || canonical.extension().and_then(|s| s.to_str()) != Some("md")
            {
                anyhow::bail!(
                    "Refusing to delete '{}': file_path must be a .md file inside {}",
                    fp,
                    adr_dir.display()
                );
            }
            if let Ok(content) = fs::read_to_string(&path) {
                let parsed = parse_adr_markdown(&path, &content);
                if target_number.is_none() {
                    target_number = parsed.adr_number;
                }
            }
            fs::remove_file(&path)?;
            removed_file = Some(path.to_string_lossy().to_string());
        }
    }

    // 2. Scan adr_dir if file not yet removed
    if removed_file.is_none()
        && adr_dir.exists()
        && let Ok(entries) = fs::read_dir(&adr_dir)
    {
        for entry in entries.flatten() {
            let path = entry.path();
            if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("md") {
                let mut is_match = false;
                if let Some(num) = target_number {
                    let prefix = format!("{:04}-", num);
                    let alt_prefix = format!("{}-", num);
                    let fname = path.file_name().and_then(|s| s.to_str()).unwrap_or("");
                    if fname.starts_with(&prefix) || fname.starts_with(&alt_prefix) {
                        is_match = true;
                    }
                }
                if !is_match
                    && (target_number.is_some() || params.title.is_some())
                    && let Ok(content) = fs::read_to_string(&path)
                {
                    let parsed = parse_adr_markdown(&path, &content);
                    if let Some(num) = target_number
                        && parsed.adr_number == Some(num)
                    {
                        is_match = true;
                    }
                    if let Some(t) = &params.title
                        && parsed.title.eq_ignore_ascii_case(t)
                    {
                        is_match = true;
                        if target_number.is_none() {
                            target_number = parsed.adr_number;
                        }
                    }
                }

                if is_match {
                    fs::remove_file(&path)
                        .map_err(|e| anyhow::anyhow!("Failed to delete {}: {e}", path.display()))?;
                    removed_file = Some(path.to_string_lossy().to_string());
                    break;
                }
            }
        }
    }

    // 3. Delete matching records from Turso database
    let mut guard = engine.db().lock().await;
    let db_adrs =
        ArchitecturalDecision::filter(ArchitecturalDecision::fields().project_id().eq(project.id))
            .exec(&mut *guard)
            .await?;

    // Once a number is known (from the request or the removed file) only that ADR matches;
    // a title alone must identify exactly one.
    let matches_target =
        |adr: &ArchitecturalDecision| match (target_number, params.title.as_deref()) {
            (Some(n), _) => adr.adr_number == n,
            (None, Some(t)) => adr.title.eq_ignore_ascii_case(t),
            (None, None) => false,
        };
    if target_number.is_none() {
        let mut numbers: Vec<u32> = db_adrs
            .iter()
            .filter(|a| matches_target(a))
            .map(|a| a.adr_number)
            .collect();
        numbers.sort_unstable();
        numbers.dedup();
        if numbers.len() > 1 {
            anyhow::bail!("Title matches several ADRs ({numbers:?}); pass adr_number to pick one");
        }
    }

    let mut removed_db_records = 0;
    for adr in db_adrs {
        if matches_target(&adr) {
            let del_stmt = format!(
                "DELETE FROM architectural_decision WHERE project_id = {} AND id = {};",
                project.id, adr.id
            );
            toasty::sql::statement(&del_stmt).exec(&mut *guard).await?;
            removed_db_records += 1;
        }
    }

    drop(guard);
    invalidate_adr_corpus(project.id);

    let success = removed_file.is_some() || removed_db_records > 0;
    let message = if success {
        format!(
            "Successfully deleted ADR (file: {}, db records: {})",
            removed_file.as_deref().unwrap_or("none"),
            removed_db_records
        )
    } else {
        "No matching ADR found on disk or in database".to_string()
    };

    Ok(DeleteAdrResult {
        success,
        removed_file,
        removed_db_records,
        message,
    })
}

fn slugify(title: &str) -> String {
    let slug: String = title
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect();
    let trimmed = slug.trim_matches('-');
    let collapsed: String = trimmed
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-");
    if collapsed.is_empty() {
        "adr".to_string()
    } else {
        collapsed
    }
}

// --- Tool Definitions ---

pub fn tool_definitions() -> Vec<Tool> {
    vec![
        make_tool::<QueryAdrsParams>(
            "query_adrs",
            "Use before architectural changes to find prior decisions, invariants and lessons on a topic or path. Searches ADRs, learnings and plans by keywords or a path and explains each ranking in match_reasons.",
            read_only(),
        ),
        make_tool::<RecordAdrParams>(
            "record_adr",
            "Use after an architectural decision has been made and should be preserved for future contributors. Creates a numbered ADR Markdown file in docs/adr and indexes it so query_adrs and inspect_symbol can find it; status defaults to accepted.",
            mutating(false),
        ),
        make_tool::<DeleteAdrParams>(
            "delete_adr",
            "Use only when deletion of a specific ADR is explicitly intended. Removes the ADR file and its index record; identify it with exactly one of adr_number, file_path (inside docs/adr) or title.",
            destructive(),
        ),
    ]
}