grimoire_css 1.9.0

A magical CSS engine for all environments
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
use crate::{
    analyzer::Analyzer, build_with_options, component, init, shorten,
    transmutator::TransmuteOptions,
};
use serde::Serialize;
use serde_json::{Value, json};
use std::path::{Path, PathBuf};

const PROTOCOL_VERSION: &str = "2025-11-25";

pub struct McpServer {
    root: PathBuf,
}

impl McpServer {
    pub fn new(root: PathBuf) -> Self {
        Self { root }
    }

    pub fn root(&self) -> &Path {
        &self.root
    }

    pub fn dispatch(&self, request: Value) -> Option<Value> {
        let Some(request) = request.as_object() else {
            return Some(error_response(Value::Null, -32600, "Invalid Request"));
        };
        let id = request.get("id").cloned();
        let response_id = id.clone().unwrap_or(Value::Null);
        let valid_id = id
            .as_ref()
            .is_none_or(|id| id.is_null() || id.is_string() || id.is_number());
        let Some(method) = request.get("method").and_then(Value::as_str) else {
            return Some(error_response(response_id, -32600, "Invalid Request"));
        };
        if request.get("jsonrpc").and_then(Value::as_str) != Some("2.0") {
            return Some(error_response(response_id, -32600, "Invalid Request"));
        }
        if !valid_id {
            return Some(error_response(Value::Null, -32600, "Invalid Request"));
        }
        let params = request.get("params").cloned().unwrap_or_else(|| json!({}));
        let result = match method {
            "initialize" => Ok(json!({
                "protocolVersion": PROTOCOL_VERSION,
                "capabilities": {"resources": {}, "tools": {}},
                "serverInfo": {"name": "grimoire-css", "version": env!("CARGO_PKG_VERSION")},
                "instructions":"Use Grimoire CSS resources and tools instead of guessing. Before presenting Grimoire CSS code, call grimoire_validate_spells for every proposed spell. Use grimoire_transmute_css for CSS migration and grimoire_import_css only for an explicit project import. After creating or changing config or project files, call grimoire_validate_config and then grimoire_check_project. Do not claim completion unless the relevant validation result has valid=true."
            })),
            "ping" => Ok(json!({})),
            "resources/list" => Ok(resources()),
            "resources/read" => self.read_resource(&params),
            "tools/list" => Ok(json!({"tools": tools()})),
            "tools/call" => self.call_tool(&params),
            _ => return id.map(|id| error_response(id, -32601, "Method not found")),
        };
        let id = id?;
        Some(match result {
            Ok(result) => json!({"jsonrpc":"2.0","id":id,"result":result}),
            Err(message) => error_response(id, -32602, &message),
        })
    }

    fn read_resource(&self, params: &Value) -> Result<Value, String> {
        match string_arg(params, "uri")? {
            "grimoire://primer" => Ok(json!({"contents":[{
                "uri":"grimoire://primer",
                "mimeType":"text/markdown",
                "text": include_str!("primer.md")
            }]})),
            "grimoire://components" => {
                let text = serde_json::to_string_pretty(&component::get_all_components_map())
                    .map_err(|error| error.to_string())?;
                Ok(json!({"contents":[{
                    "uri":"grimoire://components",
                    "mimeType":"application/json",
                    "text":text
                }]}))
            }
            "grimoire://config-schema" => Ok(json!({"contents":[{
                "uri":"grimoire://config-schema",
                "mimeType":"application/schema+json",
                "text":include_str!("../core/config/config-schema.json")
            }]})),
            "grimoire://documentation" => Ok(json!({"contents":[{
                "uri":"grimoire://documentation",
                "mimeType":"text/markdown",
                "text":include_str!("../../README.md")
            }]})),
            _ => Err("Unknown Grimoire CSS resource".to_string()),
        }
    }

    fn call_tool(&self, params: &Value) -> Result<Value, String> {
        crate::buffer::discard_messages();
        let result = self.call_tool_inner(params);
        crate::buffer::discard_messages();
        result
    }

    fn call_tool_inner(&self, params: &Value) -> Result<Value, String> {
        let name = string_arg(params, "name")?;
        let arguments = params
            .get("arguments")
            .cloned()
            .unwrap_or_else(|| json!({}));
        match name {
            "grimoire_explain" => {
                exact_keys(&arguments, &["token"])?;
                domain_result(Analyzer::explain_class_token(
                    &self.root,
                    string_arg(&arguments, "token")?,
                ))
            }
            "grimoire_config_summary" => {
                exact_keys(&arguments, &[])?;
                domain_result(Analyzer::config_summary(&self.root))
            }
            "grimoire_index" => {
                exact_keys(&arguments, &["top"])?;
                domain_result(Analyzer::index(
                    &self.root,
                    usize_arg(&arguments, "top", 30)?,
                ))
            }
            "grimoire_lint" => {
                exact_keys(&arguments, &[])?;
                domain_result(Analyzer::lint(&self.root))
            }
            "grimoire_dry" => {
                exact_keys(&arguments, &["min_support", "min_items"])?;
                domain_result(Analyzer::dry_candidates(
                    &self.root,
                    usize_arg(&arguments, "min_support", 3)?,
                    usize_arg(&arguments, "min_items", 2)?,
                ))
            }
            "grimoire_list_variables" => {
                exact_keys(&arguments, &[])?;
                domain_result(Analyzer::list_grimoire_variables(&self.root))
            }
            "grimoire_list_scrolls" => {
                exact_keys(&arguments, &[])?;
                domain_result(Analyzer::config_summary(&self.root).map(|summary| summary.scrolls))
            }
            "grimoire_refs" => {
                exact_keys(&arguments, &["kind", "query"])?;
                let query = string_arg(&arguments, "query")?;
                match string_arg(&arguments, "kind")? {
                    "spell" => domain_result(Analyzer::refs_spell(&self.root, query)),
                    "scroll" => domain_result(Analyzer::refs_scroll(&self.root, query)),
                    "variable" => domain_result(Analyzer::refs_grimoire_variable(
                        &self.root,
                        query.trim_start_matches('$'),
                    )),
                    _ => Err("'kind' must be spell, scroll, or variable".to_string()),
                }
            }
            "grimoire_stats_spells" => {
                exact_keys(&arguments, &["top"])?;
                domain_result(Analyzer::stats_spells(
                    &self.root,
                    usize_arg(&arguments, "top", 30)?,
                ))
            }
            "grimoire_stats" => {
                exact_keys(&arguments, &["group", "token", "top"])?;
                domain_result(Analyzer::stats(
                    &self.root,
                    optional_string_arg(&arguments, "group")?,
                    optional_string_arg(&arguments, "token")?,
                    usize_arg(&arguments, "top", 30)?,
                ))
            }
            "grimoire_refs_auto" => {
                exact_keys(&arguments, &["query"])?;
                domain_result(Analyzer::refs(&self.root, string_arg(&arguments, "query")?))
            }
            "grimoire_validate_config" => {
                exact_keys(&arguments, &[])?;
                domain_result(Analyzer::validate_config(&self.root))
            }
            "grimoire_validate_spells" => {
                exact_keys(&arguments, &["tokens"])?;
                domain_result(Analyzer::validate_spells(
                    &self.root,
                    &string_array_arg(&arguments, "tokens")?,
                ))
            }
            "grimoire_check_project" => {
                exact_keys(&arguments, &[])?;
                domain_result(Analyzer::check_project(&self.root))
            }
            "grimoire_transmute_css" => {
                exact_keys(&arguments, &["content", "with_oneliner"])?;
                domain_result(Analyzer::transmute_and_validate(
                    &self.root,
                    string_arg(&arguments, "content")?,
                    TransmuteOptions {
                        with_oneliner: bool_arg(&arguments, "with_oneliner", false)?,
                    },
                ))
            }
            "grimoire_import_css" => {
                exact_keys(
                    &arguments,
                    &[
                        "content",
                        "paths",
                        "import_name",
                        "with_oneliner",
                        "replace",
                    ],
                )?;
                let content = optional_string_arg(&arguments, "content")?;
                let paths = optional_string_array_arg(&arguments, "paths")?;
                domain_result(Analyzer::import_css(
                    &self.root,
                    content,
                    paths.as_deref(),
                    string_arg(&arguments, "import_name")?,
                    TransmuteOptions {
                        with_oneliner: bool_arg(&arguments, "with_oneliner", false)?,
                    },
                    bool_arg(&arguments, "replace", false)?,
                ))
            }
            "grimoire_init" => {
                exact_keys(&arguments, &[])?;
                domain_result(init(&self.root))
            }
            "grimoire_build" => {
                exact_keys(&arguments, &["force_version_update"])?;
                domain_result(build_with_options(
                    &self.root,
                    bool_arg(&arguments, "force_version_update", false)?,
                ))
            }
            "grimoire_shorten" => {
                exact_keys(&arguments, &[])?;
                domain_result(shorten(&self.root))
            }
            _ => Err("Unknown Grimoire CSS tool".to_string()),
        }
    }
}

fn resources() -> Value {
    json!({"resources":[
        {"uri":"grimoire://primer","name":"Grimoire CSS primer","mimeType":"text/markdown"},
        {"uri":"grimoire://components","name":"Grimoire CSS components","mimeType":"application/json"},
        {"uri":"grimoire://config-schema","name":"Grimoire CSS config schema","mimeType":"application/schema+json"},
        {"uri":"grimoire://documentation","name":"Grimoire CSS documentation","mimeType":"text/markdown"}
    ]})
}

fn tools() -> Vec<Value> {
    vec![
        tool(
            "grimoire_explain",
            "Validate and explain a spell or scroll using the Grimoire CSS engine",
            object_schema(json!({"token":{"type":"string","minLength":1}}), &["token"]),
            true,
        ),
        tool(
            "grimoire_config_summary",
            "Read the existing Grimoire CSS configuration summary",
            object_schema(json!({}), &[]),
            true,
        ),
        tool(
            "grimoire_index",
            "Index Grimoire CSS tokens using the existing analyzer",
            object_schema(json!({"top":{"type":"integer","minimum":1}}), &[]),
            true,
        ),
        tool(
            "grimoire_lint",
            "Lint the project using the existing analyzer",
            object_schema(json!({}), &[]),
            true,
        ),
        tool(
            "grimoire_dry",
            "Find repeated token groups using the existing fi dry analysis",
            object_schema(
                json!({"min_support":{"type":"integer","minimum":1},"min_items":{"type":"integer","minimum":1}}),
                &[],
            ),
            true,
        ),
        tool(
            "grimoire_list_variables",
            "List configured Grimoire variables",
            object_schema(json!({}), &[]),
            true,
        ),
        tool(
            "grimoire_list_scrolls",
            "List configured Grimoire scrolls",
            object_schema(json!({}), &[]),
            true,
        ),
        tool(
            "grimoire_refs",
            "Find exact project references through the existing analyzer",
            object_schema(
                json!({
                    "kind":{"type":"string","enum":["spell","scroll","variable"]},
                    "query":{"type":"string","minLength":1}
                }),
                &["kind", "query"],
            ),
            true,
        ),
        tool(
            "grimoire_stats_spells",
            "Return the most frequent expanded spells from the existing analyzer",
            object_schema(json!({"top":{"type":"integer","minimum":1}}), &[]),
            true,
        ),
        tool(
            "grimoire_stats",
            "Return the existing fi statistics for spells, scrolls, variables, or one token",
            object_schema(
                json!({
                    "group":{"type":"string","enum":["all","spells","scrolls","vars"]},
                    "token":{"type":"string","minLength":1},
                    "top":{"type":"integer","minimum":1}
                }),
                &[],
            ),
            true,
        ),
        tool(
            "grimoire_refs_auto",
            "Resolve a reference query with the existing fi spell, scroll, and variable rules",
            object_schema(json!({"query":{"type":"string","minLength":1}}), &["query"]),
            true,
        ),
        tool(
            "grimoire_validate_config",
            "Validate the main and external project configs against the official schema and real engine loader",
            object_schema(json!({}), &[]),
            true,
        ),
        tool(
            "grimoire_validate_spells",
            "Validate proposed spells and scrolls through the real parser and CSS generator",
            object_schema(
                json!({
                    "tokens":{
                        "type":"array",
                        "minItems":1,
                        "maxItems":256,
                        "items":{"type":"string","minLength":1}
                    }
                }),
                &["tokens"],
            ),
            true,
        ),
        tool(
            "grimoire_check_project",
            "Run config validation, spell indexing, lint, and the real Grimoire CSS build",
            object_schema(json!({}), &[]),
            false,
        ),
        tool(
            "grimoire_transmute_css",
            "Convert inline CSS to typed Grimoire scrolls and validate every generated spell",
            object_schema(
                json!({
                    "content":{"type":"string","minLength":1},
                    "with_oneliner":{"type":"boolean","default":false}
                }),
                &["content"],
            ),
            true,
        ),
        tool(
            "grimoire_import_css",
            "Convert CSS into an external scroll file, verify the project, and roll back on failure",
            json!({
                "type":"object",
                "properties":{
                    "content":{"type":"string","minLength":1},
                    "paths":{
                        "type":"array",
                        "minItems":1,
                        "maxItems":256,
                        "items":{"type":"string","minLength":1}
                    },
                    "import_name":{
                        "type":"string",
                        "minLength":1,
                        "pattern":"^[A-Za-z0-9_-]+$"
                    },
                    "with_oneliner":{"type":"boolean","default":false},
                    "replace":{"type":"boolean","default":false}
                },
                "required":["import_name"],
                "oneOf":[{"required":["content"]},{"required":["paths"]}],
                "additionalProperties":false
            }),
            false,
        ),
        tool(
            "grimoire_init",
            "Initialize the project with the existing Grimoire CSS init API",
            object_schema(json!({}), &[]),
            false,
        ),
        tool(
            "grimoire_build",
            "Build CSS with the existing Grimoire CSS filesystem build API",
            object_schema(
                json!({"force_version_update":{"type":"boolean","default":false}}),
                &[],
            ),
            false,
        ),
        tool(
            "grimoire_shorten",
            "Rewrite configured project files with the existing Grimoire CSS shorten API",
            object_schema(json!({}), &[]),
            false,
        ),
    ]
}

fn tool(name: &str, description: &str, input_schema: Value, read_only: bool) -> Value {
    json!({
        "name":name,
        "description":description,
        "inputSchema":input_schema,
        "outputSchema":{
            "type":"object",
            "properties":{"data":{},"error":{"type":"string"}},
            "oneOf":[{"required":["data"]},{"required":["error"]}],
            "additionalProperties":false
        },
        "annotations":{
            "readOnlyHint":read_only,
            "destructiveHint":!read_only,
            "idempotentHint":read_only,
            "openWorldHint":false
        }
    })
}

fn object_schema(properties: Value, required: &[&str]) -> Value {
    json!({
        "type":"object",
        "properties":properties,
        "required":required,
        "additionalProperties":false
    })
}

fn string_arg<'a>(value: &'a Value, name: &str) -> Result<&'a str, String> {
    value
        .get(name)
        .and_then(Value::as_str)
        .filter(|value| !value.is_empty())
        .ok_or_else(|| format!("'{name}' must be a non-empty string"))
}

fn optional_string_arg<'a>(value: &'a Value, name: &str) -> Result<Option<&'a str>, String> {
    match value.get(name) {
        None => Ok(None),
        Some(value) => value
            .as_str()
            .filter(|value| !value.is_empty())
            .map(Some)
            .ok_or_else(|| format!("'{name}' must be a non-empty string")),
    }
}

fn string_array_arg(value: &Value, name: &str) -> Result<Vec<String>, String> {
    let values = value
        .get(name)
        .and_then(Value::as_array)
        .filter(|values| !values.is_empty() && values.len() <= 256)
        .ok_or_else(|| format!("'{name}' must contain between 1 and 256 strings"))?;
    if values
        .iter()
        .any(|value| value.as_str().is_none_or(str::is_empty))
    {
        return Err(format!("'{name}' must contain only non-empty strings"));
    }
    Ok(values
        .iter()
        .filter_map(Value::as_str)
        .map(str::to_string)
        .collect())
}

fn optional_string_array_arg(value: &Value, name: &str) -> Result<Option<Vec<String>>, String> {
    if value.get(name).is_none() {
        return Ok(None);
    }
    string_array_arg(value, name).map(Some)
}

fn usize_arg(value: &Value, name: &str, default: usize) -> Result<usize, String> {
    match value.get(name) {
        None => Ok(default),
        Some(value) => value
            .as_u64()
            .and_then(|value| usize::try_from(value).ok())
            .filter(|value| *value > 0)
            .ok_or_else(|| format!("'{name}' must be a positive integer")),
    }
}

fn bool_arg(value: &Value, name: &str, default: bool) -> Result<bool, String> {
    match value.get(name) {
        None => Ok(default),
        Some(value) => value
            .as_bool()
            .ok_or_else(|| format!("'{name}' must be a boolean")),
    }
}

fn exact_keys(value: &Value, allowed: &[&str]) -> Result<(), String> {
    let object = value
        .as_object()
        .ok_or_else(|| "tool arguments must be an object".to_string())?;
    if let Some(name) = object.keys().find(|name| !allowed.contains(&name.as_str())) {
        return Err(format!("unknown tool argument '{name}'"));
    }
    Ok(())
}

fn domain_result<T: Serialize>(
    result: Result<T, crate::GrimoireCssError>,
) -> Result<Value, String> {
    Ok(match result {
        Ok(value) => {
            let structured = serde_json::to_value(value).map_err(|error| error.to_string())?;
            let text =
                serde_json::to_string_pretty(&structured).map_err(|error| error.to_string())?;
            json!({
                "content":[{"type":"text","text":text}],
                "structuredContent":{"data":structured},
                "isError":false
            })
        }
        Err(error) => {
            let message = error.to_string();
            json!({
                "content":[{"type":"text","text":message}],
                "structuredContent":{"error":message},
                "isError":true
            })
        }
    })
}

fn error_response(id: Value, code: i64, message: &str) -> Value {
    json!({"jsonrpc":"2.0","id":id,"error":{"code":code,"message":message}})
}