forked from FastLED/FastLED
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathmcp_server.py
More file actions
2551 lines (2156 loc) · 105 KB
/
mcp_server.py
File metadata and controls
2551 lines (2156 loc) · 105 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
#!/usr/bin/env -S uv run --script
# pyright: reportUnknownMemberType=false
"""
FastLED MCP Server - Provides tools for working with the FastLED project
🚨 CRITICAL FOR ALL AGENTS (FOREGROUND & BACKGROUND): Before concluding that your work is done,
the AI shall read the cursor rules again to find out what to do before task is considered complete.
This ensures you have the latest coding standards, testing requirements, and completion validation rules.
This is MANDATORY for both foreground and background agents.
🚨 CRITICAL FOR BACKGROUND AGENTS: When modifying ANY Python files (*.py),
you MUST run `bash lint` immediately after making changes and before indicating completion.
This is a NON-NEGOTIABLE REQUIREMENT to ensure code quality and prevent build failures.
🚨 MANDATORY COMMAND EXECUTION RULES 🚨
ALL AGENTS MUST FOLLOW THESE COMMAND EXECUTION PATTERNS:
### Python Code Execution:
- [ERROR] NEVER run Python code directly
- [OK] ALWAYS create/modify tmp.py with your code
- [OK] ALWAYS run: `uv run tmp.py`
### Shell Command Execution:
- [ERROR] NEVER run shell commands directly
- [OK] ALWAYS create/modify tmp.sh with your commands
- [OK] ALWAYS run: `bash tmp.sh`
### DELETE Operations - DANGER ZONE:
- 🚨 STOP and ask for permission before ANY delete operations
- [OK] EXCEPTION: Single files that you just created are OK to delete
- [ERROR] NEVER delete multiple files without explicit permission
- [ERROR] NEVER delete directories without explicit permission
- [ERROR] NEVER delete system files or project files without permission
### Examples:
**Python Code:**
```python
# tmp.py
import subprocess
result = subprocess.run(['git', 'status'], capture_output=True, text=True)
print(result.stdout)
```
Then run: `uv run tmp.py`
**Shell Commands:**
```bash
# tmp.sh
#!/bin/bash
git status
ls -la
```
Then run: `bash tmp.sh`
**Why These Rules:**
- Ensures all operations are reviewable and traceable
- Prevents accidental destructive operations
- Allows for better debugging and error handling
- Maintains consistency across all agent operations
To use this server, make sure you have the MCP library installed:
pip install mcp
Or use with uv:
uv add mcp
uv run mcp_server.py
"""
import asyncio
import sys
import re
import subprocess
import shutil
import tempfile
import time
from pathlib import Path
from typing import Any, Dict, List, Union
try:
from mcp.server import Server # type: ignore
from mcp.server.stdio import stdio_server # type: ignore
from mcp.types import ( # type: ignore
CallToolResult,
TextContent,
Tool,
)
MCP_AVAILABLE = True
except ImportError:
print("Error: MCP library not found.")
print("Please install it with: pip install mcp")
print("Or with uv: uv add mcp")
sys.exit(1)
from ci.util.build_info_analyzer import BuildInfoAnalyzer # type: ignore
# Initialize the MCP server
server = Server("fastled-mcp-server")
@server.list_tools()
async def list_tools() -> List[Tool]:
"""List available tools for the FastLED project."""
return [
Tool(
name="run_tests",
description="Run FastLED tests with various options",
inputSchema={
"type": "object",
"properties": {
"test_type": {
"type": "string",
"enum": ["all", "cpp", "specific"],
"description": "Type of tests to run",
"default": "all"
},
"specific_test": {
"type": "string",
"description": "Name of specific C++ test to run (without 'test_' prefix, e.g. 'algorithm' for test_algorithm.cpp)"
},
"test_case": {
"type": "string",
"description": "Specific TEST_CASE name to run within a test file (requires doctest filtering)"
},
"use_clang": {
"type": "boolean",
"description": "Use Clang compiler instead of default",
"default": False
},
"clean": {
"type": "boolean",
"description": "Clean build before compiling",
"default": False
},
"verbose": {
"type": "boolean",
"description": "Enable verbose output showing all test details",
"default": False
}
},
"required": ["test_type"]
}
),
Tool(
name="list_test_cases",
description="List TEST_CASEs available in FastLED test files",
inputSchema={
"type": "object",
"properties": {
"test_file": {
"type": "string",
"description": "Specific test file to analyze (without 'test_' prefix and '.cpp' extension, e.g. 'algorithm')"
},
"search_pattern": {
"type": "string",
"description": "Search pattern to filter TEST_CASE names"
}
}
}
),
Tool(
name="compile_examples",
description="Compile FastLED examples for different platforms using 'bash compile <platform> --examples <example>'",
inputSchema={
"type": "object",
"properties": {
"platform": {
"type": "string",
"description": "Target platform (e.g., 'uno', 'esp32', 'teensy')",
"default": "uno"
},
"examples": {
"type": "array",
"items": {"type": "string"},
"description": "List of example names to compile",
"default": ["Blink"]
},
"interactive": {
"type": "boolean",
"description": "Run in interactive mode",
"default": False
}
}
}
),
Tool(
name="code_fingerprint",
description="Calculate a fingerprint of the codebase to detect changes",
inputSchema={
"type": "object",
"properties": {
"directory": {
"type": "string",
"description": "Directory to fingerprint (relative to project root)",
"default": "src"
},
"patterns": {
"type": "string",
"description": "Glob patterns for files to include",
"default": "**/*.h,**/*.cpp,**/*.hpp"
}
}
}
),
Tool(
name="lint_code",
description="Run comprehensive code formatting and linting. For FOREGROUND agents, this runs `bash lint` for complete coverage. For BACKGROUND agents, can run specific tools for fine-grained control.",
inputSchema={
"type": "object",
"properties": {
"tool": {
"type": "string",
"enum": ["bash_lint", "ruff", "javascript", "all"],
"description": "Linting approach: 'bash_lint' (recommended for foreground), 'ruff' (Python only), 'javascript' (JS only), 'all' (comprehensive via bash lint)",
"default": "bash_lint"
},
"agent_type": {
"type": "string",
"enum": ["foreground", "background"],
"description": "Agent type - foreground agents should use bash_lint, background agents can use specific tools",
"default": "foreground"
},
"fix": {
"type": "boolean",
"description": "Automatically fix issues where possible (only applies to specific tools, not bash_lint)",
"default": False
}
}
}
),
Tool(
name="list_examples",
description="List available FastLED examples",
inputSchema={
"type": "object",
"properties": {
"category": {
"type": "string",
"description": "Filter by category (optional)"
}
}
}
),
Tool(
name="project_info",
description="Get information about the FastLED project structure and status",
inputSchema={
"type": "object",
"properties": {
"include_git_status": {
"type": "boolean",
"description": "Include git status information",
"default": True
}
}
}
),
Tool(
name="run_specific_command",
description="Run a specific command in the project context",
inputSchema={
"type": "object",
"properties": {
"command": {
"type": "string",
"description": "Command to run"
},
"working_directory": {
"type": "string",
"description": "Working directory (relative to project root)",
"default": "."
}
},
"required": ["command"]
}
),
Tool(
name="test_instructions",
description="Get detailed instructions on how to run TEST_CASEs in FastLED",
inputSchema={
"type": "object",
"properties": {}
}
),
Tool(
name="setup_stack_traces",
description="Install and configure stack trace debugging libraries (libunwind/execinfo)",
inputSchema={
"type": "object",
"properties": {
"method": {
"type": "string",
"enum": ["libunwind", "execinfo", "auto"],
"description": "Stack trace method to install and configure",
"default": "auto"
},
"test_installation": {
"type": "boolean",
"description": "Test the installation with crash tests",
"default": True
},
"install_only": {
"type": "boolean",
"description": "Only install packages, don't run tests",
"default": False
}
}
}
),
Tool(
name="coding_standards",
description="Get FastLED coding standards and best practices for C++ development",
inputSchema={
"type": "object",
"properties": {
"topic": {
"type": "string",
"enum": ["all", "exceptions", "std_namespace", "naming", "member_naming", "containers", "debug", "bindings", "arduino_includes", "variable_naming", "python_linting"],
"description": "Specific topic to get standards for, or 'all' for complete guide",
"default": "all"
}
}
}
),
Tool(
name="validate_completion",
description="🚨 MANDATORY FOR ALL BACKGROUND AGENTS: Validate that all tests pass before indicating completion. This tool MUST be run as the final step before any background agent indicates they are done with their task.",
inputSchema={
"type": "object",
"properties": {
"task_description": {
"type": "string",
"description": "Brief description of the task being completed",
"default": "Code changes"
},
"run_full_test_suite": {
"type": "boolean",
"description": "Run the complete test suite including unit tests and compilation checks",
"default": True
}
}
}
),
Tool(
name="esp32_symbol_analysis",
description="Run ESP32 symbol analysis to identify optimization opportunities for binary size reduction. Analyzes ELF files to find large symbols and provides recommendations for eliminating unused code.",
inputSchema={
"type": "object",
"properties": {
"board": {
"type": "string",
"description": "ESP32 board name (e.g., 'esp32dev', 'esp32s3', 'esp32c3'). If not specified, auto-detects from .build directory",
"default": "auto"
},
"example": {
"type": "string",
"description": "Example name that was compiled (for context in reports)",
"default": "Blink"
},
"output_json": {
"type": "boolean",
"description": "Include detailed JSON output in results",
"default": False
},
}
}
),
Tool(
name="build_info_analysis",
description="Analyze platform build information from build_info.json files. Extract platform-specific preprocessor defines, compiler flags, toolchain paths, and other build configuration data. Works with any platform that has been compiled (uno, esp32dev, teensy31, etc.).",
inputSchema={
"type": "object",
"properties": {
"board": {
"type": "string",
"description": "Platform/board name (e.g., 'uno', 'esp32dev', 'teensy31'). Use 'list' to see available boards",
"default": "list"
},
"show_defines": {
"type": "boolean",
"description": "Show platform preprocessor defines (C/C++ #define values)",
"default": True
},
"show_compiler": {
"type": "boolean",
"description": "Show compiler information (paths, flags, types)",
"default": False
},
"show_toolchain": {
"type": "boolean",
"description": "Show toolchain tool aliases (gcc, g++, ar, etc.)",
"default": False
},
"show_all": {
"type": "boolean",
"description": "Show all available build information",
"default": False
},
"compare_with": {
"type": "string",
"description": "Compare platform defines with another board (e.g., 'esp32dev')"
},
"output_json": {
"type": "boolean",
"description": "Output results in JSON format for programmatic use",
"default": False
}
}
}
),
Tool(
name="symbol_analysis",
description="Run generic symbol analysis for ANY platform (UNO, ESP32, Teensy, STM32, etc.) to identify optimization opportunities. Analyzes ELF files to show all symbols and their sizes without filtering. Works with any platform that has build_info.json.",
inputSchema={
"type": "object",
"properties": {
"board": {
"type": "string",
"description": "Platform/board name (e.g., 'uno', 'esp32dev', 'teensy31', 'digix'). If 'auto', detects all available platforms from .build directory",
"default": "auto"
},
"example": {
"type": "string",
"description": "Example name that was compiled (for context in reports)",
"default": "Blink"
},
"output_json": {
"type": "boolean",
"description": "Save detailed JSON output to .build/{board}_symbol_analysis.json",
"default": False
},
"run_all_platforms": {
"type": "boolean",
"description": "If true, runs analysis on all detected platforms",
"default": False
}
}
}
),
Tool(
name="run_fastled_web_compiler",
description="🌐 FOR FOREGROUND AGENTS ONLY: Run FastLED web compiler with playwright console.log capture. Compiles Arduino sketch to WASM and opens browser with automated testing. BACKGROUND AGENTS MUST NOT USE THIS TOOL.",
inputSchema={
"type": "object",
"properties": {
"example_path": {
"type": "string",
"description": "Path to example directory (e.g., 'examples/Audio', 'examples/Blink')",
"default": "examples/Audio"
},
"capture_duration": {
"type": "integer",
"description": "Duration in seconds to capture console.log output",
"default": 30
},
"headless": {
"type": "boolean",
"description": "Run browser in headless mode",
"default": False
},
"port": {
"type": "integer",
"description": "Port for web server (0 for auto-detection)",
"default": 0
},
"docker_check": {
"type": "boolean",
"description": "Check if Docker is available for faster compilation",
"default": True
},
"save_screenshot": {
"type": "boolean",
"description": "Save screenshot of the running visualization",
"default": True
}
}
}
),
Tool(
name="validate_arduino_includes",
description="🚨 CRITICAL: Validate that no new Arduino.h includes have been added to the codebase. This tool scans for #include \"Arduino.h\" and #include <Arduino.h> statements and reports any that are not pre-approved.",
inputSchema={
"type": "object",
"properties": {
"directory": {
"type": "string",
"description": "Directory to scan for Arduino.h includes (relative to project root)",
"default": "src"
},
"include_examples": {
"type": "boolean",
"description": "Also scan examples directory for Arduino.h includes",
"default": False
},
"check_dev": {
"type": "boolean",
"description": "Also scan dev directory for Arduino.h includes",
"default": False
},
"show_approved": {
"type": "boolean",
"description": "Show approved Arduino.h includes marked with '// ok include'",
"default": True
}
}
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: Dict[str, Any]) -> Any:
"""Handle tool calls."""
project_root = Path(__file__).parent
try:
if name == "run_tests":
return await run_tests(arguments, project_root)
elif name == "list_test_cases":
return await list_test_cases(arguments, project_root)
elif name == "compile_examples":
return await compile_examples(arguments, project_root)
elif name == "code_fingerprint":
return await code_fingerprint(arguments, project_root)
elif name == "lint_code":
return await lint_code(arguments, project_root)
elif name == "list_examples":
return await list_examples(arguments, project_root)
elif name == "project_info":
return await project_info(arguments, project_root)
elif name == "run_specific_command":
return await run_specific_command(arguments, project_root)
elif name == "test_instructions":
return await test_instructions(arguments, project_root)
elif name == "setup_stack_traces":
return await setup_stack_traces(arguments, project_root)
elif name == "coding_standards":
return await coding_standards(arguments, project_root)
elif name == "validate_completion":
return await validate_completion(arguments, project_root)
elif name == "build_info_analysis":
return await build_info_analysis(arguments, project_root)
elif name == "esp32_symbol_analysis":
return await esp32_symbol_analysis(arguments, project_root)
elif name == "symbol_analysis":
return await symbol_analysis(arguments, project_root)
elif name == "run_fastled_web_compiler":
return await run_fastled_web_compiler(arguments, project_root)
elif name == "validate_arduino_includes":
return await validate_arduino_includes(arguments, project_root)
else:
return CallToolResult(
content=[TextContent(type="text", text=f"Unknown tool: {name}")],
isError=True
)
except Exception as e:
return CallToolResult(
content=[TextContent(type="text", text=f"Error executing {name}: {str(e)}")],
isError=True
)
async def run_tests(arguments: Dict[str, Any], project_root: Path) -> CallToolResult:
"""Run FastLED tests."""
test_type = arguments.get("test_type", "all")
specific_test = arguments.get("specific_test")
test_case = arguments.get("test_case")
use_clang = arguments.get("use_clang", False)
clean = arguments.get("clean", False)
verbose = arguments.get("verbose", False)
# Use bash test format as per user directive
if test_case and specific_test:
# For individual TEST_CASE, we still need to use bash test with the test name
# The bash test script handles the details
cmd = ["bash", "test", specific_test]
context = f"Running test: bash test {specific_test}\n"
if test_case:
context += f"Note: To run specific TEST_CASE '{test_case}', the test framework will need to support filtering\n"
elif specific_test and test_type == "specific":
# Use bash test format for specific tests
cmd = ["bash", "test", specific_test]
context = f"Running specific test: bash test {specific_test}\n"
else:
# For all tests or cpp tests, use the original format
cmd = ["uv", "run", "test.py"]
if test_type == "cpp":
cmd.append("--cpp")
if use_clang:
cmd.append("--clang")
if clean:
cmd.append("--clean")
if verbose:
cmd.append("--verbose")
context = f"Command executed: {' '.join(cmd)}\n"
result = await run_command(cmd, project_root)
return CallToolResult(
content=[TextContent(type="text", text=context + result)]
)
async def list_test_cases(arguments: Dict[str, Any], project_root: Path) -> CallToolResult:
"""List TEST_CASEs in FastLED test files."""
test_file = arguments.get("test_file")
search_pattern = arguments.get("search_pattern", "")
tests_dir = project_root / "tests"
if not tests_dir.exists():
return CallToolResult(
content=[TextContent(type="text", text="Tests directory not found")],
isError=True
)
test_cases: Dict[str, List[str]] = {}
if test_file:
# Analyze specific test file
test_path = tests_dir / f"test_{test_file}.cpp"
if not test_path.exists():
return CallToolResult(
content=[TextContent(type="text", text=f"Test file not found: test_{test_file}.cpp")],
isError=True
)
test_cases[test_file] = extract_test_cases(test_path, search_pattern)
else:
# Analyze all test files
for test_path in tests_dir.glob("test_*.cpp"):
test_name = test_path.stem[5:] # Remove "test_" prefix
cases = extract_test_cases(test_path, search_pattern)
if cases: # Only include files with test cases
test_cases[test_name] = cases
# Format output
if not test_cases:
return CallToolResult(
content=[TextContent(type="text", text="No TEST_CASEs found matching criteria")]
)
result_text = "FastLED TEST_CASEs:\n"
result_text += "=" * 50 + "\n\n"
total_cases = 0
for test_name, cases in sorted(test_cases.items()):
result_text += f"📁 {test_name} ({len(cases)} TEST_CASEs):\n"
for i, case in enumerate(cases, 1):
result_text += f" {i:2d}. {case}\n"
result_text += "\n"
total_cases += len(cases)
result_text += f"Total: {total_cases} TEST_CASEs across {len(test_cases)} files\n\n"
# Add usage instructions
result_text += "Usage Examples:\n"
result_text += "• Run specific test file: bash test algorithm\n"
result_text += "• Run with verbose output: uv run test.py --cpp algorithm --verbose\n"
if test_cases:
first_test = list(test_cases.keys())[0]
if test_cases[first_test]:
first_case = test_cases[first_test][0]
result_text += f"• Run specific test: bash test {first_test}\n"
result_text += f" (Note: Individual TEST_CASE execution requires test framework support)\n"
return CallToolResult(
content=[TextContent(type="text", text=result_text)]
)
def extract_test_cases(file_path: Path, search_pattern: str = "") -> List[str]:
"""Extract TEST_CASE names from a test file."""
test_cases: List[str] = []
try:
with open(file_path, 'r', encoding='utf-8') as f:
content = f.read()
# Find TEST_CASE macros using regex
pattern = r'TEST_CASE\s*\(\s*"([^"]+)"'
matches = re.findall(pattern, content)
for match in matches:
if not search_pattern or search_pattern.lower() in match.lower():
test_cases.append(match)
except Exception:
# Silently skip files that can't be read
pass
return test_cases
async def test_instructions(arguments: Dict[str, Any], project_root: Path) -> CallToolResult:
"""Provide detailed instructions on running TEST_CASEs."""
instructions = """
# FastLED TEST_CASE Execution Guide
## Overview
FastLED uses the **doctest** framework for C++ unit testing. Tests are organized in files named `test_*.cpp` in the `tests/` directory. Each file can contain multiple `TEST_CASE` macros.
## Test Structure
- **Test Files**: Located in `tests/test_*.cpp` (e.g., `test_algorithm.cpp`, `test_easing.cpp`)
- **TEST_CASEs**: Individual test functions defined with `TEST_CASE("name")` macro
- **SUBCASEs**: Nested test sections within TEST_CASEs using `SUBCASE("name")`
## Running Tests
### 🚨 CRITICAL: Always Use `bash test` Format
**[OK] CORRECT Format:**
```bash
bash test # Run all tests
bash test <test_name> # Run specific test
```
**[ERROR] INCORRECT Format:**
```bash
./.build/bin/test_<name>.exe # DO NOT run executables directly
./tests/.build/bin/test_* # DO NOT use this format
```
### 1. Run All Tests
```bash
bash test
```
### 2. Run Specific Test File
```bash
bash test <test_name>
```
Example: `bash test algorithm` (runs `test_algorithm.cpp`)
Example: `bash test audio_json_parsing` (runs `test_audio_json_parsing.cpp`)
### 3. Alternative: Using test.py directly
For advanced options, you can also use:
```bash
uv run test.py # Run all tests
uv run test.py --cpp # Run only C++ tests
uv run test.py --cpp <name> # Run specific test file
```
### 4. Run with Verbose Output
```bash
uv run test.py --cpp <test_name> --verbose
```
### 5. Using MCP Server Tools
```bash
# Start MCP server
uv run mcp_server.py
# Available MCP tools:
# - run_tests: Run tests with various options
# - list_test_cases: List available TEST_CASEs
# - test_instructions: Show this guide
```
## Example Workflows
### Debug a Specific Algorithm Test
```bash
# Run algorithm tests
bash test algorithm
# Or with verbose output
uv run test.py --cpp algorithm --verbose
# List available TEST_CASEs in algorithm tests
# (use MCP list_test_cases tool with test_file: "algorithm")
```
### Test Development Workflow
```bash
# Clean build and run specific test
uv run test.py --cpp easing --clean --verbose
# Check for specific TEST_CASE patterns
# (use MCP list_test_cases tool with search_pattern)
```
## Common Test File Names
- `test_algorithm.cpp`: Algorithm utilities
- `test_easing.cpp`: Easing functions
- `test_hsv16.cpp`: HSV color space tests
- `test_math.cpp`: Mathematical functions
- `test_vector.cpp`: Vector container tests
- `test_fx.cpp`: Effects framework tests
- `test_audio_json_parsing.cpp`: Audio JSON parsing tests
## Tips
1. **Always use `bash test <name>`** format for running specific tests
2. **Use `--verbose`** to see detailed test output and assertions
3. **Use `--clean`** when testing after code changes
4. **List TEST_CASEs first** to see what's available before running
5. **Check test output carefully** - doctest provides detailed failure information
## Environment Setup
- Have UV in your environment
- Use `bash test` or `uv run test.py` - don't try to run test executables manually
- The test infrastructure handles platform differences and proper execution
## Why Use `bash test`?
The `bash test` wrapper:
- Handles platform differences automatically
- Sets up the proper environment
- Manages test execution across different systems
- Provides consistent behavior regardless of OS
"""
return CallToolResult(
content=[TextContent(type="text", text=instructions.strip())]
)
async def coding_standards(arguments: Dict[str, Any], project_root: Path) -> CallToolResult:
"""Provide FastLED coding standards and best practices."""
topic = arguments.get("topic", "all")
standards = {
"exceptions": """
# Exception Handling Standards
⚠️ **CRITICAL: DO NOT use try-catch blocks or C++ exception handling in FastLED code**
## Why No Exceptions?
FastLED is designed for embedded systems like Arduino where:
- Exception handling may not be available
- Exceptions consume significant memory and performance
- Reliable operation across all platforms is required
## What to Avoid:
[ERROR] `try { ... } catch (const std::exception& e) { ... }`
[ERROR] `throw std::runtime_error("error message")`
[ERROR] `#include <exception>` or `#include <stdexcept>`
## Use Instead:
[OK] **Return error codes:** `bool function() { return false; }`
[OK] **Optional types:** `fl::optional<T>`
[OK] **Assertions:** `FL_ASSERT(condition)`
[OK] **Early returns:** `if (!valid) return false;`
[OK] **Status objects:** Custom result types
## Examples:
```cpp
// Good: Using return codes
bool initializeHardware() {
if (!setupPins()) {
FL_WARN("Failed to setup pins");
return false;
}
return true;
}
// Good: Using fl::optional
fl::optional<float> calculateValue(int input) {
if (input < 0) {
return fl::nullopt;
}
return fl::make_optional(sqrt(input));
}
```
""",
"std_namespace": """
# Standard Library Namespace Standards
⚠️ **DO NOT use std:: prefixed functions or headers**
FastLED provides its own STL-equivalent implementations under the `fl::` namespace.
## Common Replacements:
- [ERROR] `#include <vector>` → [OK] `#include "fl/vector.h"`
- [ERROR] `#include <algorithm>` → [OK] `#include "fl/algorithm.h"`
- [ERROR] `std::move()` → [OK] `fl::move()`
- [ERROR] `std::vector` → [OK] `fl::vector`
**Always check if there's a `fl::` equivalent in `src/fl/` first!**
""",
"naming": """
# Naming Conventions
## Class/Object Names:
**Simple Objects:** lowercase (e.g., `fl::vec2f`, `fl::point`, `fl::rect`)
**Complex Objects:** CamelCase (e.g., `Raster`, `Controller`, `Canvas`)
**Pixel Types:** ALL CAPS (e.g., `CRGB`, `CHSV`, `RGB24`)
## Member Variables and Functions:
### Complex Classes/Objects:
[OK] **Member variables:** Use `mVariableName` format (e.g., `mPixelCount`, `mBufferSize`, `mCurrentIndex`)
[OK] **Member functions:** Use camelCase (e.g., `getValue()`, `setPixelColor()`, `updateBuffer()`)
[ERROR] Avoid: `m_variable_name`, `variableName`, `GetValue()`, `set_pixel_color()`
### Simple Classes/Structs:
[OK] **Member variables:** Use lowercase snake_case (e.g., `x`, `y`, `width`, `height`, `pixel_count`)
[OK] **Member functions:** Use camelCase (e.g., `getValue()`, `setPosition()`, `normalize()`)
[ERROR] Avoid: `mX`, `mY`, `get_value()`, `set_position()`
## Examples:
```cpp
// Complex class - use mVariableName for members
class Controller {
private:
int mPixelCount; // [OK] Complex class member variable
uint8_t* mBuffer; // [OK] Complex class member variable
bool mIsInitialized; // [OK] Complex class member variable
public:
void setPixelCount(int count); // [OK] Complex class member function
int getPixelCount() const; // [OK] Complex class member function
void updateBuffer(); // [OK] Complex class member function
};
// Simple struct - use snake_case for members
struct vec2 {
int x; // [OK] Simple struct member variable
int y; // [OK] Simple struct member variable
float magnitude() const; // [OK] Simple struct member function
void normalize(); // [OK] Simple struct member function
};
struct point {
float x; // [OK] Simple struct member variable
float y; // [OK] Simple struct member variable
float z; // [OK] Simple struct member variable
void setPosition(float x, float y, float z); // [OK] Simple struct member function
float distanceTo(const point& other) const; // [OK] Simple struct member function
};
```
**Why:** Complex classes use Hungarian notation for member variables to clearly distinguish them from local variables, while simple structs use concise snake_case for lightweight data containers.
""",
"member_naming": """
# Member Variable and Function Naming Standards
## Complex Classes/Objects:
[OK] **Member variables:** Use `mVariableName` format (e.g., `mPixelCount`, `mBufferSize`, `mCurrentIndex`)
[OK] **Member functions:** Use camelCase (e.g., `getValue()`, `setPixelColor()`, `updateBuffer()`)
[ERROR] Avoid: `m_variable_name`, `variableName`, `GetValue()`, `set_pixel_color()`
## Simple Classes/Structs:
[OK] **Member variables:** Use lowercase snake_case (e.g., `x`, `y`, `width`, `height`, `pixel_count`)
[OK] **Member functions:** Use camelCase (e.g., `getValue()`, `setPosition()`, `normalize()`)
[ERROR] Avoid: `mX`, `mY`, `get_value()`, `set_position()`
## Examples:
```cpp
// Complex class - use mVariableName for members
class Controller {
private:
int mPixelCount; // [OK] Complex class member variable
uint8_t* mBuffer; // [OK] Complex class member variable
bool mIsInitialized; // [OK] Complex class member variable
public:
void setPixelCount(int count); // [OK] Complex class member function
int getPixelCount() const; // [OK] Complex class member function
void updateBuffer(); // [OK] Complex class member function
};
// Simple struct - use snake_case for members
struct vec2 {
int x; // [OK] Simple struct member variable
int y; // [OK] Simple struct member variable
float magnitude() const; // [OK] Simple struct member function
void normalize(); // [OK] Simple struct member function
};
struct point {
float x; // [OK] Simple struct member variable
float y; // [OK] Simple struct member variable
float z; // [OK] Simple struct member variable
void setPosition(float x, float y, float z); // [OK] Simple struct member function
float distanceTo(const point& other) const; // [OK] Simple struct member function
};
```
**Why:** Complex classes use Hungarian notation for member variables to clearly distinguish them from local variables, while simple structs use concise snake_case for lightweight data containers.
""",
"containers": """
# Container Parameter Standards
**Prefer `fl::span<T>` over `fl::vector<T>` for function parameters**
[OK] `void processData(fl::span<const uint8_t> data)`
[ERROR] `void processData(fl::vector<uint8_t>& data)`
Benefits: automatic conversion, type safety, zero-cost abstraction
""",