-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
2015 lines (1836 loc) · 73.6 KB
/
Copy pathserver.py
File metadata and controls
2015 lines (1836 loc) · 73.6 KB
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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Monospace Design TUI — MCP Server.
Exposes the Monospace TUI design system (palettes, tokens, components,
keyboard bindings, archetypes, and full standard/reference sections)
so that AI agents in other projects can query design rules when building
terminal user interfaces.
"""
from __future__ import annotations
import json
import re
import sys
import uuid
from pathlib import Path
from typing import Any, Optional
from mcp.server.fastmcp import Context, FastMCP
from mcp.types import SamplingMessage, TextContent
# ---------------------------------------------------------------------------
# Paths
# ---------------------------------------------------------------------------
PROJECT_ROOT = Path(__file__).resolve().parent.parent
MONO_DESIGNER_DIR = PROJECT_ROOT / "mono-designer"
if str(MONO_DESIGNER_DIR) not in sys.path:
sys.path.insert(0, str(MONO_DESIGNER_DIR))
from mono_designer.core.linter import Linter, WorkspaceContext # noqa: E402
from mono_designer.core.normalization import normalize_artifact # noqa: E402
from mono_designer.core.revision import apply_revision # noqa: E402
from mono_designer.models.navigation import NavigationSpec # noqa: E402
from mono_designer.models.screen import ScreenSpec # noqa: E402
from mono_designer.models.workflow import WorkflowSpec # noqa: E402
from mono_designer.projectors.ascii_nav import project_nav_ascii # noqa: E402
from mono_designer.projectors.ascii_screen import project_screen_ascii # noqa: E402
from mono_designer.projectors.ascii_workflow import project_workflow_ascii # noqa: E402
from mono_designer.utils.yaml_io import ( # noqa: E402
load_artifact_data,
load_yaml,
save_yaml,
)
STANDARD_DIR = PROJECT_ROOT / "website" / "content" / "standard"
REFERENCE_DIR = PROJECT_ROOT / "website" / "content" / "reference"
TEXTUAL_DIR = PROJECT_ROOT / "website" / "content" / "textual"
DESIGNER_SCHEMA_PATH = PROJECT_ROOT / "dev" / "designer" / "mono-dsl.schema.json"
CORE_DOCS = {
"design-standard": PROJECT_ROOT / "monospace-tui-design-standard.md",
"rendering-reference": PROJECT_ROOT / "monospace-tui-rendering-reference.md",
"textual-appendix": PROJECT_ROOT / "monospace-tui-textual-appendix.md",
"research": PROJECT_ROOT / "monospace-design-tui-research.md",
"template": PROJECT_ROOT / "TUI-DESIGN.template.md",
}
# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------
def _strip_frontmatter(text: str) -> str:
"""Remove Hugo YAML frontmatter (--- ... ---) from markdown."""
return re.sub(r"\A---\n.*?---\n+", "", text, count=1, flags=re.DOTALL)
def _read_section_file(directory: Path, name: str) -> str | None:
"""Read a markdown file from a content directory, stripping frontmatter."""
candidates = [
directory / f"{name}.md",
directory / f"_{name}.md",
directory / "_index.md" if name == "index" else None,
]
for path in candidates:
if path and path.is_file():
return _strip_frontmatter(path.read_text())
return None
def _list_sections(directory: Path) -> list[str]:
"""List available section names in a content directory."""
return sorted(p.stem for p in directory.glob("*.md") if p.stem != "_index")
def _project_artifact(artifact: NavigationSpec | ScreenSpec | WorkflowSpec) -> str:
"""Project a validated Mono Designer artifact into ASCII."""
if isinstance(artifact, ScreenSpec):
return project_screen_ascii(artifact)
if isinstance(artifact, NavigationSpec):
return project_nav_ascii(artifact)
if isinstance(artifact, WorkflowSpec):
return project_workflow_ascii(artifact)
raise ValueError(f"Projection for {artifact.artifact_type} is not implemented.")
def _deep_merge(base: dict[str, Any], updates: dict[str, Any]) -> dict[str, Any]:
"""Recursively merge update dictionaries without mutating the source."""
merged = dict(base)
for key, value in updates.items():
existing = merged.get(key)
if isinstance(existing, dict) and isinstance(value, dict):
merged[key] = _deep_merge(existing, value)
else:
merged[key] = value
return merged
# ---------------------------------------------------------------------------
# MCP Server
# ---------------------------------------------------------------------------
mcp = FastMCP(
"mono-tui",
instructions="""\
Monospace Design TUI — a complete design system for terminal user interfaces.
Use this server when building, designing, or auditing a TUI application.
## Two ways to use this server
### Option A: Design consultation (recommended for new projects)
Call `design_consultation(message)` with a description of your project. The
server will propose workflow patterns, screen layouts, component choices,
keyboard bindings, and a color palette — all grounded in the Monospace TUI
standard. Pass the returned `session_id` in follow-up calls to continue the
conversation:
1. `design_consultation("I'm building a log aggregator with real-time tail
and severity filtering")` → get initial proposal + session_id
2. `design_consultation("What about adding saved searches?",
session_id="abc123")` → refined proposal with context
### Option B: Direct tool queries (for specific lookups)
Query individual tools when you need specific design data. The recommended
workflow:
1. **Identify the task flow** — Call `list_workflow_archetypes()` to find the
right workflow pattern (wizard, crud, monitor-respond, search-act,
drill-down, pipeline, review-approve), then `get_workflow_archetype(name)`
for the full screen sequence, navigation model, and state management rules.
2. **Pick a screen archetype** — Call `list_archetypes()` for the five UI
screen patterns (dashboard, admin, file-manager, editor, fuzzy-finder),
then `get_archetype(name)` for layout, components, and keyboard bindings.
3. **Get layout rules** — Call `get_standard_section("layout")` for the
three-region layout model, responsive breakpoints, and footer requirements.
Call `get_design_tokens()` for spacing scale, elevation levels, timing
tiers, and minimum dimensions.
4. **Choose components** — Call `get_widget_recommendation(data_type)` to get
the correct widget for your data (boolean → toggle, exclusive 2-5 → radio,
exclusive 6-25 → list box, etc.). Then `get_component_spec(name)` for
exact measurements, formats, and interaction rules.
5. **Apply a color palette** — Call `list_palettes()` to browse the eight
named palettes, then `get_palette(name)` for the full semantic-role color
mapping with 256-color indices and hex values.
6. **Wire keyboard bindings** — Call `get_keyboard_bindings()` for all three
tiers, or filter by tier. Tier 1 (global) keys are mandatory. Tier 2
(common actions) should be bound when the action exists. Tier 3 (screen
mnemonics) are application-defined.
7. **Render correctly** — Call `get_box_drawing(style)` for border characters.
Call `get_state_model()` for the 7-state rendering model with SGR codes.
Call `get_reference_section(name)` for shadows, SGR codes, sparklines,
escape sequences, or color detection.
8. **Implement in Textual** — Call `get_textual_guide()` for the full mapping
to Python Textual widgets, TCSS patterns, and async/worker rules.
9. **Document overrides** — Call `get_project_template()` to get the template
for recording project-specific WAIVE, OVERRIDE, or TIGHTEN decisions.
## Quick reference
- Workflow archetypes: wizard, crud, monitor-respond, search-act, drill-down,
pipeline, review-approve
- UI archetypes: dashboard, admin, file-manager, editor, fuzzy-finder
- Standard sections: layout, keyboard, navigation, components, color, borders,
typography, state, accessibility, motion, archetypes
- Reference sections: box-drawing, sgr-codes, color-palette, measurements,
shadows, escape-sequences, color-detection, mixed-borders, sparklines
- Palettes: default, monochrome, os2, turbo, amber, green, airlock
- Components: push-button, entry-field, toggle, radio-group, list-box,
data-table, metric-card, dialog, menu, spin-button, footer
- Widget data types: boolean, exclusive, free_text, numeric, action, spin_value
- Keyboard tiers: tier1_global, tier1_scrolling, tier1_text_entry,
tier2_common, tier3_mnemonics
- Box-drawing styles: single, heavy, double, rounded, dashed, blocks,
indicators
""",
)
# ---- Designer workflow ----------------------------------------------------
@mcp.tool()
def design_generate(file_path: str, yaml_content: str) -> dict:
"""Create or overwrite a Mono Designer YAML artifact.
The YAML is parsed, normalized through the 0.3.0 model layer, written to
disk, then projected to ASCII for human review.
"""
path = Path(file_path)
data = load_artifact_data(yaml_content)
if not isinstance(data, dict):
raise ValueError("yaml_content must parse to a YAML mapping/object.")
artifact = normalize_artifact(data)
path.parent.mkdir(parents=True, exist_ok=True)
save_yaml(data, path)
return {
"file_path": str(path),
"artifact_type": artifact.artifact_type,
"id": artifact.id,
"ascii": _project_artifact(artifact),
}
@mcp.tool()
def design_revise(file_path: str, json_patch: str) -> dict:
"""Safely revise an existing Mono Designer YAML artifact.
Accepts either an RFC 6902 JSON Patch array or a JSON object that is
recursively deep-merged into the current YAML artifact.
"""
path = Path(file_path)
if not path.exists():
raise FileNotFoundError(f"Design artifact not found: {path}")
patch_data = json.loads(json_patch)
if isinstance(patch_data, list):
artifact = apply_revision(path, patch_data)
data = load_yaml(path)
elif isinstance(patch_data, dict):
data = load_yaml(path)
if not isinstance(data, dict):
raise ValueError(f"Design artifact must be a YAML mapping/object: {path}")
data = _deep_merge(data, patch_data)
artifact = normalize_artifact(data)
save_yaml(data, path)
else:
raise ValueError("json_patch must be a JSON object or RFC 6902 array.")
return {
"file_path": str(path),
"artifact_type": artifact.artifact_type,
"id": artifact.id,
"ascii": _project_artifact(artifact),
}
@mcp.tool()
def design_lint(directory: str) -> dict:
"""Run Mono Designer schema, relational, and heuristic lint checks."""
path = Path(directory)
if not path.exists() or not path.is_dir():
raise FileNotFoundError(f"Design workspace directory not found: {path}")
ctx = WorkspaceContext(path)
linter = Linter(schema_path=DESIGNER_SCHEMA_PATH)
results = linter.lint_workspace(ctx)
issues = [
{
"file_path": str(result.file_path),
"code": result.code,
"level": result.level,
"message": result.message,
}
for result in results
]
error_count = sum(1 for issue in issues if issue["level"] == "error")
warning_count = sum(1 for issue in issues if issue["level"] == "warning")
return {
"ok": error_count == 0 and warning_count == 0,
"error_count": error_count,
"warning_count": warning_count,
"issues": issues,
}
# ---- Standard sections ----------------------------------------------------
@mcp.tool()
def get_standard_section(
section: str,
) -> str:
"""Get a section of the Monospace TUI Design Standard.
Available sections: layout, keyboard, navigation, components, color,
borders, typography, state, accessibility, motion, archetypes.
"""
content = _read_section_file(STANDARD_DIR, section)
if content is None:
available = _list_sections(STANDARD_DIR)
return f"Section '{section}' not found. Available: {', '.join(available)}"
return content
# ---- Reference sections ---------------------------------------------------
@mcp.tool()
def get_reference_section(
section: str,
) -> str:
"""Get a section of the Monospace TUI Rendering Reference.
Available sections: box-drawing, sgr-codes, color-palette, measurements,
shadows, escape-sequences, color-detection, mixed-borders, sparklines.
"""
content = _read_section_file(REFERENCE_DIR, section)
if content is None:
available = _list_sections(REFERENCE_DIR)
return f"Section '{section}' not found. Available: {', '.join(available)}"
return content
# ---- Textual appendix -----------------------------------------------------
@mcp.tool()
def get_textual_guide() -> str:
"""Get the Textual framework mapping guide.
Returns widget mappings, TCSS patterns, async rules, and binding helpers
for implementing Monospace TUI with Python Textual.
"""
path = CORE_DOCS["textual-appendix"]
if path.is_file():
return path.read_text()
# Fall back to website version
content = _read_section_file(TEXTUAL_DIR, "_index")
if content:
return content
return "Textual appendix not found."
# ---- Design tokens --------------------------------------------------------
@mcp.tool()
def get_design_tokens() -> dict:
"""Get core design tokens: spacing scale, elevation levels, timing tiers,
responsive breakpoints, and typography treatments.
Returns structured data that can be directly used in implementations.
"""
return {
"spacing_scale": {
"values": [0, 1, 2, 3, 4, 6, 8],
"unit": "character cells",
"rule": "Intermediate values (5, 7) MUST NOT be used.",
},
"elevation_levels": [
{
"level": 0,
"use": "Inline content",
"border": "none",
"shadow": False,
"scrim": False,
},
{
"level": 1,
"use": "Panels, content regions",
"border": "single-line",
"border_chars": "─│┌┐└┘├┤┬┴┼",
"shadow": False,
"scrim": False,
},
{
"level": 2,
"use": "Menus, dropdowns",
"border": "single-line",
"border_chars": "─│┌┐└┘├┤┬┴┼",
"shadow": {"offset_cols": 2, "offset_rows": 1, "sgr": "dim (SGR 2)"},
"scrim": False,
},
{
"level": 3,
"use": "Dialogs, secondary windows",
"border": "double-line",
"border_chars": "═║╔╗╚╝╠╣╦╩╬",
"shadow": {"offset_cols": 2, "offset_rows": 1, "sgr": "dim (SGR 2)"},
"scrim": False,
},
{
"level": 4,
"use": "Modal overlays",
"border": "double-line",
"border_chars": "═║╔╗╚╝╠╣╦╩╬",
"shadow": {"offset_cols": 2, "offset_rows": 1, "sgr": "dim (SGR 2)"},
"scrim": True,
},
],
"timing_tiers": {
"instant": {"ms": 0, "use": "State toggles, key echo"},
"fast": {"ms": "50-100", "use": "Button press feedback, cursor movement"},
"standard": {"ms": "150-300", "use": "Panel transitions, menu open/close"},
"slow": {
"ms": "300-500",
"use": "Screen transitions, progressive disclosure",
},
"max": "500ms for any UI transition",
},
"breakpoints": {
"compact": {
"cols": "40-79",
"layout": "Region A collapses; C hidden/stacked; footer 1 row",
},
"standard": {
"cols": "80-119",
"layout": "Region A visible (8-12 cols); C optional; full footer",
},
"expanded": {
"cols": "120-159",
"layout": "Full three-region; A at 12-16 cols",
},
"wide": {
"cols": "160+",
"layout": "A at full width (up to 20); C expanded",
},
},
"min_dimensions": {
"minimum_viable": {"cols": 80, "rows": 24, "requirement": "MUST support"},
"standard": {"cols": 120, "rows": 40, "requirement": "SHOULD target"},
},
"typography": {
"display": {"sgr": "1 (bold)", "transform": "uppercase"},
"title": {"sgr": "1 (bold)", "transform": "none"},
"body": {"sgr": "none", "transform": "none"},
"label": {"sgr": "2 (dim)", "transform": "none"},
},
}
# ---- Color palettes -------------------------------------------------------
PALETTES = {
"default": {
"name": "Default (Textual Dark)",
"description": "Standard dark theme based on Textual defaults",
"theme": "dark",
"roles": {
"primary": {
"fg": {"index": 75, "hex": "#5fafff"},
"bg": {"index": 17, "hex": "#00005f"},
},
"secondary": {
"fg": {"index": 109, "hex": "#87afaf"},
"bg": {"index": 236, "hex": "#303030"},
},
"tertiary": {
"fg": {"index": 79, "hex": "#5fd7af"},
"bg": {"index": 236, "hex": "#303030"},
},
"error": {
"fg": {"index": 196, "hex": "#ff0000"},
"bg": {"index": 52, "hex": "#5f0000"},
},
"neutral": {
"fg": {"index": 252, "hex": "#d0d0d0"},
"fg_bright": {"index": 231, "hex": "#ffffff"},
"bg": {"index": 235, "hex": "#262626"},
},
},
"status": {
"healthy": {"index": 40, "hex": "#00d700"},
"error": {"index": 196, "hex": "#ff0000"},
"warning": {"index": 220, "hex": "#ffd700"},
"inactive": {"index": 240, "hex": "#585858"},
},
},
"monochrome": {
"name": "Monochrome (CUA)",
"description": "Single-color theme using SGR attributes only",
"theme": "dark",
"roles": {
"primary": {"sgr": "1 (bold)", "note": "Bold white on black"},
"secondary": {"sgr": "none", "note": "Normal white on black"},
"tertiary": {"sgr": "4 (underline)", "note": "Underlined white on black"},
"error": {
"sgr": "1;7 (bold+reverse)",
"note": "Bold reverse white on black",
},
"neutral": {"sgr": "2 (dim)", "note": "Dim white on black"},
},
"status": {
"healthy": {"sgr": "none"},
"warning": {"sgr": "1 (bold)"},
"error": {"sgr": "1;7 (bold+reverse)"},
"inactive": {"sgr": "2 (dim)"},
},
},
"os2": {
"name": "OS/2 (Presentation Manager)",
"description": "IBM OS/2 Warp yellow-on-blue theme",
"theme": "dark",
"roles": {
"primary": {
"fg": {"index": 14, "hex": "#ffff00"},
"bg": {"index": 1, "hex": "#0000aa"},
},
"secondary": {
"fg": {"index": 7, "hex": "#c0c0c0"},
"bg": {"index": 1, "hex": "#0000aa"},
},
"tertiary": {
"fg": {"index": 0, "hex": "#000000"},
"bg": {"index": 7, "hex": "#c0c0c0"},
},
"error": {
"fg": {"index": 12, "hex": "#ff5555"},
"bg": {"index": 1, "hex": "#0000aa"},
},
"neutral": {
"fg": {"index": 0, "hex": "#000000"},
"bg": {"index": 7, "hex": "#aaaaaa"},
},
},
},
"turbo": {
"name": "Turbo Pascal (Borland IDE)",
"description": "Classic Borland IDE white-on-blue theme",
"theme": "dark",
"roles": {
"primary": {
"fg": {"index": 15, "hex": "#ffffff"},
"bg": {"index": 1, "hex": "#0000aa"},
},
"secondary": {
"fg": {"index": 7, "hex": "#c0c0c0"},
"bg": {"index": 1, "hex": "#0000aa"},
},
"tertiary": {
"fg": {"index": 0, "hex": "#000000"},
"bg": {"index": 2, "hex": "#00aa00"},
},
"error": {
"fg": {"index": 12, "hex": "#ff5555"},
"bg": {"index": 1, "hex": "#0000aa"},
},
"neutral": {
"fg": {"index": 0, "hex": "#000000"},
"bg": {"index": 7, "hex": "#aaaaaa"},
},
},
"special": {
"desktop_pattern": "░ (U+2591) in light gray on blue",
},
},
"amber": {
"name": "Amber Phosphor (DEC VT220)",
"description": "Single-hue amber CRT theme",
"theme": "dark",
"roles": {
"primary": {
"fg": {"index": 214, "hex": "#ffaf00"},
"bg": {"index": 0, "hex": "#000000"},
},
"secondary": {
"fg": {"index": 172, "hex": "#d78700"},
"bg": {"index": 0, "hex": "#000000"},
},
"tertiary": {
"fg": {"index": 214, "hex": "#ffaf00"},
"bg": {"index": 0, "hex": "#000000"},
"sgr": "4 (underline)",
},
"error": {
"fg": {"index": 214, "hex": "#ffaf00"},
"bg": {"index": 0, "hex": "#000000"},
"sgr": "1;7 (bold+reverse)",
},
"neutral": {
"fg": {"index": 136, "hex": "#af8700"},
"bg": {"index": 0, "hex": "#000000"},
},
},
},
"green": {
"name": "Green Phosphor (DEC VT100)",
"description": "Single-hue green CRT theme",
"theme": "dark",
"roles": {
"primary": {
"fg": {"index": 82, "hex": "#5fff00"},
"bg": {"index": 0, "hex": "#000000"},
},
"secondary": {
"fg": {"index": 34, "hex": "#00af00"},
"bg": {"index": 0, "hex": "#000000"},
},
"tertiary": {
"fg": {"index": 82, "hex": "#5fff00"},
"bg": {"index": 0, "hex": "#000000"},
"sgr": "4 (underline)",
},
"error": {
"fg": {"index": 82, "hex": "#5fff00"},
"bg": {"index": 0, "hex": "#000000"},
"sgr": "1;7 (bold+reverse)",
},
"neutral": {
"fg": {"index": 28, "hex": "#008700"},
"bg": {"index": 0, "hex": "#000000"},
},
},
},
"airlock": {
"name": "Airlock (AI-Agent Security)",
"description": "Muted dark theme for security/agent proxy interfaces",
"theme": "dark",
"roles": {
"primary": {
"fg": {"index": 75, "hex": "#5fafff"},
"bg": {"index": 236, "hex": "#303030"},
},
"secondary": {
"fg": {"index": 109, "hex": "#87afaf"},
"bg": {"index": 236, "hex": "#303030"},
},
"tertiary": {
"fg": {"index": 214, "hex": "#ffaf00"},
"bg": {"index": 236, "hex": "#303030"},
},
"error": {
"fg": {"index": 167, "hex": "#d75f5f"},
"bg": {"index": 52, "hex": "#5f0000"},
},
"neutral": {
"fg": {"index": 252, "hex": "#d0d0d0"},
"bg": {"index": 235, "hex": "#262626"},
},
},
"status": {
"healthy": {"index": 117, "hex": "#87d7ff"},
"error": {"index": 167, "hex": "#d75f5f"},
"warning": {"index": 214, "hex": "#ffaf00"},
"inactive": {"index": 245, "hex": "#8a8a8a"},
},
},
}
@mcp.tool()
def list_palettes() -> list[dict]:
"""List all available Monospace TUI color palettes.
Returns name, description, and theme type for each palette.
"""
return [
{
"id": pid,
"name": p["name"],
"description": p["description"],
"theme": p.get("theme", "dark"),
}
for pid, p in PALETTES.items()
]
@mcp.tool()
def get_palette(name: str) -> dict | str:
"""Get a specific color palette with all semantic role mappings.
Args:
name: Palette identifier. One of: default, monochrome, os2, turbo,
amber, green, airlock.
Returns full palette with foreground/background colors per semantic role,
status colors, and any special mappings.
"""
palette = PALETTES.get(name)
if palette is None:
return f"Palette '{name}' not found. Available: {', '.join(PALETTES.keys())}"
return palette
# ---- Component specs -------------------------------------------------------
COMPONENTS = {
"push-button": {
"name": "Push Button",
"height": 1,
"width": "label + 4",
"padding": "1 cell each side",
"standard_format": "< label >",
"default_format": "» label «",
"activation": "Enter or Space",
"rule": "Exactly one default button per dialog (§4.3)",
},
"entry-field": {
"name": "Entry Field",
"height": 1,
"width": "10-60 cols",
"padding": "1 space between label and field",
"format": "[input____] (fill with underscore)",
"navigation": "Arrow keys within, Tab to next field",
},
"toggle": {
"name": "Toggle / Checkbox",
"height": "1 per item",
"indicator_width": 3,
"gap": "1 space",
"format_checked": "[X]",
"format_unchecked": "[ ]",
"activation": "Space",
"use": "Non-mutually-exclusive boolean options",
},
"radio-group": {
"name": "Radio Group",
"height": "1 per option",
"indicator_width": 3,
"gap": "1 space",
"format_selected": "(*)",
"format_unselected": "( )",
"navigation": "Arrow keys within group",
"use": "Mutually exclusive, 2-5 options",
},
"list-box": {
"name": "List Box",
"height": "5-17 rows",
"width": "20+ cols",
"padding": "1 cell each side",
"border": "Level 1 (single-line)",
"focus_indicator": "▸",
"scroll_indicators": "↑ ↓",
"use": "Selection from 6-25 items",
},
"data-table": {
"name": "Data Table",
"height": "1 header + 1 separator + N data rows",
"cell_padding": "1 cell each side",
"sort_ascending": "▴",
"sort_descending": "▾",
"separator": "─ (full width)",
},
"metric-card": {
"name": "Metric Card",
"height": "1-3 rows",
"layout": "icon (1-2) + gap (1) + label + gap (1) + value",
},
"dialog": {
"name": "Dialog",
"height": "7-40 rows",
"width": "30-72 cols",
"padding": "2 horizontal, 1 vertical",
"border": "Level 3 (double-line ═║╔╗╚╝)",
"shadow": "2 cols right, 1 row down",
"title": "Centered in top border",
},
"menu": {
"name": "Menu",
"height": "1 per item + separator rows",
"max_width": 40,
"padding": "1 cell each side",
"border": "Level 2 (single-line + shadow)",
"separator": "Full-width horizontal line",
"shortcut_alignment": "Right-aligned",
"max_items": 10,
},
"spin-button": {
"name": "Spin Button",
"height": 1,
"width": "value + 4",
"padding": "1 around value",
"format": "< value >",
"navigation": "Arrow Up/Down to cycle",
"max_choices": 20,
},
"footer": {
"name": "Footer Key Strip",
"height": "1-2 rows",
"format": "F1 Help F5 Refresh / Filter q Quit",
"separator": "2+ spaces between key-action pairs",
"rule": "MUST always be visible, MUST update with context",
},
}
@mcp.tool()
def list_components() -> list[dict]:
"""List all component specifications available in the design system."""
return [{"id": cid, "name": c["name"]} for cid, c in COMPONENTS.items()]
@mcp.tool()
def get_component_spec(component: str) -> dict | str:
"""Get the measurement and behavior spec for a specific component.
Args:
component: Component identifier. One of: push-button, entry-field,
toggle, radio-group, list-box, data-table, metric-card,
dialog, menu, spin-button, footer.
"""
spec = COMPONENTS.get(component)
if spec is None:
return f"Component '{component}' not found. Available: {', '.join(COMPONENTS.keys())}"
return spec
# ---- Keyboard bindings ----------------------------------------------------
KEYBOARD_BINDINGS = {
"tier1_global": {
"description": "Mandatory global keys — MUST be bound in every application",
"bindings": [
{
"action": "Help",
"cua_key": "F1",
"common_key": "?",
"context": "Context-sensitive",
},
{
"action": "Back/Cancel",
"cua_key": "F3",
"common_key": "Esc",
"context": "Return to previous screen",
},
{
"action": "Refresh",
"cua_key": "F5",
"common_key": "r",
"context": "When no text input focused",
},
{
"action": "Scroll backward",
"cua_key": "F7",
"common_key": "PageUp",
"context": "Scrollable areas",
},
{
"action": "Scroll forward",
"cua_key": "F8",
"common_key": "PageDown",
"context": "Scrollable areas",
},
{
"action": "Activate menu",
"cua_key": "F10",
"common_key": "Alt",
"context": "Toggle action bar focus",
},
{
"action": "Next field",
"cua_key": None,
"common_key": "Tab",
"context": "LTR top-to-bottom order",
},
{
"action": "Previous field",
"cua_key": None,
"common_key": "Shift+Tab",
"context": "Reverse tab order",
},
{
"action": "Confirm/activate",
"cua_key": None,
"common_key": "Enter",
"context": "Submit form, press button",
},
{
"action": "Toggle/select",
"cua_key": None,
"common_key": "Space",
"context": "Toggles, checkboxes, radio",
},
{
"action": "Navigate within control",
"cua_key": None,
"common_key": "Arrow keys",
"context": "Within single control",
},
{
"action": "Quit application",
"cua_key": None,
"common_key": "q",
"context": "When no text input focused",
},
{
"action": "Search/filter",
"cua_key": None,
"common_key": "/",
"context": "Open filter input",
},
],
},
"tier1_scrolling": {
"description": "Scrolling keys — active in scrollable content when no text input focused",
"bindings": [
{"action": "Top of list", "key": "gg or Home"},
{"action": "Bottom of list", "key": "G (Shift+G) or End"},
{"action": "Half-page down", "key": "Ctrl+D"},
{"action": "Half-page up", "key": "Ctrl+U"},
{"action": "Next search result", "key": "n (after /)"},
],
},
"tier1_text_entry": {
"description": "Text entry keys — active when text input field is focused",
"bindings": [
{"action": "Cut", "key": "Ctrl+X"},
{"action": "Copy", "key": "Ctrl+C or Ctrl+Ins"},
{"action": "Paste", "key": "Ctrl+V"},
{"action": "Undo", "key": "Ctrl+Z"},
],
},
"tier2_common": {
"description": "Common action keys — SHOULD bind when action exists",
"bindings": [
{"action": "Delete/remove", "key": "d", "case_insensitive": True},
{"action": "Edit/modify", "key": "e", "case_insensitive": True},
{"action": "Add/create", "key": "a", "case_insensitive": True},
{"action": "Yank/copy value", "key": "y", "case_insensitive": True},
{"action": "Sort", "key": "s", "case_insensitive": True},
{"action": "Command mode", "key": ":"},
{"action": "Suspend to background", "key": "Ctrl+Z"},
],
},
"tier3_mnemonics": {
"description": "Screen mnemonics — application-defined, must not conflict with Tier 1/2",
"common_patterns": [
"1-9 for numbered screens",
"d Dashboard, w Wizard, c Config, l Logs, m Models",
],
"rules": [
"Must not conflict with Tier 1 or Tier 2 bindings",
"Case-insensitive (bind both cases, show lowercase in footer)",
"Shown in footer key strip",
],
},
"key_scope_rule": (
"Single-letter keys (q, r, /, d, e, a, s, g, n, y, Tier 3) are "
"suppressed when text input widget is focused. Only Ctrl+, Alt+, "
"F-keys, and Esc remain active during text entry."
),
}
@mcp.tool()
def get_keyboard_bindings(
tier: Optional[str] = None,
) -> dict | str:
"""Get keyboard binding specifications.
Args:
tier: Optional filter. One of: tier1_global, tier1_scrolling,
tier1_text_entry, tier2_common, tier3_mnemonics.
If omitted, returns all tiers.
"""
if tier is None:
return KEYBOARD_BINDINGS
bindings = KEYBOARD_BINDINGS.get(tier)
if bindings is None:
available = [k for k in KEYBOARD_BINDINGS.keys() if k != "key_scope_rule"]
return f"Tier '{tier}' not found. Available: {', '.join(available)}"
return bindings
# ---- Archetypes -----------------------------------------------------------
ARCHETYPES = {
"dashboard": {
"name": "Dashboard",
"section": "§11.1",
"description": "Real-time monitoring (htop, btop, system dashboards)",
"layout": "Metric header + data table + footer",
"components": ["Metric cards", "Data table", "Sparklines", "Status indicators"],
"keyboard": {
"?": "Help",
"r": "Refresh",
"/": "Filter",
"s": "Sort",
"q": "Quit",
"1-9": "Column sort",
},
},
"admin": {
"name": "Admin / Config",
"section": "§11.2",
"description": "Settings and configuration panels",
"layout": "Category sidebar + form body + footer",
"components": ["Entry fields", "Toggles", "Radio groups", "Buttons"],
"keyboard": {
"Tab/Shift+Tab": "Field navigation",
"Esc": "Cancel",
"Ctrl+S": "Save",
"1-9": "Jump to sidebar item",
"[ ]": "Tab cycling",
},
},