mo3ta-coverage 1.2.1 → 1.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/AGENT.md CHANGED
@@ -61,9 +61,9 @@ index.js
61
61
  ├─ verifyGitRepoExists() src/gitUtils.js
62
62
  ├─ getExplicitFiles(options) --files / --filesFrom, or
63
63
  ├─ getChangedFiles(base) merge-base diff + working tree, all authors
64
- ├─ dryRun(files, mode, depth) --dryRun: print the would-run test list, exit 0
65
- ├─ runRelatedTests(files, mode, depth)
66
- │ └─ npx jest ... --coverage
64
+ ├─ dryRun(files, mode, depth, filter) --dryRun: print the would-run (filtered) test list, exit 0
65
+ ├─ runRelatedTests(files, mode, depth, jestFlags)
66
+ │ └─ npx jest ... --coverage [--jest flags]
67
67
  └─ reportUncoveredChangedLines(...)
68
68
  ├─ parseLcov(path)
69
69
  ├─ getChangedLines(file, base) git diff -U0
@@ -103,6 +103,19 @@ Depth semantics for `smart`: one edge = an import. `--depth 1` finds test files
103
103
  that import the changed file directly. `--depth 2` also finds test files that
104
104
  import a module which imports the changed file.
105
105
 
106
+ ### Spec filter
107
+
108
+ `--filter <regex>` (CLI, config `"filter"`, or the API/MCP `filter` argument)
109
+ compiles to a regex via `parseFilter()` and is applied to the **final** list
110
+ of selected spec paths by `filterTestFiles()` inside `resolveTestPlan()`.
111
+ `resolveTestPlan` returns both `allTestsToRun` (before the filter) and
112
+ `testsToRun` (after it); `logFilteredTestFiles()` prints both lists so the
113
+ user can validate the regex. An invalid regex throws
114
+ `INVALID_FILTER`, which `main()` turns into exit 1. In `full` mode the regex
115
+ is also appended to Jest's args as `--testPathPatterns` (skipped when the
116
+ caller already supplied a Jest path pattern via `--jest`). Config values are
117
+ merged in `index.js` before `main()`.
118
+
106
119
  ### Coverage reporting
107
120
 
108
121
  - `parseLcov()` absolutizes `SF:` paths.
@@ -143,8 +156,17 @@ import a module which imports the changed file.
143
156
  is matched against repo-relative paths by exact match or path suffix.
144
157
  Over-matching is acceptable (it may run extra tests) but under-matching is not.
145
158
  - `runRelatedTests` exits the process (`exit(0)`/`exit(1)`) rather than throwing.
159
+ - Extra Jest flags come from `--jest` (repeatable or comma-separated, parsed by
160
+ `parseJestArgs`) and are appended after the selected test files in
161
+ `resolveTestPlan`. `.mo3ta-coverage.json` can store a `jest` array as a default;
162
+ a CLI `--jest` overrides it. The API/MCP path reads the same `jest` option.
163
+ - The API's captured run (`buildCapturedJestArgs`) adds `--runInBand` for
164
+ timeout control, but drops it when the caller passes `--maxWorkers`/`-w`/`-i`
165
+ because Jest rejects `--runInBand` together with `--maxWorkers`.
146
166
  - `--dryRun` must keep stdout a clean one-path-per-line list (other tools
147
- consume it); informational messages go to stderr.
167
+ consume it); informational messages go to stderr, including the
168
+ before/after filter log (`dryRun` receives the filter and prints the log
169
+ via `console.error`).
148
170
  - The config subcommand writes `.mo3ta-coverage.json` in `process.cwd()`.
149
171
  - CLI options with commander defaults (`mode`, `depth`) override config unless
150
172
  you check `program.getOptionValueSource(...) === 'cli'`.
package/README.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  mo3ta-coverage checks coverage for changed lines in a pull request. It finds changed source files, maps them to likely test files, runs Jest in a selected execution mode, and validates changed-line coverage against a threshold.
6
6
 
7
+ Project site: https://mo3ta.top/mo3ta-coverage/
8
+
7
9
  ## Demo
8
10
 
9
11
  https://github.com/user-attachments/assets/1139ca7a-69e6-4b41-ad24-ff20e083c4e0
@@ -177,6 +179,8 @@ specs that reach the changed file through barrel files. See
177
179
  | `--depth <number>` | Max reverse-import depth used by `smart` (`1` or `2` recommended) | `2` |
178
180
  | `--files <files...>` | Scan only these files instead of auto-detecting changed files (space- or comma-separated) | – |
179
181
  | `--filesFrom <path>` | Read the file list to scan from a newline-separated file | – |
182
+ | `--jest <value>` | Extra Jest CLI flag passed through to the run, e.g. `--maxWorkers=2`. Repeatable or comma-separated | – |
183
+ | `--filter <regex>` | Regex matched against the final list of selected spec files; only matching test files run. The full and filtered lists are both printed for validation | – |
180
184
  | `--ci <bool>` | CI mode: emit results as a markdown table and save it to a file so CI can read it without parsing logs | `false` |
181
185
  | `--ciReport <path>` | Where to save the CI markdown table | `coverage/mo3ta-coverage-report.md` |
182
186
  | `--dryRun <bool>` | Print the test files that would run (one per line) and stop, without running Jest or the coverage check | `false` |
@@ -203,6 +207,93 @@ Explicitly provided files skip git changed-file detection. Their changed lines
203
207
  are still computed against `--base`, so only lines that differ from the base
204
208
  branch are counted toward coverage.
205
209
 
210
+ ## Passing Extra Jest Flags
211
+
212
+ Use `--jest` to forward any Jest CLI flag to the underlying Jest run, for
213
+ example to control parallelism or silence output. Pass it once per flag, or
214
+ comma-separate several flags in one value:
215
+
216
+ ```sh
217
+ # Limit Jest to 2 workers and run silently
218
+ mo3ta-coverage --base origin/main --jest --maxWorkers=2 --jest --silent
219
+
220
+ # Same thing, comma-separated
221
+ mo3ta-coverage --base origin/main --jest "--maxWorkers=2,--silent"
222
+
223
+ # A single flag that takes a value
224
+ mo3ta-coverage --base origin/main --jest --maxWorkers=50%
225
+ ```
226
+
227
+ The flags are appended to the arguments mo3ta-coverage already passes
228
+ (`--coverage`, `--passWithNoTests`, and the selected test files), so they are
229
+ handled by Jest's own argument parser. Use them for things like `--maxWorkers`,
230
+ `--silent`, `--ci`, `--bail`, `--testTimeout`, or `--coverageDirectory`.
231
+
232
+ Jest flags that take a value work best in the `=` form (`--maxWorkers=2`). If a
233
+ flag's value is normally separated by a space, give each token its own `--jest`:
234
+
235
+ ```sh
236
+ # Equivalent to: jest --maxWorkers 2
237
+ mo3ta-coverage --base origin/main --jest --maxWorkers --jest 2
238
+ ```
239
+
240
+ To make flags the default for a repo, save them with the `config` subcommand:
241
+
242
+ ```sh
243
+ mo3ta-coverage config --jest --maxWorkers=2 --jest --silent
244
+ # written to .mo3ta-coverage.json as "jest": ["--maxWorkers=2", "--silent"]
245
+ ```
246
+
247
+ A `--jest` value on the command line overrides the saved list.
248
+
249
+ ## Filtering Spec Files
250
+
251
+ Pass `--filter` a regular expression. After the mode has selected the test
252
+ files that would run, only the ones that **match** the regex are executed
253
+ (everything else is skipped). The regex is matched against the full
254
+ repo-relative spec path, so it can narrow by directory, project, or name:
255
+
256
+ ```sh
257
+ # Only run specs under the login feature folder
258
+ mo3ta-coverage --base origin/main --filter "src/__tests__/login"
259
+
260
+ # Only run specs whose name contains "auth"
261
+ mo3ta-coverage --base origin/main --filter "auth"
262
+
263
+ # Combined with an explicit file list and a dry run to preview
264
+ mo3ta-coverage --files src/a.js,src/b.ts --base main --dryRun true --filter "b"
265
+ ```
266
+
267
+ For validation, the run logs both lists:
268
+
269
+ ```text
270
+ 🔎 Filter regex: /src\/__tests__\/login/
271
+ All test files before filter (5):
272
+ - src/__tests__/login.spec.js
273
+ - src/checkout/checkout.spec.js
274
+ ...
275
+ Test files after filter (1):
276
+ - src/__tests__/login.spec.js
277
+ ```
278
+
279
+ If the filter matches nothing, no tests are run and the tool exits 0 with
280
+ that log block, so you can see the candidate list and adjust the pattern.
281
+
282
+ In `full` mode the filter is also forwarded to Jest as
283
+ `--testPathPatterns`, since Jest discovers the related specs itself. If you
284
+ already set a Jest path pattern via `--jest --testPathPatterns=...`, your own
285
+ pattern wins.
286
+
287
+ To make the filter the default for a repo, save it with the `config`
288
+ subcommand:
289
+
290
+ ```sh
291
+ mo3ta-coverage config --filter "src/__tests__/login"
292
+ # written to .mo3ta-coverage.json as "filter": "src/__tests__/login"
293
+ ```
294
+
295
+ A `--filter` value on the command line overrides the saved one.
296
+
206
297
  ## CI Mode
207
298
 
208
299
  Pass `--ci true` to print the coverage results as a markdown table **and**
@@ -309,7 +400,92 @@ You can persist defaults with the `config` subcommand:
309
400
  mo3ta-coverage config --base origin/main --mode smart --depth 2
310
401
  ```
311
402
 
312
- This writes `.mo3ta-coverage.json` in the project root.
403
+ This writes `.mo3ta-coverage.json` in the project root. The `base`, `mode`,
404
+ `depth`, `jest` (extra Jest flags), and `filter` (spec filter regex) defaults
405
+ are supported. For example, `mo3ta-coverage config --jest --maxWorkers=2`
406
+ saves a default Jest worker cap, and
407
+ `mo3ta-coverage config --filter "src/__tests__/login"` saves a default spec
408
+ filter.
409
+
410
+ ## MCP server
411
+
412
+ `mo3ta-coverage` also ships an [MCP](https://modelcontextprotocol.io) server so an agent working in a local checkout can list the changed files, see which tests would run, and read the uncovered changed lines it should write tests for. The server calls the same functions as the CLI. It does not reimplement git diffs, test mapping, or lcov parsing.
413
+
414
+ The server is a second bin in this package, `mo3ta-coverage-mcp`, speaking MCP over stdio. It lives here rather than in a separate package so one publish ships it, and so it imports this repo's source directly. The CLI flags, stdout, and exit codes are unchanged; the [GitHub Action](https://github.com/MahmoudMabrok/mo3ta-coverage-action) keeps running `node index.js`.
415
+
416
+ The server requires Node.js 18 or newer. Each tool takes `root` (the checkout to inspect). When `root` is omitted, Claude Code's `CLAUDE_PROJECT_DIR` is used if it is set, otherwise the server process cwd. `useConfig` defaults to true: `base`, `mode`, `depth`, `jest`, and `filter` are read from `.mo3ta-coverage.json` when present, and explicit arguments override the file.
417
+
418
+ | Tool | Purpose |
419
+ | --- | --- |
420
+ | `list_changed_files` | List JS/TS files changed versus a base ref (or an explicit list). |
421
+ | `map_related_tests` | Map those files to the tests `fast`, `smart`, or `full` mode would run. |
422
+ | `check_changed_line_coverage` | Run the changed-line coverage check and return uncovered lines with source text. |
423
+
424
+ `check_changed_line_coverage` runs the repo's local Jest and writes `coverage/` there, same as the CLI. Jest is killed after `timeoutMs` (default 5 minutes) and only a tail of its output is returned. Pass `runTests: false` to grade an existing `lcov.info` without running tests. Pass `jest` (an array of flags or a comma-separated string, e.g. `["--maxWorkers=4"]`) to forward extra Jest CLI flags, and `filter` (a regex) to narrow the final list of selected spec files. A missed threshold comes back as data (`ok: false` plus the uncovered lines), not a crashed tool. A missing git repo, a bad base ref, a missing Jest install, or a timeout comes back as a tool error with a `code` and a hint.
425
+
426
+ When a `filter` is used, results include `allTestsToRun` (the selected specs before the filter) and `testsToRun` (what matched), so an agent can validate that the regex kept what it expected.
427
+
428
+ `full` mode still delegates discovery to `jest --findRelatedTests`. `map_related_tests` can only list the changed test files until a check actually runs Jest, matching `--dryRun`.
429
+
430
+ ### Run it
431
+
432
+ From a checkout, after `npm install`:
433
+
434
+ ```sh
435
+ node mcp/server.js
436
+ # or
437
+ npx --package . -- mo3ta-coverage-mcp
438
+ ```
439
+
440
+ Once this package is published, any project can start it without cloning the repo:
441
+
442
+ ```sh
443
+ npx -y --package mo3ta-coverage mo3ta-coverage-mcp
444
+ ```
445
+
446
+ The bin name and the package name differ, so `npx` needs `--package mo3ta-coverage` to install this package and then run the `mo3ta-coverage-mcp` binary.
447
+
448
+ ### Claude Desktop
449
+
450
+ Add this to `claude_desktop_config.json` (`~/Library/Application Support/Claude/` on macOS, `%APPDATA%\Claude\` on Windows):
451
+
452
+ ```json
453
+ {
454
+ "mcpServers": {
455
+ "mo3ta-coverage": {
456
+ "command": "npx",
457
+ "args": ["-y", "--package", "mo3ta-coverage", "mo3ta-coverage-mcp"]
458
+ }
459
+ }
460
+ }
461
+ ```
462
+
463
+ ### Cursor
464
+
465
+ Add this to `.cursor/mcp.json` in the project, or to Cursor's user MCP config:
466
+
467
+ ```json
468
+ {
469
+ "mcpServers": {
470
+ "mo3ta-coverage": {
471
+ "command": "npx",
472
+ "args": ["-y", "--package", "mo3ta-coverage", "mo3ta-coverage-mcp"]
473
+ }
474
+ }
475
+ }
476
+ ```
477
+
478
+ ### Claude Code
479
+
480
+ ```sh
481
+ claude mcp add mo3ta-coverage -- npx -y --package mo3ta-coverage mo3ta-coverage-mcp
482
+ ```
483
+
484
+ From a local checkout of this repo, point the command at the script instead:
485
+
486
+ ```sh
487
+ claude mcp add mo3ta-coverage -- node /absolute/path/to/mo3ta-coverage/mcp/server.js
488
+ ```
313
489
 
314
490
  ## How It Works
315
491
 
@@ -325,7 +501,8 @@ This writes `.mo3ta-coverage.json` in the project root.
325
501
 
326
502
  ```sh
327
503
  npm install
328
- npm test
504
+ npm test # Jest, then the MCP server tests (node --test)
505
+ node mcp/server.js
329
506
  ```
330
507
 
331
508
  ## Security & dependencies
package/index.js CHANGED
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
 
4
- import { Command } from 'commander';
4
+ import { Command, Option } from 'commander';
5
5
  import { main } from './src/cli.js';
6
6
  import fs from 'fs';
7
7
  import path from 'path';
@@ -15,7 +15,13 @@ function readConfig(quiet = false) {
15
15
  }
16
16
 
17
17
  if (fs.existsSync(CONFIG_PATH)) {
18
- return JSON.parse(fs.readFileSync(CONFIG_PATH, 'utf8'));
18
+ const raw = fs.readFileSync(CONFIG_PATH, 'utf8');
19
+ try {
20
+ return JSON.parse(raw);
21
+ } catch (error) {
22
+ console.error(`❌ Could not parse ${CONFIG_PATH}: ${error.message}`);
23
+ process.exit(1);
24
+ }
19
25
  }
20
26
  return {};
21
27
  }
@@ -25,6 +31,14 @@ function writeConfig(config) {
25
31
  console.log(`Updated config: ${JSON.stringify(config, null, 2)}`);
26
32
  }
27
33
 
34
+ // commander accumulator for the repeatable `--jest` option: each occurrence is
35
+ // appended, and a comma within one value splits it into separate flags. The
36
+ // result stays in the order the user typed the flags.
37
+ function collectJest(value, previous) {
38
+ const list = Array.isArray(previous) && previous.length > 0 ? previous : [];
39
+ return list.concat(String(value).split(',').map(flag => flag.trim()).filter(Boolean));
40
+ }
41
+
28
42
  const program = new Command();
29
43
 
30
44
  const PkgPath = new URL('./package.json', import.meta.url);
@@ -46,7 +60,9 @@ program
46
60
  .option('--depth <number>', 'Smart mode max reverse-dependency depth (1 = direct importers, 2 = also importers of importers)', '2')
47
61
  .option('--files <files...>', 'Scan only these files instead of detecting changed files (space- or comma-separated)')
48
62
  .option('--filesFrom <path>', 'Read the list of files to scan from a newline-separated file')
63
+ .addOption(new Option('--jest <value>', 'Extra Jest CLI flag, e.g. --maxWorkers=2 (repeatable or comma-separated)').argParser(collectJest))
49
64
  .option('--dryRun <bool>', 'Print the test files that would run (one per line) and exit, without running Jest or the coverage check', false)
65
+ .option('--filter <regex>', 'Regex matched against the final list of selected spec files; only matching test files run. The full list and the filtered list are both printed so you can validate the filter.')
50
66
  .enablePositionalOptions(); // used to allow using same options in subcommands
51
67
 
52
68
  // Usage help text (printed next to --help)
@@ -56,9 +72,11 @@ Examples:
56
72
  $ mo3ta-coverage --mode smart --base origin/main --limit 80
57
73
  $ mo3ta-coverage --files src/a.js,src/b.ts --base origin/main
58
74
  $ mo3ta-coverage --filesFrom changed.txt --base origin/main
59
- $ mo3ta-coverage --dry-run true --files src/a.js,src/b.ts --base main
75
+ $ mo3ta-coverage --dryRun true --files src/a.js,src/b.ts --base main
60
76
  $ mo3ta-coverage --mode fast --showCovered true
61
77
  $ mo3ta-coverage --mode smart --base origin/main --ci true --ciReport coverage/report.md
78
+ $ mo3ta-coverage --base origin/main --jest --maxWorkers=2 --jest --silent
79
+ $ mo3ta-coverage --base origin/main --filter "src/__tests__/login"
62
80
  $ mo3ta-coverage config --mode smart --depth 2
63
81
  $ mo3ta-coverage --version
64
82
 
@@ -70,12 +88,14 @@ Modes:
70
88
  See README.md for details: https://github.com/MahmoudMabrok/mo3ta-coverage`);
71
89
 
72
90
 
73
- program
91
+ const configCommand = program
74
92
  .command('config')
75
93
  .description('Set or get configuration options')
76
94
  .option('--base <branch>', 'Set default base branch')
77
95
  .option('--mode <mode>', 'Set default mode (fast/smart/full)')
78
96
  .option('--depth <number>', 'Set default smart-mode depth (1-10)')
97
+ .addOption(new Option('--jest <value>', 'Set default extra Jest CLI flag, e.g. --maxWorkers=2 (repeatable or comma-separated)').argParser(collectJest))
98
+ .option('--filter <regex>', 'Set default spec filter regex matched against the final selected spec files')
79
99
  .action((opts) => {
80
100
  let config = readConfig();
81
101
 
@@ -83,7 +103,7 @@ program
83
103
 
84
104
  if (opts.base) {
85
105
  verifyBaseBranchExists(opts.base);
86
-
106
+
87
107
  config.base = opts.base;
88
108
  updated = true;
89
109
  console.log(`Default base branch set to: ${opts.base}`);
@@ -110,6 +130,18 @@ program
110
130
  updated = true;
111
131
  console.log(`Default smart-mode depth set to: ${config.depth}`);
112
132
  }
133
+
134
+ if (configCommand.getOptionValueSource('filter') === 'cli') {
135
+ config.filter = opts.filter;
136
+ updated = true;
137
+ console.log(`Default spec filter set to: ${opts.filter}`);
138
+ }
139
+
140
+ if (configCommand.getOptionValueSource('jest') === 'cli') {
141
+ config.jest = opts.jest;
142
+ updated = true;
143
+ console.log(`Default Jest flags set to: ${opts.jest.join(' ')}`);
144
+ }
113
145
  if (updated) {
114
146
  writeConfig(config);
115
147
  } else {
@@ -127,7 +159,8 @@ program.action((opts) => {
127
159
 
128
160
  const modeFromCli = program.getOptionValueSource('mode') === 'cli';
129
161
  const depthFromCli = program.getOptionValueSource('depth') === 'cli';
130
-
162
+ const jestFromCli = program.getOptionValueSource('jest') === 'cli';
163
+
131
164
  // Use config base if not provided in CLI
132
165
  if (!options.base && config.base) {
133
166
  options.base = config.base;
@@ -139,6 +172,14 @@ program.action((opts) => {
139
172
  options.mode = config.mode;
140
173
  }
141
174
 
175
+ if (!jestFromCli && config.jest !== undefined && config.jest !== null) {
176
+ options.jest = config.jest;
177
+ }
178
+
179
+ if (!options.filter && config.filter) {
180
+ options.filter = config.filter;
181
+ }
182
+
142
183
  options.mode = String(options.mode || 'smart').toLowerCase();
143
184
  if (!['fast', 'smart', 'full'].includes(options.mode)) {
144
185
  console.error(`Invalid mode: ${options.mode}. Expected one of: fast, smart, full.`);
@@ -0,0 +1,179 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import { z } from 'zod';
3
+ import {
4
+ checkChangedLineCoverage,
5
+ listChangedFiles,
6
+ mapRelatedTests
7
+ } from '../src/api.js';
8
+
9
+ const rootField = z.string().optional().describe(
10
+ 'Path to the git checkout to inspect. Defaults to CLAUDE_PROJECT_DIR when Claude Code sets it, otherwise the MCP server process cwd.'
11
+ );
12
+ const baseField = z.string().optional().describe(
13
+ 'Git ref to compare against (branch, tag, or commit). Defaults to .mo3ta-coverage.json "base" when useConfig is true, otherwise origin/main.'
14
+ );
15
+ const filesField = z.union([z.array(z.string()), z.string()]).optional().describe(
16
+ 'Scan these repo-relative paths instead of git changed-file detection. A comma-separated string or an array. An empty list does not fall back to git.'
17
+ );
18
+ const filesFromField = z.string().optional().describe(
19
+ 'Newline-separated file list to scan, relative to root (for example the output of git diff --name-only).'
20
+ );
21
+ const modeField = z.string().optional().describe(
22
+ 'Test selection mode: fast (filename plus a direct import scan), smart (filename plus a reverse-import walk, default), or full (jest --findRelatedTests).'
23
+ );
24
+ const depthField = z.union([z.number(), z.string()]).optional().describe(
25
+ 'Smart-mode reverse-import depth, an integer from 1 to 10. 1 = tests that import the file. 2 (default) = also one intermediate module.'
26
+ );
27
+ const jestArgsField = z.union([z.array(z.string()), z.string()]).optional().describe(
28
+ 'Extra Jest CLI flags to pass through, e.g. ["--maxWorkers=4","--silent"] or "--maxWorkers=4,--silent". Appended to the tool\'s own Jest arguments.'
29
+ );
30
+ const filterField = z.string().optional().describe(
31
+ 'Regular expression matched against the final list of selected spec files; only matching test paths run. Example: "src/__tests__/login". Reads "filter" from .mo3ta-coverage.json when not passed explicitly.'
32
+ );
33
+ const useConfigField = z.boolean().optional().describe(
34
+ 'Read base, mode, depth, jest, and filter defaults from .mo3ta-coverage.json in the repo. Default true. Explicit arguments override the file. Set false to ignore a broken config.'
35
+ );
36
+
37
+ const INSTRUCTIONS = [
38
+ 'mo3ta-coverage checks coverage of lines changed versus a base ref.',
39
+ 'Use list_changed_files to see changed JS/TS files, map_related_tests to see which tests would run, and check_changed_line_coverage to get the uncovered changed lines to write tests for.',
40
+ 'check_changed_line_coverage runs the repo\'s local Jest and writes coverage/ in that repo. Pass runTests: false to read an existing lcov file instead.',
41
+ 'Pass a filter (a regex) to map_related_tests or check_changed_line_coverage to narrow the final list of selected spec files to the matching paths. The result includes allTestsToRun (before the filter) and testsToRun (after) so you can validate the match.',
42
+ 'A result with ok: false and uncovered lines is a coverage gap, not a crashed tool. Operational problems (not a git repo, bad base ref, Jest missing) come back as tool errors with a code and a hint.'
43
+ ].join(' ');
44
+
45
+ function toolResult(data, { isError = false } = {}) {
46
+ const payload = JSON.parse(JSON.stringify(data));
47
+ const summary = payload.summary || payload.message || '';
48
+ return {
49
+ isError,
50
+ content: [{ type: 'text', text: `${summary}\n\n${JSON.stringify(payload, null, 2)}` }],
51
+ structuredContent: payload
52
+ };
53
+ }
54
+
55
+ function errorResult(error) {
56
+ const data = {
57
+ ok: false,
58
+ code: error.code || 'UNEXPECTED',
59
+ message: error.message || String(error)
60
+ };
61
+ if (error.hint) data.hint = error.hint;
62
+ if (error.jest) data.jest = error.jest;
63
+ const summary = [data.message, data.hint].filter(Boolean).join('\n');
64
+ return toolResult({ ...data, summary }, { isError: true });
65
+ }
66
+
67
+ function run(fn, args) {
68
+ try {
69
+ return toolResult(fn(args || {}));
70
+ } catch (error) {
71
+ return errorResult(error);
72
+ }
73
+ }
74
+
75
+ /**
76
+ * MCP server that exposes mo3ta-coverage as tools. Does not connect a transport.
77
+ * @param {{version?: string}} [options]
78
+ */
79
+ export function createServer({ version = '0.0.0' } = {}) {
80
+ const server = new McpServer({
81
+ name: 'mo3ta-coverage',
82
+ version
83
+ }, {
84
+ instructions: INSTRUCTIONS
85
+ });
86
+
87
+ server.registerTool(
88
+ 'list_changed_files',
89
+ {
90
+ title: 'List changed files',
91
+ description: 'List JavaScript and TypeScript files changed versus a base ref (every author since the merge base, plus staged and unstaged edits). Pass files or filesFrom to scan an explicit list instead. Does not run tests.',
92
+ annotations: {
93
+ readOnlyHint: true,
94
+ destructiveHint: false,
95
+ idempotentHint: true,
96
+ openWorldHint: false
97
+ },
98
+ inputSchema: {
99
+ root: rootField,
100
+ base: baseField,
101
+ files: filesField,
102
+ filesFrom: filesFromField,
103
+ useConfig: useConfigField
104
+ }
105
+ },
106
+ async args => run(listChangedFiles, args)
107
+ );
108
+
109
+ server.registerTool(
110
+ 'map_related_tests',
111
+ {
112
+ title: 'Map related tests',
113
+ description: 'Map changed source files to the test files fast, smart, or full mode would run. smart (default) uses filenames plus a depth-limited reverse-import walk. full cannot list Jest\'s expanded set until tests actually run. Pass filter (a regex) to narrow the selected spec files to matching paths. Does not run Jest or read coverage.',
114
+ annotations: {
115
+ readOnlyHint: true,
116
+ destructiveHint: false,
117
+ idempotentHint: true,
118
+ openWorldHint: false
119
+ },
120
+ inputSchema: {
121
+ root: rootField,
122
+ base: baseField,
123
+ files: filesField,
124
+ filesFrom: filesFromField,
125
+ mode: modeField,
126
+ depth: depthField,
127
+ filter: filterField,
128
+ useConfig: useConfigField
129
+ }
130
+ },
131
+ async args => run(mapRelatedTests, args)
132
+ );
133
+
134
+ server.registerTool(
135
+ 'check_changed_line_coverage',
136
+ {
137
+ title: 'Check changed-line coverage',
138
+ description: 'Run the changed-line coverage check. By default runs the repo\'s local Jest (writes coverage/ in that repo) and returns per-file uncovered changed lines with source text so you can add tests. Set runTests false to grade an existing lcov file. ok false with uncovered lines means the threshold was missed. Timeout defaults to 5 minutes (timeoutMs).',
139
+ annotations: {
140
+ readOnlyHint: false,
141
+ destructiveHint: false,
142
+ idempotentHint: true,
143
+ openWorldHint: false
144
+ },
145
+ inputSchema: {
146
+ root: rootField,
147
+ base: baseField,
148
+ files: filesField,
149
+ filesFrom: filesFromField,
150
+ mode: modeField,
151
+ depth: depthField,
152
+ limit: z.union([z.number(), z.string()]).optional().describe(
153
+ 'Minimum percent of changed, coverable lines that must be covered. Default 80. Range 0 to 100.'
154
+ ),
155
+ lcov: z.string().optional().describe(
156
+ 'Path to lcov.info, relative to root or absolute. Default coverage/lcov.info.'
157
+ ),
158
+ runTests: z.boolean().optional().describe(
159
+ 'Run Jest before reading lcov. Default true. Set false to grade an existing report without running tests.'
160
+ ),
161
+ showCovered: z.boolean().optional().describe(
162
+ 'Also return covered changed line numbers. Uncovered lines are always returned. Default false.'
163
+ ),
164
+ timeoutMs: z.union([z.number(), z.string()]).optional().describe(
165
+ 'Kill Jest after this many milliseconds. Default 300000 (5 minutes). Range 1000 to 1800000.'
166
+ ),
167
+ ciReport: z.string().optional().describe(
168
+ 'Also write the CLI markdown table to this path (relative to root). Omitted by default so the tool does not create a report file.'
169
+ ),
170
+ jest: jestArgsField,
171
+ filter: filterField,
172
+ useConfig: useConfigField
173
+ }
174
+ },
175
+ async args => run(checkChangedLineCoverage, args)
176
+ );
177
+
178
+ return server;
179
+ }
package/mcp/server.js ADDED
@@ -0,0 +1,18 @@
1
+ #!/usr/bin/env node
2
+
3
+ const major = Number(process.versions.node.split('.')[0]);
4
+ if (!Number.isInteger(major) || major < 18) {
5
+ console.error(`mo3ta-coverage-mcp requires Node.js 18 or newer. This process is Node ${process.versions.node}.`);
6
+ process.exit(1);
7
+ }
8
+
9
+ const { createServer } = await import('./createServer.js');
10
+ const { StdioServerTransport } = await import('@modelcontextprotocol/sdk/server/stdio.js');
11
+ const { readFileSync } = await import('node:fs');
12
+
13
+ const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
14
+ const server = createServer({ version: pkg.version });
15
+
16
+ // stdout is the MCP JSON-RPC stream. Diagnostics stay on stderr.
17
+ console.error(`mo3ta-coverage MCP server ${pkg.version} listening on stdio`);
18
+ await server.connect(new StdioServerTransport());