## Build & Verification
After modifying any `.ss` (Gerbil Scheme) source files, always run the build command and fix any errors before moving on. Common issues include: missing imports, wrong function names, and duplicate definitions.
## Gerbil MCP Tools — MANDATORY Usage
When a Gerbil MCP server is available, you MUST use its tools extensively instead of guessing about Gerbil APIs, syntax, or behavior. Gerbil is a niche Scheme dialect with limited training data — always verify with live tools rather than relying on memory.
### Before Writing Code — Cookbook First!
- **`gerbil_howto`** (**MUST call FIRST**): Before writing ANY non-trivial Gerbil code, search the cookbook for relevant patterns. The cookbook contains verified, working examples with correct imports, arities, and keyword conventions — accumulated from real debugging sessions. Many bugs (wrong arity, missing parent arg, keyword vs positional) are already documented here. Search with the widget/module/task name (e.g., `"dialog create"`, `"layout parent"`, `"shortcut keyboard"`, `"hash iterate"`). **Skipping this step has repeatedly caused bugs that were already solved in the cookbook.**
- **`gerbil_security_scan`** (**MUST run on new/modified code**): Before finalizing ANY Gerbil code that involves FFI, shell commands, file I/O, or C shims, run the security scanner. It checks for known vulnerability patterns (shell injection, FFI type mismatches, resource leaks, unsafe C patterns) and reports findings with severity and remediation guidance. Run on a single file or an entire project. **Skipping this step risks shipping code with known vulnerability patterns that the scanner would have caught.**
- **`gerbil_module_exports`**: Check what a module actually exports before using it. Never guess function names. Handles modules with Gambit `(declare ...)` forms by falling back to compiled `.scm` artifacts.
- **`gerbil_function_signature`**: Check procedure arities and keyword arguments before calling functions. Prevents wrong-number-of-arguments errors. Falls back to scanning compiled `.scm` artifacts for `keyword-dispatch` patterns when source is unavailable. Shows positional vs keyword args for keyword-dispatch functions.
- **`gerbil_check_syntax`**: Validate syntax of any code you write before presenting it.
- **`gerbil_batch_syntax_check`**: Check multiple Gerbil code snippets for syntax validity in a single call. Accepts an array of `{id, code}` objects and returns per-snippet pass/fail results. Much more efficient than individual `gerbil_check_syntax` calls when verifying many functions at once.
- **`gerbil_compile_check`**: Run the full compiler (`gxc -S`) to catch unbound identifiers and type issues beyond syntax. Combines stdout/stderr for complete error output.
- **`gerbil_doc`**: Look up any symbol for type, arity, qualified name, and related symbols.
### When Exploring or Debugging
- **`gerbil_eval`**: Test expressions interactively to verify assumptions and reproduce issues. Cleanly captures stdout output separately from the return value using `parameterize`. Use `env` parameter for FFI library paths (e.g. `DYLD_LIBRARY_PATH`, `LD_LIBRARY_PATH`).
- **`gerbil_apropos`**: Search for symbols by substring when you're unsure of exact names.
- **`gerbil_list_std_modules`**: Discover available standard library modules, optionally filtered by prefix.
- **`gerbil_find_definition`**: Locate where a symbol is defined (source file, module, kind, arity). Use `source_preview: true` to include a code preview. Automatically resolves standard library source files via the Gerbil installation's `src/` tree (`lib/` → `src/` path rewrite).
- **`gerbil_smart_complete`**: Context-aware symbol completion for partial identifiers. Optionally scope completions to specific modules.
- **`gerbil_explain_error`**: Classify Gerbil/Gambit error messages with likely causes, suggested fixes, and relevant cookbook recipes.
- **`gerbil_load_file`**: Parse a `.ss` file to extract its imports, exports, and definitions without executing it.
- **`gerbil_module_deps`**: See what a module imports. Use `transitive: true` for full dependency tree.
- **`gerbil_demangle`**: Decode Gambit-mangled C symbol names from GDB backtraces or core dumps back to readable Gerbil module/function paths. Recognizes prefixes like `___H_` (module init), `___G_` (global).
- **`gerbil_bisect_crash`**: Binary-search a crashing Gerbil file to find the minimal set of top-level forms that reproduce the crash. Keeps preamble (imports, exports, declarations) and bisects body forms. Useful for isolating segfaults and uncaught exceptions in FFI code.
- **`gerbil_describe`**: Evaluate an expression and describe the resulting value's type, structure, and contents. Shows hash table entries, list length, vector elements, string length, number type, etc. Useful for understanding what a function returns.
- **`gerbil_stack_trace_decode`**: Parse GDB/Gambit stack traces and decode mangled C symbol names to readable Gerbil module/function paths. Complements `gerbil_demangle` for full backtrace analysis.
- **`gerbil_function_behavior`**: Generate a behavior card for a Gerbil function showing return values for normal cases, edge cases, and error conditions. Has ~50 built-in cards covering hash operations, sorting, list utilities, JSON, path functions, alist operations, and control flow gotchas (when/unless returning `#!void`). For unknown functions, generates test cases dynamically.
- **`gerbil_error_fix_lookup`**: Look up known fixes for Gerbil error messages. Searches ~20 built-in error→fix mappings covering common issues like wrong arity, unbound identifiers, import conflicts, and segfaults. Returns matching patterns with explanations, fixes, and related cookbook recipes.
- **`gerbil_stdlib_source`**: Read the source code of any standard library module. Resolves module paths to source files via lib→src path rewrite. Useful for understanding internal implementations.
- **`gerbil_trace_eval`**: Step through `let*/let/letrec/letrec*` bindings, showing each variable's name, type, and value as it is bound. Useful for understanding complex binding sequences.
- **`gerbil_sxml_inspect`**: Parse XML text or evaluate an SXML expression and display the tree structure with labeled node types (DOCUMENT, PI, ELEMENT, ATTR, TEXT).
- **`gerbil_port_fd_inspector`**: Extract the internal file descriptor number and properties from a Gambit port object. Evaluates an expression that returns a port and reports fd number, fd type, input/output direction, and tty status. Useful for debugging fd/port dual-layer issues (redirect offsets, pipe lifecycle, dup2). Parameters: `expression` (required), `imports`, `loadpath`, `project_path`, `env`.
### When Understanding Macros
- **`gerbil_expand_macro`**: See the fully expanded core form of a macro expression.
- **`gerbil_trace_macro`**: Step-by-step expansion showing each transformation level.
### When Working with Types and FFI
- **`gerbil_class_info`**: Inspect defclass/defstruct types — slots, fields, inheritance, precedence list, and exact constructor signature with positional argument order (annotates inherited fields).
- **`gerbil_ffi_inspect`**: Classify a module's FFI exports (C constants, C functions, Gerbil wrappers).
- **`gerbil_ffi_scaffold`**: Parse a C header file and generate Gambit FFI binding code with `c-define-type`, `c-lambda`, and `define-const` declarations. Recognizes create/destroy pairs for automatic GC cleanup.
- **`gerbil_ffi_callback_debug`**: Static analysis of FFI `c-define`/`extern` linkage in `.ss` files. Detects orphan callbacks (c-define without matching extern), missing callbacks (extern without c-define), duplicate C names, and c-define outside `begin-foreign` blocks.
- **`gerbil_ffi_type_check`**: Detect FFI type mismatches between `c-lambda`/`define-c-lambda` declarations and call sites. Flags known incompatible combinations like u8vector passed to `(pointer void)`, string passed to int. Static analysis, no subprocess.
- **`gerbil_ffi_null_safety`**: Static analysis of `.scm` FFI files to find `c-lambda` declarations that dereference pointer arguments without null checks. Cross-references with `.ss` wrapper files to check for guards.
- **`gerbil_ffi_buffer_size_audit`**: Cross-reference C function output buffer sizes with Scheme-side `make-u8vector` allocations. Detects potential buffer overflow mismatches.
- **`gerbil_ffi_link_check`**: Cross-reference C function calls in `c-declare` blocks against symbols exported by linked static libraries (`.a` files) via `nm`. Catches missing library links (undefined symbol errors) before a full build-test cycle. Reads library paths from `build.ss` `ld-options` or accepts explicit paths.
- **`gerbil_detect_ifdef_stubs`**: Scan `c-declare` blocks for `#ifdef`/`#else` stub patterns that return NULL, 0, or `(void*)0`. These stubs are a common source of segfaults in cross-project exe builds because Gambit's exe builder doesn't propagate per-module `cc-options`, causing the `#else` fallback branch to compile instead of the real implementation. Scans a single file (`file_path`) or entire project (`project_path`).
- **`gerbil_error_hierarchy`**: View the full exception/error class hierarchy tree.
- **`gerbil_gambit_source_extract`**: Identify the exact Gambit commit Gerbil was built with (from `gsc -v`) and optionally extract matching source files from a Gambit git repo. Reports version, commit hash, build date, and architecture. When `gambit_repo_path` is provided, extracts source subdirectories matching the commit. Critical for embedding `gambitgsc` modules. Parameters: `gambit_repo_path`, `output_dir`, `subdirs` (all optional).
### For Multi-Step Exploration
- **`gerbil_repl_session`**: Maintain persistent state across evaluations. Define functions, import modules, test incrementally. Use `preload_file` to load a file's imports into the session automatically. Use `env` parameter for FFI library paths.
### For Building and Testing
- **`gerbil_build_project`**: Compile or clean a project directory using gxpkg.
- **`gerbil_build_and_report`**: Run `gerbil build` and get structured diagnostics with file, line, column. Prefer this over running `gerbil build` via bash for better error reporting. Auto-detects external dependencies from `gerbil.pkg` `depend:` entries and sets `GERBIL_LOADPATH` automatically. Auto-retries with clean on lock errors or missing exe C files. Detects missing C system headers and suggests package install commands. Use `loadpath` to override. Use `modules_only: true` to skip exe linking targets and only compile library modules (dramatically faster when iterating on code and running tests).
- **`gerbil_build_conflict_check`**: Detect when multiple gerbil build processes are running on the same project directory. Checks for running processes via ps, lock files in .gerbil/, and matching working directories. Warns about potential conflicts with suggestions to kill old builds.
- **`gerbil_build_progress`**: Monitor build output from a background task. Shows current phase (compile/link/install/clean), modules compiled, errors, warnings, and whether the build is still running. Pass `output_file` for background task output or `build_output` for direct text.
- **`gerbil_check_c_library`**: Scan build.ss for -lXXX linker flags and check if those C libraries are available via pkg-config or ldconfig. Reports missing libraries with suggested apt install commands. Use before building FFI projects to catch missing dependencies early.
- **`gerbil_build_chain`**: Build a chain of dependent Gerbil projects in dependency order. Reads `gerbil.pkg` `depend:` entries and `GERBIL_LOADPATH` from Makefile to find upstream projects, checks if they need rebuilding (source newer than artifacts), and builds them before the target. Use `dry_run: true` to preview the build plan without executing.
- **`gerbil_run_tests`**: Execute a single `:std/test` file (`file_path`) or run project-wide tests (`directory`). Use `filter` to match test names, `quiet` for errors-only output. Auto-detects `GERBIL_LOADPATH` from `gerbil.pkg` `depend:` entries. Use `env` parameter for FFI library paths (e.g. `DYLD_LIBRARY_PATH`). Use `clean_stale: true` to remove stale compiled artifacts before running tests. Use `verbose: true` in single-file mode for check expression tracing.
- **`gerbil_dispatch_coverage_analysis`**: Analyze functional test files for command interaction coverage gaps. Identifies commands tested in isolation but never in combination with other commands. Scans for `execute-command!` calls and suggests missing interaction patterns. Helps detect missing test scenarios for multi-command sequences that could reveal state management bugs.
- **`gerbil_package_info`**: List installed packages, search the package directory, or view metadata.
- **`gerbil_package_manage`**: Install, update, or uninstall Gerbil packages. Automatically defaults to `$HOME` as working directory when in a project directory (with `gerbil.pkg`) to prevent destructive operations on local package context.
- **`gerbil_scaffold`**: Create a new Gerbil project from a template using gxpkg new.
- **`gerbil_stale_static`**: Compare compiled artifacts in global `$GERBIL_PATH/lib/static/` vs project-local `.gerbil/lib/static/` to detect stale global copies that could shadow the current build. Common cause of segfaults and `#!unbound` errors in compiled executables.
- **`gerbil_stale_linked_pkg`**: Detect stale linked packages (via `gerbil pkg link`) whose source `.ss` files are newer than compiled `.ssi`/`.scm` artifacts. Reports which packages need rebuilding with `gerbil pkg build`.
- **`gerbil_make`**: Run Makefile targets in a Gerbil project directory. Useful for projects that use `make build` instead of `gerbil build` directly.
- **`gerbil_check_arity`**: Detect functions called with the wrong number of arguments across a project. Compares call sites against known arities from local definitions and standard library introspection.
- **`gerbil_check_test_arity`**: Scan `*-test.ss` files for calls to a specific function and check if call-site arities match the function's signature. Useful when changing a function's parameters to find affected tests.
- **`gerbil_signature_impact`**: Combined pre-signature-change impact report. Finds ALL call sites (source + test files) for a function in one call. Optionally specify `new_arity` to preview which call sites would break.
- **`gerbil_test_assertion_audit`**: Detect common :std/test check assertion mistakes that silently pass — `(check X ? #f)`, `(check X ? values)`, type mismatches, missing operators.
- **`gerbil_build_linkage_diagnostic`**: Analyze exe targets in `build.ss` for missing transitive FFI link dependencies. Traces imports from exe main modules, identifies FFI modules, and checks whether `ld-options` include the required static libraries. Catches silent linkage failures where an exe produces a broken binary due to missing `-L`/`-l` flags. Use `exe_target` to check a specific target.
- **`gerbil_qt_test_runner`**: Build and run a Qt FFI test executable in one step. Handles build, patchelf rpath, and QT_QPA_PLATFORM=offscreen automatically. Use `skip_build` to rerun without rebuilding. Use `rpath` to override auto-detected rpath values.
- **`gerbil_pkg_link_sync`**: Detect and sync stale linked-package artifacts (.ssi, .so, .scm) between a package's local build and global ~/.gerbil/lib/. Dry-run by default. Use `sync: true` to copy stale artifacts. Complements `gerbil_stale_linked_pkg` with actual sync capability.
### For Performance Analysis
- **`gerbil_profile`**: Instrument specific functions with call counting and timing. Reports per-function stats (calls, time, avg, %) plus overall wall/CPU/GC time and allocation.
- **`gerbil_heap_profile`**: Capture GC heap metrics before/after an expression. Reports heap size, allocation, live/movable/still objects with deltas.
- **`gerbil_trace_calls`**: Lightweight call counting (no timing overhead). Count how many times specified functions are called.
- **`gerbil_benchmark_compare`**: Run a benchmark command, save results as a named baseline, and compare against previous runs with percentage changes.
### For Code Quality
- **`gerbil_lint`**: Static analysis for common issues: unused imports, duplicate definitions, style warnings, shadowed bindings, hash literal symbol key warnings, channel anti-patterns, unquote outside quasiquote, dot in brackets, missing exported definitions (re-export aware), port-type mismatches (fdopen byte ports used with char I/O), pregexp inline flag detection ((?i)/(?m)/(?s)/(?x) cause runtime crashes in :std/pregexp), and compilation errors.
- **`gerbil_diagnostics`**: Run `gxc -S` on a file or project and get structured diagnostics with file, line, column, severity, and message. Use `loadpath` to resolve project-local module imports.
- **`gerbil_check_exports`**: Cross-module export/import consistency checker. Detects symbols exported but not defined, and cross-module import mismatches across a project.
- **`gerbil_check_import_conflicts`**: Detect import conflicts before build and suggest fixes. Checks if locally defined symbols conflict with imported module exports (causing "Bad binding; import conflict" errors), and if multiple imports export the same symbol. Detects cross-module export collisions where sibling modules export the same symbol. Resolves standard library exports at runtime and project-local exports statically. Handles `only-in` filtered imports. For each conflict, suggests fixes using `(only-in)` or `(except-in)`. Supports batch checking via `project_path`.
- **`gerbil_dead_code`**: Detect unexported, uncalled definitions across a project. Finds functions/values that are defined but never referenced from other files and not exported.
- **`gerbil_dependency_cycles`**: Detect circular module dependencies in a project using DFS cycle detection. Reports all unique cycles found.
- **`gerbil_migration_check`**: Scan Gerbil source files for v0.18 → v0.19 migration issues. Detects deprecated patterns (e.g. `define` → `def`, `hash-ref` → `hash-get`, getopt module rename) with severity levels and suggested fixes.
- **`gerbil_diff_modules`**: Compare exports between two modules, showing added, removed, and shared symbols. Useful for understanding API differences between module versions.
- **`gerbil_cross_package_diff`**: Compare function signatures (arity, kind) between two Gerbil modules from potentially different packages. Shows symbols only in each module and shared symbols with different arities. Critical for debugging wrapper/wrapped function mismatches (e.g. a shim with different parameter defaults). Use `show_shared: true` to also show matching signatures.
- **`gerbil_format`**: Pretty-print Gerbil expressions using Gambit's pretty-print.
- **`gerbil_benchmark`**: Measure wall-clock time, CPU time, GC stats, and memory allocation.
- **`gerbil_tail_position_check`**: Analyze whether recursive calls in a function are in tail position. Detects non-tail calls wrapped in forms like `+`, `cons`, `let`.
- **`gerbil_return_type_analysis`**: Detect gotcha return values: `hash-ref` returning `#!void`, `when`/`unless` returning `#<void>`, and other common Gerbil return value pitfalls.
- **`gerbil_method_dispatch_audit`**: Detect `{method-name obj}` dispatch calls and cross-reference with `defmethod` declarations to find potential dispatch mismatches.
- **`gerbil_macro_hygiene_check`**: Detect free variable capture in `defrule`/`defsyntax` macro definitions — a common source of subtle bugs.
- **`gerbil_interface_compliance_check`**: Verify that struct/class types implement all required interface methods by cross-referencing type definitions with interface declarations.
- **`gerbil_concurrent_plan_validate`**: Validate DAG-based execution plans (step dependencies). Detects circular dependencies, missing steps, and unreachable steps.
- **`gerbil_project_health_check`**: Composite project audit that runs lint, dead code detection, dependency cycle checking, and export consistency in a single call.
- **`gerbil_check_duplicates`**: Fast pre-build check for duplicate top-level definitions (def, defmethod, defrule, defsyntax, defstruct, etc.). Reports line numbers for both original and duplicate. Catches "Bad binding; rebind conflict" errors before the slow compilation step. No subprocess needed.
- **`gerbil_verify`**: Combined verification tool that runs syntax check, compile check (gxc -S), lint, arity check, and duplicate definition detection in a single pass. Returns a unified issue list with phase, severity, and line numbers. Saves multiple tool calls when validating code. Skips syntax phase for FFI code (begin-ffi, begin-foreign) to avoid false EOF errors.
- **`gerbil_cross_module_check`**: Detect cross-module unbound symbol references before compilation. Extracts definitions and references from each file, resolves imports, and reports symbols used but not imported or locally defined. Invaluable when splitting large modules into sub-modules — catches all unbound identifier errors in one pass instead of iterative compile-fix cycles. Use `files` to limit scope.
- **`gerbil_pattern_cache_check`**: Detect regex/pattern compilation anti-patterns in Gerbil code. Finds pregexp/pcre2-compile inside function bodies or loops, dynamic pattern building via string-append, redundant wrapping, and duplicate patterns.
- **`gerbil_sigchld_check`**: Detect SIGCHLD/process-status incompatibility when add-signal-handler! blocks SIGCHLD via signalfd.
### For Security Auditing
- **`gerbil_security_scan`**: Static security scanner for Gerbil `.ss` and C `.c`/`.h` files. Scans for known vulnerability patterns including shell injection via string concatenation, FFI `(pointer void)` type mismatches, `___alloc_scmobj` without `___FIXNUMP` failure checks, ports opened without `unwind-protect`, C buffer silent truncation, static global buffers (thread safety), and unused security-relevant parameters. Reports findings with severity (critical/high/medium/low), line number, and remediation guidance. Scans a single file (`file_path`) or entire project (`project_path`). Merge custom rules via `rules_path`. Filter by `severity_threshold`. Supports inline suppression comments to silence specific findings.
- **`gerbil_security_pattern_add`**: Add new security detection rules to the scanner. Each rule needs an `id` (kebab-case), `title`, `severity` (critical/high/medium/low), `scope` (scheme/c-shim/ffi-boundary), `pattern` (regex), `message` (vulnerability explanation), and `remediation` (fix guidance). Optional: `related_recipe` (cookbook recipe ID with fix), `tags` (search keywords). If a rule with the same `id` exists, it is replaced (update semantics). By default writes to the gerbil-mcp repo `security-rules.json`.
### For Macro Development and Refactoring
- **`gerbil_macro_pattern_detector`**: Analyze Gerbil source files for repetitive code patterns that could be replaced with macros. Detects: (1) repeated function definitions with similar structure, (2) repeated hash-ref accessors, (3) repeated method wrappers. For each pattern, suggests a macro definition and shows potential code size reduction.
- **`gerbil_boilerplate_converter`**: Convert repetitive code blocks into macro definitions automatically. Given 2+ similar Scheme expressions, extracts the common pattern and generates a `defrule` macro with appropriate pattern variables. Returns both the macro definition and replacement invocations, showing code reduction.
- **`gerbil_signal_trace`**: Generate Gerbil code for debugging signal handling. Creates an instrumentation module that logs when signals are received, when handlers execute, and whether exceptions occur. Outputs timestamped trace log. Useful for debugging unresponsive CTRL-C, trap execution failures, or process hangs.
- **`gerbil_macro_expansion_size`**: Analyze macro expansion size to detect accidentally explosive macros. Expands a macro invocation and compares the number of forms/tokens in the source vs expanded output. Reports expansion ratio and warning level (ok/large/explosive). Helps catch macros that expand recursively, generate more code than expected, or should be functions instead.
- **`gerbil_macro_template_library`**: Generate reusable macro templates for common patterns. Supports: hash-accessors, method-delegation, validation-guards, enum-constants, event-handlers, type-setters. Returns working `defrule` definitions with example invocations and expansions, customized with project-specific naming. Ready to copy into your project.
### For Navigation and Discovery
- **`gerbil_document_symbols`**: List all definitions in a file with name, kind, and line number.
- **`gerbil_workspace_symbols`**: Search for symbol definitions across all `.ss` files in a project directory.
- **`gerbil_find_callers`**: Find all files in a directory that reference a given symbol, with line numbers.
- **`gerbil_suggest_imports`**: Discover which standard library module exports a given symbol.
- **`gerbil_call_graph`**: Static call graph analysis — see which functions call which in a source file.
- **`gerbil_check_balance`**: Fast paren/bracket/brace balance checking without spawning a subprocess. Handles `#!` reader directives and suggests cross-checking with `gerbil_read_forms` on errors.
- **`gerbil_read_forms`**: Read a file with the actual Gerbil reader and see each form's line range and summary.
- **`gerbil_version`**: Check Gerbil/Gambit versions, installation path, and system type.
- **`gerbil_preflight_check`**: Diagnostic tool that verifies MCP server prerequisites and Gerbil environment health. Checks gxi/gxc/gerbil availability, Gerbil version, `GERBIL_HOME`/`GERBIL_PATH`, basic eval functionality, and optionally checks a TypeScript MCP server project (dist/, node_modules). Use when tools are not working or to verify the environment.
### For Refactoring and Code Generation
- **`gerbil_rename_symbol`**: Rename a symbol across all `.ss` files in a project directory or in a single file. Uses word-boundary detection to avoid partial matches. Dry-run by default. Use `file_path` for single-file local renames.
- **`gerbil_generate_module_stub`**: Generate a module skeleton matching another module's exported signatures.
- **`gerbil_generate_module`**: Create new modules by applying word-boundary-aware substitutions to a template file. Useful for mechanical variations of an existing module pattern.
- **`gerbil_scaffold_test`**: Generate a `:std/test` skeleton from a module's exports.
- **`gerbil_balanced_replace`**: Like Edit/string-replace but validates delimiter balance before and after. Rejects edits that would break balance, but tolerates matching imbalance where old and new fragments have the same net delimiter change. Dry-run by default.
- **`gerbil_wrap_form`**: Wrap lines in a new Scheme form (e.g. `when`, `let`, `begin`) with guaranteed matching parentheses. Auto-detects form boundaries when `end_line` is omitted. Dry-run by default.
- **`gerbil_splice_form`**: Remove a wrapper form while keeping selected children (inverse of wrap). Child indices are 1-based. Default: keep all children except the head. Dry-run by default.
- **`gerbil_generate_api_docs`**: Generate markdown API documentation from a module's exports. Introspects procedures (with arities), macros, and values to produce a complete API reference.
- **`gerbil_httpd_handler_scaffold`**: Generate HTTP server code from route specifications. Produces handler functions, routing setup, and middleware patterns for `:std/net/httpd`.
- **`gerbil_parser_grammar_scaffold`**: Generate `deflexer`/`defparser` skeleton from token and rule specifications for `:std/parser`.
- **`gerbil_actor_ensemble_scaffold`**: Generate distributed actor project template with multiple actor types, message protocols, and supervision trees.
- **`gerbil_test_fixture_gen`**: Generate mock modules, factory functions, and `parameterize`-based test setup/teardown patterns for `:std/test`.
- **`gerbil_db_pattern_scaffold`**: Generate database CRUD patterns with connection pooling for SQLite (`:std/db/sqlite`) or PostgreSQL (`:std/db/postgresql`).
- **`gerbil_graceful_shutdown_scaffold`**: Generate signal handling and cleanup patterns with optional actor system integration.
- **`gerbil_translate_scheme`**: Mechanically translate R7RS or Racket Scheme code to idiomatic Gerbil. Handles ~40 translation rules covering syntax transforms (define→def, struct→defstruct), function renames (hash-has-key?→hash-key?, for/list→for/collect, hash-set!→hash-put!), import translation (require→import with module path mappings), exception handling (with-handlers→try), and macro system differences. Returns translated code plus semantic warnings where behavior differs.
- **`gerbil_project_template`**: Generate a complete Gerbil project from 8 templates (cli, http-api, library, actor-service, db-crud, parser, ffi-wrapper, test-project). Creates gerbil.pkg, build.ss, Makefile, source modules, and test files.
- **`gerbil_resolve_imports`**: Analyze a Gerbil source file for unbound identifiers and generate a suggested import block. Useful when creating new modules or splitting existing ones — automatically discovers which standard library modules export the symbols you need.
### For Project Context
- **`gerbil_project_info`**: Single-call project summary: package name, build targets, source files, and external dependencies.
- **`gerbil_project_map`**: Complete view of all modules with their exports, definitions by kind, and import dependencies.
- **`gerbil_project_dep_graph`**: Visualize project module dependency graph as an ASCII tree. Shows which project modules import from which others. External dependencies listed separately.
- **`gerbil_test_coverage`**: Compare a module's exports against its test file to identify untested symbols. Auto-discovers `*-test.ss` files. Reports coverage percentage.
- **`gerbil_module_catalog`**: Compact reference of all exports from a module with kind, arity, and brief descriptions. Has curated descriptions for `:std/sugar`, `:std/iter`. Replaces multiple `gerbil_doc` calls.
- **`gerbil_example_api_coverage`**: Check which module exports are referenced in example/doc files. Scans a directory of `.ss` files and reports per-export coverage with file references and overall coverage percentage.
- **`gerbil_validate_example_imports`**: Validate that imported modules actually export the symbols used in a Gerbil source file. Hybrid static+runtime analysis that detects symbols used but not available from any import or local definition.
- **`gerbil_module_quickstart`**: Generate a working example file that exercises a module's main exports. Introspects exports, arities, and types, then produces a runnable `.ss` file. Useful for undocumented stdlib modules.
- **`gerbil_dynamic_reference`**: Auto-generate reference documentation for any Gerbil module on demand. Introspects all exports, classifies them (procedure/macro/value/type), and formats as markdown. Not limited to hardcoded reference docs.
- **`gerbil_event_system_guide`**: Interactive guide for `:std/event` patterns (sync, select, choice, wrap, handle, timeout, channels). Topic-based exploration with live module introspection.
### For Recipes and Idioms
- **`gerbil_howto`**: Search curated Gerbil idioms and code examples by keyword with synonym expansion and fuzzy matching. Covers common tasks like file I/O, JSON, HTTP, hash tables, iteration, error handling, concurrency, testing, and more. Use this **before writing Gerbil code** for common patterns — it returns verified, working examples with correct imports. The server automatically loads both built-in recipes and any accumulated recipes from previous sessions. Searches for "dict" automatically include "hash"/"hashtable"/"map"; "flatten" includes "unnest"; "unique" includes "deduplicate"/"distinct"; etc.
- Example queries: `"json parse"`, `"file read"`, `"channel thread"`, `"hash iterate"`, `"error handling"`
- Use `compact: true` for a brief listing (id, title, tags only — no code blocks), then `gerbil_howto_get` to fetch full recipe by id. This saves tokens when browsing.
- Use `max_results` to limit the number of results (default: 5).
- Optionally pass `cookbook_path` to merge in additional project-specific recipes from a JSON file.
- **`gerbil_howto_get`**: Fetch a single cookbook recipe by its ID. Returns the full recipe with code, imports, notes, and related recipes. Use after `gerbil_howto` with `compact: true` to retrieve only the recipes you need.
- **`gerbil_howto_add`**: Save new Gerbil recipes directly to the gerbil-mcp server's cookbook. No path needed — recipes are written to the server's own `cookbooks.json` and become available to all future sessions across all projects. Each recipe needs an `id` (kebab-case), `title`, `tags` (search keywords), `imports`, and `code`. Optional: `notes`, `related` recipe IDs, `supersedes` (ID of an older recipe to mark as deprecated), and `valid_for` (list of confirmed-working version strings, e.g. `["v0.18.1-173", "v0.19.0-42"]`).
- If a recipe with the same `id` already exists, it is replaced (update semantics). Existing `valid_for` is preserved when updating without providing a new one.
- Use `supersedes` to deprecate an older recipe — sets `deprecated: true` and `superseded_by` on the old recipe. Deprecated recipes are deprioritized in search results and shown with a `[DEPRECATED]` marker.
- Optionally pass `cookbook_path` to write to a different file instead.
- **`gerbil_howto_run`**: Compile-check and optionally execute a cookbook recipe by ID. Validates that the recipe's code and imports produce valid Gerbil before running. Reports PASS/FAIL with output.
- **`gerbil_howto_verify`**: Batch-verify cookbook recipes for syntax and optionally compilation validity. Use to maintain cookbook quality.
- **`gerbil_error_fix_add`**: Add new error→fix mappings to the error fix database. Each entry needs an `id`, `pattern` (regex), `message`, `explanation`, `fix`, and optional `related_recipe`.
- **`gerbil_file_summary`**: Quick structural overview of a `.ss` file — imports, exports, and definitions grouped by kind — without reading the entire file. Faster than `gerbil_load_file` when you only need the shape of a module.
### For Feature Suggestions
- **`gerbil_list_features`**: Search or list existing feature suggestions for the gerbil-mcp toolset. Use before suggesting a new feature to check for duplicates. Shows vote counts for each feature. Use `gerbil_version` to filter by Gerbil version — excludes version-tagged features that don't match, while untagged features always pass through.
- **`gerbil_suggest_feature`**: Submit a feature suggestion for a new or improved gerbil-mcp tool. Requires `id`, `title`, `description`, `impact` (high/medium/low), `tags`, `use_case`, `example_scenario`, and `estimated_token_reduction`. Suggestions are stored in the server's `features.json`. New suggestions start with 0 votes. Use `gerbil_version` to tag version-specific features (e.g. "v0.18", "v0.19"). Omit for version-agnostic features.
- **`gerbil_vote_feature`**: Vote for an existing feature suggestion by ID. Use this when you encounter a situation where a suggested feature would have saved time or tokens. Votes help prioritize which features to implement next.
### Key Principle
**Never guess — always verify.** If you are unsure about any Gerbil API, symbol name, module export, function arity, or macro behavior, use the appropriate MCP tool to check before writing code. This is not optional — it is required practice for all Gerbil work in this repository.
---
## MANDATORY: Save What You Learn to the Gerbil Cookbook
This is a **hard requirement**, not a suggestion. Gerbil is a niche language with limited training data. Every non-trivial pattern you discover and verify during a session is valuable knowledge that prevents future sessions from wasting time re-discovering the same thing.
### You MUST call `gerbil_howto_add` whenever you:
- Discover a working pattern through `gerbil_eval`, `gerbil_check_syntax`, or trial-and-error
- Figure out the correct imports, function names, or calling conventions for a module that wasn't obvious
- Find a workaround for a Gerbil quirk, gotcha, or undocumented behavior
- Combine multiple standard library functions to accomplish a common task
- Get something working that required reading source code or experimentation to figure out
### Before saving, first check `gerbil_howto` to avoid duplicates.
### Do NOT save:
- Trivial one-liners that any Scheme programmer would know (e.g., `(+ 1 2)`)
- Project-specific business logic that won't generalize
- Recipes that already exist in the cookbook (check first!)
### When saving, follow these rules:
- **`id`**: Use kebab-case (e.g., `"read-csv-file"`, `"channel-fan-out"`)
- **`tags`**: Include 4-6 search keywords. Think about what someone would type when looking for this pattern. Include the module name, the task, and alternative phrasings.
- **`imports`**: List all required imports. Use `[]` if none needed.
- **`code`**: Include a complete, working example — not a fragment. Someone should be able to copy-paste it.
- **`notes`**: Explain any non-obvious details, gotchas, or alternatives.
### This is not optional. If you solved a non-trivial Gerbil problem during this session and the pattern is reusable, you MUST save it before the session ends.
---
## MANDATORY: Suggest Tooling Improvements
When you notice opportunities to improve the gerbil-mcp toolset during a session, you MUST record them via `gerbil_suggest_feature`. This helps the toolset evolve based on real usage patterns.
### You MUST call `gerbil_suggest_feature` whenever you:
- Find yourself making multiple sequential tool calls that could be a single tool
- Encounter a workflow where a missing tool forces you to fall back to `gerbil_eval` or bash
- Notice repeated patterns across sessions that could be automated
- Discover that an existing tool is missing a useful parameter or mode
### Before suggesting, first check `gerbil_list_features` to avoid duplicates. If a feature already exists that matches your need, vote for it with `gerbil_vote_feature` instead of creating a duplicate.
### When suggesting, fill in all fields honestly:
- **`id`**: Use kebab-case (e.g., `"batch-module-check"`, `"cross-file-rename"`)
- **`impact`**: `"high"` = saves many tokens or round-trips regularly; `"medium"` = useful but less frequent; `"low"` = nice-to-have
- **`tags`**: Include 3-5 search keywords for discoverability
- **`estimated_token_reduction`**: Be specific (e.g., `"~500 tokens per invocation"`, `"eliminates 3 tool calls"`)
---
## Common Workflows
- **Pre-build dependency check**: `gerbil_build_conflict_check` -> `gerbil_check_c_library` -> `gerbil_build_and_report`
## Workflow Conventions
When implementing new features, always complete the documentation update in the same session. Document non-trivial solutions as howto recipes in the cookbook system.
## Language-Specific Notes
When editing Gerbil Scheme, be careful with function naming conventions (e.g., `md5` not `md5sum`) and avoid introducing duplicate definitions across modules.