lemma 0.8.18

A language that means business.
Documentation
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
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
mod imp {
    use anyhow::Result;
    use lemma::DateTimeValue;
    use lemma::Engine;
    use serde::{Deserialize, Serialize};
    use std::io::{self, BufRead, Write};
    use tracing::{debug, error, info};

    const PROTOCOL_VERSION: &str = "2024-11-05";
    const SERVER_VERSION: &str = env!("CARGO_PKG_VERSION");

    #[derive(Debug, Deserialize)]
    struct McpRequest {
        jsonrpc: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        id: Option<serde_json::Value>,
        method: String,
        #[serde(default)]
        params: Option<serde_json::Value>,
    }

    #[derive(Debug, Serialize)]
    struct McpResponse {
        jsonrpc: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        id: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        result: Option<serde_json::Value>,
        #[serde(skip_serializing_if = "Option::is_none")]
        error: Option<McpError>,
    }

    #[derive(Debug, Serialize)]
    struct McpError {
        code: i32,
        message: String,
        #[serde(skip_serializing_if = "Option::is_none")]
        data: Option<serde_json::Value>,
    }

    impl McpError {
        fn parse_error(message: String) -> Self {
            Self {
                code: -32700,
                message,
                data: None,
            }
        }

        fn invalid_request(message: String) -> Self {
            Self {
                code: -32600,
                message,
                data: None,
            }
        }

        fn method_not_found(method: String) -> Self {
            Self {
                code: -32601,
                message: format!("Method not found: {method}"),
                data: None,
            }
        }

        fn invalid_params(message: String) -> Self {
            Self {
                code: -32602,
                message,
                data: None,
            }
        }

        fn internal_error(message: String) -> Self {
            Self {
                code: -32603,
                message,
                data: None,
            }
        }
    }

    fn resolve_effective(args: &serde_json::Value) -> Result<DateTimeValue, McpError> {
        let raw = args.get("effective").and_then(|v| v.as_str());
        lemma::Engine::resolve_effective(raw)
            .map_err(|e| McpError::invalid_params(e.message().to_string()))
    }

    /// Configuration for the MCP server.
    #[derive(Default)]
    pub struct McpConfig {
        /// When true, admin tools (`add_spec`, `get_spec_source`) are
        /// advertised and allowed. When false (default), the server is read-only.
        pub admin: bool,
    }

    struct McpServer {
        engine: Engine,
        config: McpConfig,
    }

    impl McpServer {
        fn new(engine: Engine, config: McpConfig) -> Self {
            Self { engine, config }
        }

        /// JSON-RPC 2.0: requests with no `id` are notifications and MUST NOT
        /// receive a response (§4.1). Returns `None` for notifications, even
        /// on error, so the transport layer skips the write entirely.
        fn handle_request(&mut self, request: McpRequest) -> Option<McpResponse> {
            debug!("Handling request: method={}", request.method);

            let is_notification = request.id.is_none();

            if request.jsonrpc != "2.0" {
                if is_notification {
                    debug!("Dropping notification with bad jsonrpc version");
                    return None;
                }
                return Some(McpResponse {
                    jsonrpc: "2.0".to_string(),
                    id: request.id,
                    result: None,
                    error: Some(McpError::invalid_request(
                        "Invalid JSON-RPC version, expected '2.0'".to_string(),
                    )),
                });
            }

            if is_notification {
                match request.method.as_str() {
                    "notifications/initialized" => {
                        debug!("Client signalled notifications/initialized");
                    }
                    other => {
                        debug!("Ignoring notification: {}", other);
                    }
                }
                return None;
            }

            let result = match request.method.as_str() {
                "initialize" => self.initialize(),
                "tools/list" => self.list_tools(),
                "tools/call" => self.call_tool(request.params),
                _ => Err(McpError::method_not_found(request.method)),
            };

            Some(match result {
                Ok(result) => McpResponse {
                    jsonrpc: "2.0".to_string(),
                    id: request.id,
                    result: Some(result),
                    error: None,
                },
                Err(error) => McpResponse {
                    jsonrpc: "2.0".to_string(),
                    id: request.id,
                    result: None,
                    error: Some(error),
                },
            })
        }

        fn initialize(&self) -> Result<serde_json::Value, McpError> {
            info!("Initializing MCP server");
            Ok(serde_json::json!({
                "protocolVersion": PROTOCOL_VERSION,
                "serverInfo": {
                    "name": "lemma-mcp-server",
                    "version": SERVER_VERSION
                },
                "capabilities": {
                    "tools": {
                        "listChanged": false
                    }
                }
            }))
        }

        fn list_tools(&self) -> Result<serde_json::Value, McpError> {
            debug!("Listing tools");

            let mut tools = vec![
                serde_json::json!({
                    "name": "evaluate",
                "description": "Evaluate rules in a Lemma spec. Returns the result and a step-by-step reasoning trace showing which data were used and which conditions matched. Omit 'rule' to evaluate all rules.",
                            "inputSchema": {
                                "type": "object",
                                "properties": {
                                    "spec": {
                                        "type": "string",
                                        "description": "Spec set id, e.g. pricing"
                            },
                            "rule": {
                                "type": "string",
                                "description": "Optional: name of a specific rule to evaluate. Omit to evaluate all rules."
                            },
                            "data": {
                                "type": "array",
                                "items": { "type": "string" },
                                "description": "Optional data values as 'name=value' (e.g. ['price=100', 'quantity=5'])",
                                "default": []
                            },
                            "effective": {
                                "type": "string",
                                "description": "Optional: evaluate at a specific effective datetime (e.g. '2026', '2026-03', '2026-03-04', '2026-03-04T10:30:00Z')"
                            },
                            "conversions": {
                                "type": "array",
                                "items": { "type": "string" },
                                "description": "Optional quantity unit conversions as 'rule=unit' or 'rule:unit' (e.g. ['total=usd'])",
                                "default": []
                            }
                        },
                        "required": ["spec"]
                    }
                }),
                serde_json::json!({
                    "name": "list_specs",
                    "description": "List all loaded Lemma specs with their schemas: data names, types, defaults, and rule names with return types.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "effective": {
                                "type": "string",
                                "description": "Optional: list specs at a specific effective datetime (e.g. '2026', '2026-03-04')"
                            }
                        }
                    }
                }),
                serde_json::json!({
                    "name": "get_schema",
                "description": "Get a spec's schema: its data (inputs with types, constraints, and defaults) and rules (outputs with types). Optionally scope to a specific rule to see only the data it needs. Use this before calling evaluate to know which data to provide.",
                            "inputSchema": {
                                "type": "object",
                                "properties": {
                                    "spec": {
                                        "type": "string",
                                        "description": "Spec set id, e.g. pricing"
                                    },
                                    "rule": {
                                        "type": "string",
                                        "description": "Optional: name of a specific rule. Omit to get the full spec schema."
                                    },
                            "effective": {
                                "type": "string",
                                "description": "Optional: get schema at a specific effective datetime"
                            }
                        },
                        "required": ["spec"]
                    }
                }),
            ];

            if self.config.admin {
                tools.push(serde_json::json!({
                    "name": "add_spec",
                    "description": "Add Lemma source to the engine. Returns each new spec schema on success.",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "code": {
                                "type": "string",
                                "description": "The complete Lemma code to add"
                            },
                            "source_id": {
                                "type": "string",
                                "description": "Identifier for this source fragment (used as load path)"
                            }
                        },
                        "required": ["code", "source_id"]
                    }
                }));
                tools.push(serde_json::json!({
                    "name": "get_spec_source",
                    "description": "Return formatted Lemma source. Pass `repository` (e.g. `lemma` for embedded units stdlib) for the whole repo, or `spec` for a workspace spec.",
                            "inputSchema": {
                                "type": "object",
                                "properties": {
                                    "repository": {
                                        "type": "string",
                                        "description": "Repository qualifier (e.g. lemma). When set, returns formatted source for the entire repository."
                                    },
                                    "spec": {
                                        "type": "string",
                                        "description": "Workspace spec set id (when repository is omitted)"
                                    },
                            "effective": {
                                "type": "string",
                                "description": "Optional: get source at a specific effective datetime"
                            }
                        }
                    }
                }));
            }

            Ok(serde_json::json!({ "tools": tools }))
        }

        fn call_tool(
            &mut self,
            params: Option<serde_json::Value>,
        ) -> Result<serde_json::Value, McpError> {
            let params =
                params.ok_or_else(|| McpError::invalid_params("Missing params".to_string()))?;

            let tool_name = params["name"]
                .as_str()
                .ok_or_else(|| McpError::invalid_params("Missing tool name".to_string()))?;

            let arguments = params
                .get("arguments")
                .ok_or_else(|| McpError::invalid_params("Missing arguments".to_string()))?;

            debug!("Calling tool: {}", tool_name);

            match tool_name {
                "add_spec" | "get_spec_source" if !self.config.admin => {
                    Err(McpError::invalid_params(
                        "Admin tools are disabled. Start the server with --admin to enable them."
                            .to_string(),
                    ))
                }
                "add_spec" => self.tool_add_spec(arguments),
                "get_spec_source" => self.tool_get_spec_source(arguments),
                "evaluate" => self.tool_evaluate(arguments),
                "list_specs" => self.tool_list_specs(arguments),
                "get_schema" => self.tool_get_schema(arguments),
                _ => Err(McpError::invalid_params(format!(
                    "Unknown tool: {}",
                    tool_name
                ))),
            }
        }

        fn tool_add_spec(
            &mut self,
            args: &serde_json::Value,
        ) -> Result<serde_json::Value, McpError> {
            let code = args["code"]
                .as_str()
                .ok_or_else(|| McpError::invalid_params("Missing 'code' field".to_string()))?;

            if code.trim().is_empty() {
                return Err(McpError::invalid_params(
                    "Lemma source cannot be empty".to_string(),
                ));
            }

            let source_id = args["source_id"]
                .as_str()
                .map(str::trim)
                .filter(|s| !s.is_empty())
                .ok_or_else(|| McpError::invalid_params("Missing 'source_id' field".to_string()))?
                .to_string();

            let names_before: std::collections::HashSet<String> = self
                .engine
                .get_workspace()
                .specs
                .iter()
                .map(|ss| ss.name.clone())
                .collect();

            let source_type =
                lemma::SourceType::Path(std::sync::Arc::new(std::path::PathBuf::from(&source_id)));
            self.engine.load(code, source_type).map_err(|load_err| {
                for e in load_err.iter() {
                    error!(
                        "{}",
                        crate::error_formatter::format_error(e, &load_err.sources)
                    );
                }
                McpError::internal_error(format!(
                    "Failed to load Lemma source ({} error(s))",
                    load_err.errors.len()
                ))
            })?;

            let new_spec_names: Vec<String> = self
                .engine
                .get_workspace()
                .specs
                .iter()
                .filter(|ss| !names_before.contains(&ss.name))
                .map(|ss| ss.name.clone())
                .collect();

            let mut output = String::from("Spec added successfully.\n\n");

            let now = DateTimeValue::now();
            for spec_name in &new_spec_names {
                if let Ok(plan) = self.engine.get_plan(None, spec_name, Some(&now)) {
                    output.push_str(&plan.schema(&lemma::DataOverlay::default()).to_string());
                    output.push('\n');
                }
            }

            info!(
                "Spec added from source '{}': {:?}",
                source_id, new_spec_names
            );

            Ok(serde_json::json!({
                "content": [{
                    "type": "text",
                    "text": output
                }]
            }))
        }

        fn tool_get_spec_source(
            &self,
            args: &serde_json::Value,
        ) -> Result<serde_json::Value, McpError> {
            if let Some(repo) = args
                .get("repository")
                .and_then(|v| v.as_str())
                .map(str::trim)
                .filter(|s| !s.is_empty())
            {
                let source = self.engine.format_repository(repo).map_err(|e| {
                    McpError::invalid_params(format!(
                        "Repository '{}' not found: {}. Use list_specs to see loaded repositories.",
                        repo, e
                    ))
                })?;
                debug!("Returned formatted source for repository '{}'", repo);
                return Ok(serde_json::json!({
                    "content": [{
                        "type": "text",
                        "text": source
                    }]
                }));
            }

            let spec_set_id = args["spec"].as_str().ok_or_else(|| {
                McpError::invalid_params("Missing 'spec' or 'repository' field".to_string())
            })?;

            let spec_name = lemma::parse_spec_set_id(spec_set_id.trim())
                .map_err(|e| McpError::invalid_params(format!("{}", e)))?;

            let now = resolve_effective(args)?;
            let spec = self.engine.get_spec(&spec_name, Some(&now)).map_err(|e| {
                McpError::invalid_params(format!(
                    "Spec '{}' not found: {}. Use list_specs to see available specs.",
                    spec_set_id, e
                ))
            })?;

            let source = lemma::format_specs(std::slice::from_ref(spec.as_ref()));

            debug!("Returned source for spec '{}'", spec_name);

            Ok(serde_json::json!({
                "content": [{
                    "type": "text",
                    "text": source
                }]
            }))
        }

        fn tool_evaluate(
            &mut self,
            args: &serde_json::Value,
        ) -> Result<serde_json::Value, McpError> {
            let spec_set_id = args["spec"]
                .as_str()
                .ok_or_else(|| McpError::invalid_params("Missing 'spec' field".to_string()))?;

            if spec_set_id.trim().is_empty() {
                return Err(McpError::invalid_params(
                    "Spec set id cannot be empty".to_string(),
                ));
            }

            let spec_name = lemma::parse_spec_set_id(spec_set_id.trim())
                .map_err(|e| McpError::invalid_params(format!("{}", e)))?;

            let rule_names: Vec<String> = match args.get("rule").and_then(|v| v.as_str()) {
                Some(rule) if !rule.trim().is_empty() => vec![rule.trim().to_string()],
                _ => Vec::new(),
            };

            let data: Vec<&str> = args["data"]
                .as_array()
                .map(|arr| arr.iter().filter_map(|v| v.as_str()).collect())
                .unwrap_or_default();

            let data_values: std::collections::HashMap<String, String> = data
                .iter()
                .filter_map(|s| {
                    s.split_once('=')
                        .map(|(k, v)| (k.to_string(), v.to_string()))
                })
                .collect();

            let now = resolve_effective(args)?;

            let plan = self
                .engine
                .get_plan(None, &spec_name, Some(&now))
                .map_err(|e| {
                    error!("Evaluation failed: {}", e);
                    McpError::internal_error(format!("Evaluation failed: {e}"))
                })?;
            let rules = if rule_names.is_empty() {
                None
            } else {
                Some(rule_names.as_slice())
            };
            let data_input: std::collections::HashMap<String, lemma::DataValueInput> = data_values
                .into_iter()
                .map(|(k, v)| (k, lemma::DataValueInput::convenience(v)))
                .collect();
            let response = self
                .engine
                .run_plan(plan, Some(&now), data_input, true, rules)
                .map_err(|e| {
                    error!("Evaluation failed: {}", e);
                    McpError::internal_error(format!("Evaluation failed: {e}"))
                })?;

            let mut output = String::new();
            output.push_str(&format!("spec: {}\n", spec_set_id.trim()));
            output.push_str(&format!("effective: {}\n", now));
            output.push('\n');

            for result in response.results.values() {
                output.push_str(&format!("{}: ", result.rule.name));
                if result.vetoed {
                    if let Some(reason) = result.veto_reason.as_deref() {
                        output.push_str(reason);
                    }
                } else {
                    let display = result.display.as_deref().ok_or_else(|| {
                        McpError::internal_error(format!(
                            "Rule '{}' evaluated without display after evaluation",
                            result.rule.name
                        ))
                    })?;
                    output.push_str(display);
                }
                output.push('\n');

                if let Some(explanation) = &result.explanation {
                    let steps = lemma::format_explanation(explanation);
                    if !steps.is_empty() {
                        output.push_str("\nReasoning:\n");
                        output.push_str(&steps);
                        output.push('\n');
                    }
                }
            }

            info!(
                "Evaluated spec '{}' with {} results",
                spec_set_id.trim(),
                response.results.len()
            );

            Ok(serde_json::json!({
                "content": [{
                    "type": "text",
                    "text": output
                }]
            }))
        }

        fn tool_list_specs(&self, args: &serde_json::Value) -> Result<serde_json::Value, McpError> {
            let now = resolve_effective(args)?;
            let mut sections: Vec<String> = Vec::new();
            let mut spec_count = 0usize;

            for resolved in self.engine.list() {
                let label = crate::interactive::repo_label(resolved.repository.as_ref());
                let repo_q = resolved.repository.name.as_deref();
                let schemas: Vec<String> = resolved
                    .specs
                    .iter()
                    .flat_map(|ss| ss.iter_specs())
                    .filter_map(|spec| {
                        let effective = spec
                            .effective_from()
                            .cloned()
                            .unwrap_or_else(|| now.clone());
                        self.engine
                            .schema(repo_q, &spec.name, Some(&effective))
                            .ok()
                            .map(|s| s.to_string())
                    })
                    .collect();
                spec_count += schemas.len();
                if !schemas.is_empty() {
                    sections.push(format!("Repository: {}\n\n{}", label, schemas.join("\n\n")));
                }
            }

            let workspace_empty = self
                .engine
                .get_workspace()
                .specs
                .iter()
                .all(|ss| ss.iter_specs().next().is_none());

            let output = if spec_count == 0 {
                if self.config.admin {
                    "No specs loaded.\n\nUse the 'add_spec' tool to load Lemma source.".to_string()
                } else {
                    "No specs loaded.".to_string()
                }
            } else {
                let mut out = sections.join("\n\n---\n\n");
                if self.config.admin && workspace_empty {
                    out.push_str("\n\nUse the 'add_spec' tool to load workspace Lemma source.");
                }
                out
            };

            debug!("Listed {} specs across repositories", spec_count);

            Ok(serde_json::json!({
                "content": [{
                    "type": "text",
                    "text": output
                }]
            }))
        }

        fn tool_get_schema(&self, args: &serde_json::Value) -> Result<serde_json::Value, McpError> {
            let spec_set_id = args["spec"]
                .as_str()
                .ok_or_else(|| McpError::invalid_params("Missing 'spec' field".to_string()))?;

            if spec_set_id.trim().is_empty() {
                return Err(McpError::invalid_params(
                    "Spec set id cannot be empty".to_string(),
                ));
            }

            let spec_name = lemma::parse_spec_set_id(spec_set_id.trim())
                .map_err(|e| McpError::invalid_params(format!("{}", e)))?;

            let now = resolve_effective(args)?;
            let plan = self
                .engine
                .get_plan(None, &spec_name, Some(&now))
                .map_err(|_| {
                    McpError::invalid_params(format!(
                        "Spec '{}' not found. Use list_specs to see available specs.",
                        spec_set_id.trim()
                    ))
                })?;

            let rule_names: Vec<String> = match args.get("rule").and_then(|v| v.as_str()) {
                Some(rule) if !rule.trim().is_empty() => vec![rule.trim().to_string()],
                _ => Vec::new(),
            };

            let schema = if rule_names.is_empty() {
                plan.schema(&lemma::DataOverlay::default())
            } else {
                plan.schema_for_rules(&rule_names, &lemma::DataOverlay::default())
                    .map_err(|e| {
                        error!("schema_for_rules failed: {}", e);
                        McpError::internal_error(format!("Failed to get schema for rules: {e}"))
                    })?
            };

            let scope = if rule_names.is_empty() {
                format!("{} (all rules)", spec_set_id.trim())
            } else {
                format!("{}.{}", spec_set_id.trim(), rule_names[0])
            };

            let output = format!("Schema for {}:\n\n{}", scope, schema);

            info!(
                "Returned schema for '{}' ({} data, {} rules)",
                scope,
                schema.data.len(),
                schema.rules.len()
            );

            Ok(serde_json::json!({
                "content": [{
                    "type": "text",
                    "text": output
                }]
            }))
        }
    }

    pub fn start_server(engine: Engine, config: McpConfig) -> Result<()> {
        tracing_subscriber::fmt()
            .with_env_filter(
                tracing_subscriber::EnvFilter::try_from_default_env()
                    .unwrap_or_else(|_| "lemma_mcp=info".into()),
            )
            .with_writer(io::stderr)
            .init();

        info!("Starting Lemma MCP server v{}", SERVER_VERSION);
        info!("Protocol version: {}", PROTOCOL_VERSION);
        if config.admin {
            info!("Admin mode enabled (--admin)");
        } else {
            info!("Read-only mode (default)");
        }

        let mut server = McpServer::new(engine, config);
        let stdin = io::stdin();
        let mut stdout = io::stdout();

        for line in stdin.lock().lines() {
            let line = line?;

            if line.trim().is_empty() {
                continue;
            }

            debug!("Received: {}", line);

            // Parse error responds with id: null (JSON-RPC 2.0 §4.2). For
            // any successfully-parsed notification, handle_request returns
            // None and we MUST NOT write anything back.
            let response = match serde_json::from_str::<McpRequest>(&line) {
                Ok(request) => server.handle_request(request),
                Err(e) => {
                    error!("Parse error: {}", e);
                    Some(McpResponse {
                        jsonrpc: "2.0".to_string(),
                        id: None,
                        result: None,
                        error: Some(McpError::parse_error(format!("Parse error: {e}"))),
                    })
                }
            };

            if let Some(response) = response {
                let response_json = serde_json::to_string(&response)?;
                writeln!(stdout, "{}", response_json)?;
                stdout.flush()?;
                debug!("Sent response");
            } else {
                debug!("No response (notification)");
            }
        }

        info!("MCP server shutting down");
        Ok(())
    }

    #[cfg(test)]
    mod tests {
        use super::*;

        fn server() -> McpServer {
            McpServer::new(Engine::new(), McpConfig::default())
        }

        fn parse(line: &str) -> McpRequest {
            serde_json::from_str(line).expect("test fixture must be valid JSON-RPC")
        }

        #[test]
        fn notification_returns_no_response() {
            let mut s = server();
            let req = parse(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#);
            assert!(s.handle_request(req).is_none());
        }

        #[test]
        fn notification_with_unknown_method_still_silent() {
            let mut s = server();
            let req = parse(r#"{"jsonrpc":"2.0","method":"some/random/notification"}"#);
            assert!(s.handle_request(req).is_none());
        }

        #[test]
        fn notification_with_bad_jsonrpc_version_silent() {
            let mut s = server();
            let req = parse(r#"{"jsonrpc":"1.0","method":"notifications/initialized"}"#);
            assert!(s.handle_request(req).is_none());
        }

        #[test]
        fn request_with_id_gets_response() {
            let mut s = server();
            let req = parse(r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#);
            let resp = s.handle_request(req).expect("request must yield response");
            assert_eq!(resp.id, Some(serde_json::json!(1)));
            assert!(resp.result.is_some());
            assert!(resp.error.is_none());
        }

        #[test]
        fn request_with_unknown_method_returns_method_not_found() {
            let mut s = server();
            let req = parse(r#"{"jsonrpc":"2.0","id":7,"method":"does/not/exist"}"#);
            let resp = s.handle_request(req).expect("request must yield response");
            assert_eq!(resp.id, Some(serde_json::json!(7)));
            assert_eq!(resp.error.as_ref().expect("error expected").code, -32601);
        }

        #[test]
        fn request_with_bad_jsonrpc_version_returns_invalid_request() {
            let mut s = server();
            let req = parse(r#"{"jsonrpc":"1.0","id":2,"method":"initialize"}"#);
            let resp = s.handle_request(req).expect("request must yield response");
            assert_eq!(resp.error.as_ref().expect("error expected").code, -32600);
        }

        #[test]
        fn initialize_advertises_tools_list_changed_false() {
            let mut s = server();
            let req = parse(r#"{"jsonrpc":"2.0","id":1,"method":"initialize"}"#);
            let resp = s.handle_request(req).expect("request must yield response");
            let result = resp.result.expect("result expected");
            assert_eq!(result["capabilities"]["tools"]["listChanged"], false);
        }
    }
}

pub use imp::start_server;
pub use imp::McpConfig;