@mandujs/mcp 0.38.12 → 0.39.0-beta.1

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.
Files changed (183) hide show
  1. package/README.md +3 -3
  2. package/package.json +3 -5
  3. package/src/activity-adapter.ts +23 -23
  4. package/src/activity-monitor.ts +39 -10
  5. package/src/adapters/index.ts +20 -20
  6. package/src/adapters/monitor-adapter.ts +100 -100
  7. package/src/adapters/tool-adapter.ts +90 -90
  8. package/src/executor/index.ts +22 -22
  9. package/src/executor/tool-executor.ts +148 -148
  10. package/src/hooks/config-watcher.ts +173 -173
  11. package/src/hooks/index.ts +23 -23
  12. package/src/hooks/mcp-hooks.ts +227 -227
  13. package/src/index.ts +5 -5
  14. package/src/logging/index.ts +15 -15
  15. package/src/logging/mcp-transport.ts +134 -134
  16. package/src/new-resources.ts +2 -2
  17. package/src/profiles.ts +25 -54
  18. package/src/prompts.ts +4 -4
  19. package/src/registry/index.ts +13 -13
  20. package/src/registry/mcp-tool-registry.ts +298 -298
  21. package/src/resources/generated-skills/catalog.ts +36 -0
  22. package/src/resources/generated-skills/mandu-agent-workflow/SKILL.md +48 -0
  23. package/src/resources/generated-skills/mandu-contract/SKILL.md +20 -0
  24. package/src/resources/generated-skills/mandu-fs-routes/SKILL.md +19 -0
  25. package/src/resources/generated-skills/mandu-guard/SKILL.md +20 -0
  26. package/src/resources/generated-skills/mandu-hydration/SKILL.md +19 -0
  27. package/src/resources/generated-skills/mandu-testing/SKILL.md +20 -0
  28. package/src/resources/handlers.ts +3 -3
  29. package/src/resources/skills/guides.ts +49 -49
  30. package/src/resources/skills/index.ts +12 -12
  31. package/src/resources/skills/loader.ts +8 -35
  32. package/src/resources/skills/recipes.ts +28 -28
  33. package/src/server.ts +1 -1
  34. package/src/tools/agent.ts +479 -409
  35. package/src/tools/ate-exemplar.ts +92 -92
  36. package/src/tools/ate-flakes.ts +90 -90
  37. package/src/tools/ate-mutate.ts +103 -103
  38. package/src/tools/ate-mutation-report.ts +64 -64
  39. package/src/tools/ate-oracle-pending.ts +49 -49
  40. package/src/tools/ate-oracle-replay.ts +44 -44
  41. package/src/tools/ate-oracle-verdict.ts +70 -70
  42. package/src/tools/ate-prompt.ts +146 -146
  43. package/src/tools/ate-run.ts +1 -1
  44. package/src/tools/ate.ts +38 -38
  45. package/src/tools/brain.ts +6 -6
  46. package/src/tools/composite.ts +19 -61
  47. package/src/tools/contract.ts +11 -9
  48. package/src/tools/deploy-plan.ts +2 -2
  49. package/src/tools/deploy-preview.ts +316 -316
  50. package/src/tools/design.ts +825 -825
  51. package/src/tools/docs.ts +350 -350
  52. package/src/tools/generate.ts +4 -3
  53. package/src/tools/guard.ts +1 -1
  54. package/src/tools/history.ts +1 -1
  55. package/src/tools/hydration.ts +64 -64
  56. package/src/tools/index.ts +0 -118
  57. package/src/tools/kitchen.ts +72 -72
  58. package/src/tools/lint.ts +226 -226
  59. package/src/tools/loop-close.ts +175 -175
  60. package/src/tools/negotiate.ts +263 -263
  61. package/src/tools/resource.ts +1 -1
  62. package/src/tools/run-tests.ts +424 -424
  63. package/src/tools/runtime.ts +1 -1
  64. package/src/tools/seo.ts +1 -1
  65. package/src/tools/slot-validation.ts +19 -19
  66. package/src/tools/spec.ts +201 -201
  67. package/src/tools/transaction.ts +1 -1
  68. package/src/tx-lock.ts +73 -73
  69. package/src/utils/runtime-control.ts +52 -52
  70. package/src/utils/withWarnings.ts +1 -1
  71. package/src/resources/skills/mandu-agent-workflow/SKILL.md +0 -124
  72. package/src/resources/skills/mandu-agent-workflow/metadata.json +0 -7
  73. package/src/resources/skills/mandu-composition/SKILL.md +0 -131
  74. package/src/resources/skills/mandu-composition/metadata.json +0 -13
  75. package/src/resources/skills/mandu-composition/rules/_sections.md +0 -26
  76. package/src/resources/skills/mandu-composition/rules/_template.md +0 -77
  77. package/src/resources/skills/mandu-composition/rules/comp-arch-avoid-boolean-props.md +0 -146
  78. package/src/resources/skills/mandu-composition/rules/comp-arch-compound-components.md +0 -164
  79. package/src/resources/skills/mandu-composition/rules/comp-island-event.md +0 -161
  80. package/src/resources/skills/mandu-composition/rules/comp-island-slot-split.md +0 -167
  81. package/src/resources/skills/mandu-composition/rules/comp-pattern-children.md +0 -149
  82. package/src/resources/skills/mandu-composition/rules/comp-state-context-interface.md +0 -148
  83. package/src/resources/skills/mandu-composition/rules/comp-state-lift-state.md +0 -150
  84. package/src/resources/skills/mandu-deployment/SKILL.md +0 -135
  85. package/src/resources/skills/mandu-deployment/_sections.md +0 -41
  86. package/src/resources/skills/mandu-deployment/_template.md +0 -38
  87. package/src/resources/skills/mandu-deployment/metadata.json +0 -13
  88. package/src/resources/skills/mandu-deployment/rules/db-provider-supabase.md +0 -300
  89. package/src/resources/skills/mandu-deployment/rules/deploy-build-bun.md +0 -109
  90. package/src/resources/skills/mandu-deployment/rules/deploy-build-output.md +0 -115
  91. package/src/resources/skills/mandu-deployment/rules/deploy-cicd-github.md +0 -219
  92. package/src/resources/skills/mandu-deployment/rules/deploy-docker-bun.md +0 -150
  93. package/src/resources/skills/mandu-deployment/rules/deploy-docker-compose.md +0 -223
  94. package/src/resources/skills/mandu-deployment/rules/deploy-platform-fly.md +0 -152
  95. package/src/resources/skills/mandu-deployment/rules/deploy-platform-render.md +0 -179
  96. package/src/resources/skills/mandu-deployment/rules/deploy-platform-vercel.md +0 -140
  97. package/src/resources/skills/mandu-fs-routes/SKILL.md +0 -122
  98. package/src/resources/skills/mandu-fs-routes/metadata.json +0 -12
  99. package/src/resources/skills/mandu-fs-routes/rules/_sections.md +0 -36
  100. package/src/resources/skills/mandu-fs-routes/rules/_template.md +0 -69
  101. package/src/resources/skills/mandu-fs-routes/rules/routes-api-methods.md +0 -65
  102. package/src/resources/skills/mandu-fs-routes/rules/routes-dynamic-param.md +0 -93
  103. package/src/resources/skills/mandu-fs-routes/rules/routes-naming-page.md +0 -55
  104. package/src/resources/skills/mandu-guard/SKILL.md +0 -162
  105. package/src/resources/skills/mandu-guard/metadata.json +0 -12
  106. package/src/resources/skills/mandu-guard/rules/_sections.md +0 -36
  107. package/src/resources/skills/mandu-guard/rules/_template.md +0 -82
  108. package/src/resources/skills/mandu-guard/rules/guard-config-rules.md +0 -100
  109. package/src/resources/skills/mandu-guard/rules/guard-layer-direction.md +0 -76
  110. package/src/resources/skills/mandu-guard/rules/guard-preset-mandu.md +0 -81
  111. package/src/resources/skills/mandu-guard/rules/guard-validate-import.md +0 -80
  112. package/src/resources/skills/mandu-hydration/SKILL.md +0 -139
  113. package/src/resources/skills/mandu-hydration/metadata.json +0 -12
  114. package/src/resources/skills/mandu-hydration/rules/_sections.md +0 -31
  115. package/src/resources/skills/mandu-hydration/rules/_template.md +0 -72
  116. package/src/resources/skills/mandu-hydration/rules/hydration-data-event.md +0 -109
  117. package/src/resources/skills/mandu-hydration/rules/hydration-directive-use-client.md +0 -55
  118. package/src/resources/skills/mandu-hydration/rules/hydration-island-setup.md +0 -160
  119. package/src/resources/skills/mandu-hydration/rules/hydration-priority-visible.md +0 -91
  120. package/src/resources/skills/mandu-performance/SKILL.md +0 -125
  121. package/src/resources/skills/mandu-performance/metadata.json +0 -14
  122. package/src/resources/skills/mandu-performance/rules/_sections.md +0 -31
  123. package/src/resources/skills/mandu-performance/rules/_template.md +0 -64
  124. package/src/resources/skills/mandu-performance/rules/perf-async-defer-await.md +0 -103
  125. package/src/resources/skills/mandu-performance/rules/perf-async-parallel.md +0 -95
  126. package/src/resources/skills/mandu-performance/rules/perf-bun-file.md +0 -124
  127. package/src/resources/skills/mandu-performance/rules/perf-bun-serve.md +0 -125
  128. package/src/resources/skills/mandu-performance/rules/perf-bundle-imports.md +0 -80
  129. package/src/resources/skills/mandu-performance/rules/perf-bundle-island-lazy.md +0 -145
  130. package/src/resources/skills/mandu-performance/rules/perf-cache-react.md +0 -98
  131. package/src/resources/skills/mandu-performance/rules/perf-render-transitions.md +0 -154
  132. package/src/resources/skills/mandu-security/SKILL.md +0 -127
  133. package/src/resources/skills/mandu-security/metadata.json +0 -13
  134. package/src/resources/skills/mandu-security/rules/_sections.md +0 -31
  135. package/src/resources/skills/mandu-security/rules/_template.md +0 -74
  136. package/src/resources/skills/mandu-security/rules/sec-auth-guard.md +0 -127
  137. package/src/resources/skills/mandu-security/rules/sec-env-management.md +0 -133
  138. package/src/resources/skills/mandu-security/rules/sec-input-validate.md +0 -148
  139. package/src/resources/skills/mandu-security/rules/sec-protect-csrf.md +0 -146
  140. package/src/resources/skills/mandu-security/rules/sec-protect-headers.md +0 -138
  141. package/src/resources/skills/mandu-slot/SKILL.md +0 -125
  142. package/src/resources/skills/mandu-slot/metadata.json +0 -12
  143. package/src/resources/skills/mandu-slot/rules/_sections.md +0 -36
  144. package/src/resources/skills/mandu-slot/rules/_template.md +0 -63
  145. package/src/resources/skills/mandu-slot/rules/slot-basic-structure.md +0 -38
  146. package/src/resources/skills/mandu-slot/rules/slot-ctx-response.md +0 -56
  147. package/src/resources/skills/mandu-slot/rules/slot-guard-auth.md +0 -59
  148. package/src/resources/skills/mandu-slot/rules/slot-http-methods.md +0 -64
  149. package/src/resources/skills/mandu-styling/SKILL.md +0 -196
  150. package/src/resources/skills/mandu-styling/_sections.md +0 -43
  151. package/src/resources/skills/mandu-styling/_template.md +0 -32
  152. package/src/resources/skills/mandu-styling/metadata.json +0 -15
  153. package/src/resources/skills/mandu-styling/rules/style-component-compound.md +0 -235
  154. package/src/resources/skills/mandu-styling/rules/style-component-slots.md +0 -255
  155. package/src/resources/skills/mandu-styling/rules/style-component-tokens.md +0 -205
  156. package/src/resources/skills/mandu-styling/rules/style-island-animations.md +0 -272
  157. package/src/resources/skills/mandu-styling/rules/style-island-scoping.md +0 -167
  158. package/src/resources/skills/mandu-styling/rules/style-island-variants.md +0 -221
  159. package/src/resources/skills/mandu-styling/rules/style-perf-critical.md +0 -209
  160. package/src/resources/skills/mandu-styling/rules/style-perf-purge.md +0 -192
  161. package/src/resources/skills/mandu-styling/rules/style-setup-modules.md +0 -162
  162. package/src/resources/skills/mandu-styling/rules/style-setup-panda.md +0 -164
  163. package/src/resources/skills/mandu-styling/rules/style-setup-tailwind.md +0 -170
  164. package/src/resources/skills/mandu-styling/rules/style-tailwind-v4-gotchas.md +0 -179
  165. package/src/resources/skills/mandu-styling/rules/style-theme-darkmode.md +0 -229
  166. package/src/resources/skills/mandu-testing/SKILL.md +0 -132
  167. package/src/resources/skills/mandu-testing/metadata.json +0 -13
  168. package/src/resources/skills/mandu-testing/rules/_sections.md +0 -26
  169. package/src/resources/skills/mandu-testing/rules/_template.md +0 -65
  170. package/src/resources/skills/mandu-testing/rules/test-component-island.md +0 -195
  171. package/src/resources/skills/mandu-testing/rules/test-e2e-playwright.md +0 -196
  172. package/src/resources/skills/mandu-testing/rules/test-mock-fetch.md +0 -219
  173. package/src/resources/skills/mandu-testing/rules/test-slot-unit.md +0 -192
  174. package/src/resources/skills/mandu-ui/SKILL.md +0 -159
  175. package/src/resources/skills/mandu-ui/_sections.md +0 -23
  176. package/src/resources/skills/mandu-ui/_template.md +0 -32
  177. package/src/resources/skills/mandu-ui/metadata.json +0 -13
  178. package/src/resources/skills/mandu-ui/rules/ui-accessibility-aria.md +0 -232
  179. package/src/resources/skills/mandu-ui/rules/ui-accessibility-focus.md +0 -238
  180. package/src/resources/skills/mandu-ui/rules/ui-composition-patterns.md +0 -259
  181. package/src/resources/skills/mandu-ui/rules/ui-island-integration.md +0 -258
  182. package/src/resources/skills/mandu-ui/rules/ui-radix-patterns.md +0 -213
  183. package/src/resources/skills/mandu-ui/rules/ui-shadcn-setup.md +0 -209
@@ -1,424 +1,424 @@
1
- /**
2
- * MCP tool — `mandu.run.tests`
3
- *
4
- * Invokes `mandu test` as a child process via `Bun.spawn` and parses the
5
- * resulting Bun test output into a structured summary:
6
- *
7
- * { passed, failed, skipped, failing_tests: [{ name, file, error }] }
8
- *
9
- * Design notes:
10
- * • Input is validated against a minimal runtime schema (see `validateInput`).
11
- * Bad input produces a structured `{ error, field, hint }` object — the
12
- * error-handler's `isSoftErrorResult` detector will surface this as
13
- * `isError: true` to MCP clients.
14
- * • If no test files are discovered we return `{ passed: 0, failed: 0,
15
- * skipped: 0, note: "no test files" }` without failing the caller.
16
- * • The child process is spawned with a 10-minute ceiling via Promise.race —
17
- * well above normal test suites but short enough that a stuck process
18
- * never hangs the MCP server.
19
- */
20
-
21
- import type { Tool } from "@modelcontextprotocol/sdk/types.js";
22
- import { spawn } from "bun";
23
- import path from "path";
24
-
25
- // ─────────────────────────────────────────────────────────────────────────
26
- // Types
27
- // ─────────────────────────────────────────────────────────────────────────
28
-
29
- type RunTarget = "unit" | "integration" | "e2e" | "all";
30
-
31
- interface RunTestsInput {
32
- target?: RunTarget;
33
- filter?: string;
34
- coverage?: boolean;
35
- }
36
-
37
- interface FailingTest {
38
- name: string;
39
- file?: string;
40
- error?: string;
41
- }
42
-
43
- interface RunTestsResult {
44
- target: RunTarget;
45
- passed: number;
46
- failed: number;
47
- skipped: number;
48
- duration_ms?: number;
49
- failing_tests: FailingTest[];
50
- exit_code: number;
51
- note?: string;
52
- /** Trailing 2000 chars of stdout for diagnostic context. */
53
- stdout_tail?: string;
54
- /** Trailing 2000 chars of stderr for diagnostic context. */
55
- stderr_tail?: string;
56
- }
57
-
58
- // ─────────────────────────────────────────────────────────────────────────
59
- // Validation
60
- // ─────────────────────────────────────────────────────────────────────────
61
-
62
- const VALID_TARGETS = new Set<RunTarget>(["unit", "integration", "e2e", "all"]);
63
- const COMMAND_TIMEOUT_MS = 10 * 60_000;
64
-
65
- function validateInput(raw: Record<string, unknown>): {
66
- ok: true;
67
- value: Required<Pick<RunTestsInput, "target" | "coverage">> &
68
- Pick<RunTestsInput, "filter">;
69
- } | { ok: false; error: string; field: string; hint: string } {
70
- const target = raw.target ?? "all";
71
- if (typeof target !== "string" || !VALID_TARGETS.has(target as RunTarget)) {
72
- return {
73
- ok: false,
74
- error: "Invalid 'target' — expected 'unit', 'integration', 'e2e', or 'all'",
75
- field: "target",
76
- hint: "Omit to default to 'all'",
77
- };
78
- }
79
-
80
- const filter = raw.filter;
81
- if (filter !== undefined && typeof filter !== "string") {
82
- return {
83
- ok: false,
84
- error: "'filter' must be a string",
85
- field: "filter",
86
- hint: "Pass a bun-test filter pattern, e.g. 'my-describe > my-case'",
87
- };
88
- }
89
-
90
- const coverage = raw.coverage;
91
- if (coverage !== undefined && typeof coverage !== "boolean") {
92
- return {
93
- ok: false,
94
- error: "'coverage' must be a boolean",
95
- field: "coverage",
96
- hint: "Pass true to emit a coverage report",
97
- };
98
- }
99
-
100
- return {
101
- ok: true,
102
- value: {
103
- target: target as RunTarget,
104
- coverage: coverage === true,
105
- ...(typeof filter === "string" && filter.length > 0 ? { filter } : {}),
106
- },
107
- };
108
- }
109
-
110
- // ─────────────────────────────────────────────────────────────────────────
111
- // Parser — Bun test output → RunTestsResult
112
- // ─────────────────────────────────────────────────────────────────────────
113
-
114
- /**
115
- * Parse bun-test style output. Bun emits:
116
- * `(pass) describe > test`
117
- * `(fail) describe > test`
118
- * `(skip) describe > test`
119
- *
120
- * And a trailing summary block:
121
- * `N pass`
122
- * `M fail`
123
- * `K skipped`
124
- * `Ran ... tests across ... files. [x.xxs]`
125
- *
126
- * This parser is intentionally forgiving: counts are taken from the
127
- * explicit summary lines when present, else derived from `(pass|fail|skip)`
128
- * markers.
129
- */
130
- export function parseBunTestOutput(raw: string): {
131
- passed: number;
132
- failed: number;
133
- skipped: number;
134
- duration_ms?: number;
135
- failing_tests: FailingTest[];
136
- } {
137
- const lines = raw.split(/\r?\n/);
138
- let passed = 0;
139
- let failed = 0;
140
- let skipped = 0;
141
- let duration_ms: number | undefined;
142
- const failing_tests: FailingTest[] = [];
143
-
144
- let currentFile: string | undefined;
145
- let pendingFailure: FailingTest | null = null;
146
-
147
- for (const line of lines) {
148
- const trimmed = line.trim();
149
-
150
- // Track the current file heading (e.g. "src/foo.test.ts:"):
151
- const fileMatch = /^([^\s()]+\.(?:test|spec)\.(?:ts|tsx|js|jsx|mjs|cjs)):$/.exec(trimmed);
152
- if (fileMatch) {
153
- currentFile = fileMatch[1];
154
- continue;
155
- }
156
-
157
- // `(fail) ...` → start a failing test record.
158
- const failMatch = /^\(fail\)\s+(.+)$/.exec(trimmed);
159
- if (failMatch) {
160
- if (pendingFailure) {
161
- failing_tests.push(pendingFailure);
162
- }
163
- pendingFailure = {
164
- name: failMatch[1].trim(),
165
- file: currentFile,
166
- };
167
- continue;
168
- }
169
-
170
- // `(skip) ...` counts as skipped but doesn't emit a record.
171
- if (/^\(skip\)\s+/.test(trimmed)) {
172
- continue;
173
- }
174
-
175
- // If we're inside a failure block, capture the first few non-empty
176
- // lines that follow as error context.
177
- if (pendingFailure && trimmed.length > 0) {
178
- const isNextTestMarker = /^\(pass|fail|skip\)/.test(trimmed);
179
- if (!isNextTestMarker) {
180
- pendingFailure.error = pendingFailure.error
181
- ? `${pendingFailure.error}\n${trimmed}`
182
- : trimmed;
183
- // Cap the captured error to keep payloads tight.
184
- if (pendingFailure.error.length > 800) {
185
- pendingFailure.error = pendingFailure.error.slice(0, 800);
186
- }
187
- continue;
188
- }
189
- }
190
-
191
- // End-of-block marker flushes the current failure record.
192
- if (pendingFailure && (trimmed.length === 0 || /^\d+\s+(pass|fail|skipped)\b/.test(trimmed))) {
193
- failing_tests.push(pendingFailure);
194
- pendingFailure = null;
195
- }
196
-
197
- // Totals block — authoritative if present.
198
- const passMatch = /^(\d+)\s+pass\b/.exec(trimmed);
199
- if (passMatch) {
200
- passed = Number(passMatch[1]);
201
- continue;
202
- }
203
- const failSumMatch = /^(\d+)\s+fail\b/.exec(trimmed);
204
- if (failSumMatch) {
205
- failed = Number(failSumMatch[1]);
206
- continue;
207
- }
208
- const skipMatch = /^(\d+)\s+skipped\b/.exec(trimmed);
209
- if (skipMatch) {
210
- skipped = Number(skipMatch[1]);
211
- continue;
212
- }
213
-
214
- // Duration: `Ran 123 tests across 10 files. [1.23s]`
215
- const dur = /\[([\d.]+)s\]/.exec(trimmed);
216
- if (dur && /Ran\s+\d+\s+tests/.test(trimmed)) {
217
- duration_ms = Math.round(Number(dur[1]) * 1000);
218
- }
219
- }
220
-
221
- if (pendingFailure) {
222
- failing_tests.push(pendingFailure);
223
- }
224
-
225
- return { passed, failed, skipped, duration_ms, failing_tests };
226
- }
227
-
228
- // ─────────────────────────────────────────────────────────────────────────
229
- // Child process invocation
230
- // ─────────────────────────────────────────────────────────────────────────
231
-
232
- function tailString(s: string, max = 2000): string {
233
- if (s.length <= max) return s;
234
- return s.slice(-max);
235
- }
236
-
237
- function isNoTestFilesSignal(stdout: string, stderr: string): boolean {
238
- // Bun reports "0 tests" or exits with a "No tests found" banner depending
239
- // on version. We match on both variants.
240
- const combined = `${stdout}\n${stderr}`;
241
- if (/Ran\s+0\s+tests/i.test(combined)) return true;
242
- if (/No tests found/i.test(combined)) return true;
243
- if (/no test files/i.test(combined)) return true;
244
- return false;
245
- }
246
-
247
- /**
248
- * Resolve the `mandu` CLI entry. We prefer the workspace binary
249
- * (`packages/cli/src/main.ts`) when running inside the monorepo, else
250
- * fall back to `mandu` on PATH.
251
- *
252
- * The CLI entry is invoked directly via `bun run <path>` so users get
253
- * the version bundled with their project without relying on global installs.
254
- */
255
- async function resolveManduCommand(projectRoot: string): Promise<string[]> {
256
- // Prefer a local `.bin/mandu` if the project installed `@mandujs/cli`.
257
- const localBin = path.join(projectRoot, "node_modules", ".bin", "mandu");
258
- try {
259
- const f = Bun.file(localBin);
260
- if (await f.exists()) {
261
- return ["bun", "run", localBin];
262
- }
263
- } catch {}
264
-
265
- // Monorepo: packages/cli/src/main.ts is directly executable via bun.
266
- const monorepoCli = path.resolve(projectRoot, "packages", "cli", "src", "main.ts");
267
- try {
268
- const f = Bun.file(monorepoCli);
269
- if (await f.exists()) {
270
- return ["bun", "run", monorepoCli];
271
- }
272
- } catch {}
273
-
274
- // Fallback: rely on PATH.
275
- return ["mandu"];
276
- }
277
-
278
- async function runProcess(
279
- cmd: string[],
280
- cwd: string,
281
- timeoutMs: number,
282
- ): Promise<{ stdout: string; stderr: string; exitCode: number; timedOut: boolean }> {
283
- const proc = spawn(cmd, {
284
- cwd,
285
- stdout: "pipe",
286
- stderr: "pipe",
287
- });
288
-
289
- let timedOut = false;
290
- const timeoutHandle: ReturnType<typeof setTimeout> = setTimeout(() => {
291
- timedOut = true;
292
- try {
293
- proc.kill();
294
- } catch {}
295
- }, timeoutMs);
296
-
297
- try {
298
- const [stdout, stderr, exitCode] = await Promise.all([
299
- new Response(proc.stdout).text(),
300
- new Response(proc.stderr).text(),
301
- proc.exited,
302
- ]);
303
- return { stdout, stderr, exitCode: exitCode ?? 1, timedOut };
304
- } finally {
305
- clearTimeout(timeoutHandle);
306
- }
307
- }
308
-
309
- // ─────────────────────────────────────────────────────────────────────────
310
- // Public handler
311
- // ─────────────────────────────────────────────────────────────────────────
312
-
313
- async function runManduTests(
314
- projectRoot: string,
315
- input: RunTestsInput,
316
- ): Promise<RunTestsResult | { error: string; field?: string; hint?: string }> {
317
- const validated = validateInput(input as Record<string, unknown>);
318
- if (!validated.ok) {
319
- return {
320
- error: validated.error,
321
- field: validated.field,
322
- hint: validated.hint,
323
- };
324
- }
325
-
326
- const { target, filter, coverage } = validated.value;
327
-
328
- const base = await resolveManduCommand(projectRoot);
329
- const args = [...base, "test"];
330
- if (target !== "all") args.push(target);
331
- if (filter) args.push("--filter", filter);
332
- if (coverage) args.push("--coverage");
333
-
334
- let proc: { stdout: string; stderr: string; exitCode: number; timedOut: boolean };
335
- try {
336
- proc = await runProcess(args, projectRoot, COMMAND_TIMEOUT_MS);
337
- } catch (err) {
338
- return {
339
- error: `Failed to spawn test runner: ${err instanceof Error ? err.message : String(err)}`,
340
- hint: "Verify that @mandujs/cli is installed and accessible",
341
- };
342
- }
343
-
344
- // No-tests case: the caller gets a benign zeroed summary.
345
- if (isNoTestFilesSignal(proc.stdout, proc.stderr) && proc.exitCode !== 0) {
346
- return {
347
- target,
348
- passed: 0,
349
- failed: 0,
350
- skipped: 0,
351
- failing_tests: [],
352
- exit_code: proc.exitCode,
353
- note: "no test files",
354
- stdout_tail: tailString(proc.stdout),
355
- stderr_tail: tailString(proc.stderr),
356
- };
357
- }
358
-
359
- const parsed = parseBunTestOutput(`${proc.stdout}\n${proc.stderr}`);
360
-
361
- const result: RunTestsResult = {
362
- target,
363
- passed: parsed.passed,
364
- failed: parsed.failed,
365
- skipped: parsed.skipped,
366
- failing_tests: parsed.failing_tests,
367
- exit_code: proc.exitCode,
368
- stdout_tail: tailString(proc.stdout),
369
- stderr_tail: tailString(proc.stderr),
370
- };
371
- if (parsed.duration_ms !== undefined) result.duration_ms = parsed.duration_ms;
372
- if (proc.timedOut) result.note = "timed out";
373
- if (parsed.passed === 0 && parsed.failed === 0 && parsed.skipped === 0) {
374
- result.note = result.note ?? "no test files";
375
- }
376
-
377
- return result;
378
- }
379
-
380
- // ─────────────────────────────────────────────────────────────────────────
381
- // MCP tool definition + handler map
382
- // ─────────────────────────────────────────────────────────────────────────
383
-
384
- export const runTestsToolDefinitions: Tool[] = [
385
- {
386
- name: "mandu.run.tests",
387
- description:
388
- "Run the project's tests via `mandu test` and return a structured summary: passed / failed / skipped counts plus a list of failing tests with file and error context. Safe to call repeatedly — no writes, just spawns the child process and parses its output.",
389
- annotations: {
390
- readOnlyHint: true,
391
- },
392
- inputSchema: {
393
- type: "object",
394
- properties: {
395
- target: {
396
- type: "string",
397
- enum: ["unit", "integration", "e2e", "all"],
398
- description:
399
- "Which test target to run (default: 'all'). Maps directly to `mandu test <target>`.",
400
- },
401
- filter: {
402
- type: "string",
403
- description:
404
- "Forward `--filter <pattern>` to `bun test` — restricts to matching describe/it names.",
405
- },
406
- coverage: {
407
- type: "boolean",
408
- description: "Pass `--coverage` to emit a coverage report (default: false).",
409
- },
410
- },
411
- required: [],
412
- },
413
- },
414
- ];
415
-
416
- export function runTestsTools(projectRoot: string) {
417
- const handlers: Record<string, (args: Record<string, unknown>) => Promise<unknown>> = {
418
- "mandu.run.tests": async (args) => runManduTests(projectRoot, args as RunTestsInput),
419
- };
420
- return handlers;
421
- }
422
-
423
- // Re-export with canonical snake-case alias for parsimony (used by tests).
424
- export { parseBunTestOutput as parseTestOutput };
1
+ /**
2
+ * MCP tool — `mandu.run.tests`
3
+ *
4
+ * Invokes `mandu test` as a child process via `Bun.spawn` and parses the
5
+ * resulting Bun test output into a structured summary:
6
+ *
7
+ * { passed, failed, skipped, failing_tests: [{ name, file, error }] }
8
+ *
9
+ * Design notes:
10
+ * • Input is validated against a minimal runtime schema (see `validateInput`).
11
+ * Bad input produces a structured `{ error, field, hint }` object — the
12
+ * error-handler's `isSoftErrorResult` detector will surface this as
13
+ * `isError: true` to MCP clients.
14
+ * • If no test files are discovered we return `{ passed: 0, failed: 0,
15
+ * skipped: 0, note: "no test files" }` without failing the caller.
16
+ * • The child process is spawned with a 10-minute ceiling via Promise.race —
17
+ * well above normal test suites but short enough that a stuck process
18
+ * never hangs the MCP server.
19
+ */
20
+
21
+ import type { Tool } from "@modelcontextprotocol/sdk/types.js";
22
+ import { spawn } from "bun";
23
+ import path from "path";
24
+
25
+ // ─────────────────────────────────────────────────────────────────────────
26
+ // Types
27
+ // ─────────────────────────────────────────────────────────────────────────
28
+
29
+ type RunTarget = "unit" | "integration" | "e2e" | "all";
30
+
31
+ interface RunTestsInput {
32
+ target?: RunTarget;
33
+ filter?: string;
34
+ coverage?: boolean;
35
+ }
36
+
37
+ interface FailingTest {
38
+ name: string;
39
+ file?: string;
40
+ error?: string;
41
+ }
42
+
43
+ interface RunTestsResult {
44
+ target: RunTarget;
45
+ passed: number;
46
+ failed: number;
47
+ skipped: number;
48
+ duration_ms?: number;
49
+ failing_tests: FailingTest[];
50
+ exit_code: number;
51
+ note?: string;
52
+ /** Trailing 2000 chars of stdout for diagnostic context. */
53
+ stdout_tail?: string;
54
+ /** Trailing 2000 chars of stderr for diagnostic context. */
55
+ stderr_tail?: string;
56
+ }
57
+
58
+ // ─────────────────────────────────────────────────────────────────────────
59
+ // Validation
60
+ // ─────────────────────────────────────────────────────────────────────────
61
+
62
+ const VALID_TARGETS = new Set<RunTarget>(["unit", "integration", "e2e", "all"]);
63
+ const COMMAND_TIMEOUT_MS = 10 * 60_000;
64
+
65
+ function validateInput(raw: Record<string, unknown>): {
66
+ ok: true;
67
+ value: Required<Pick<RunTestsInput, "target" | "coverage">> &
68
+ Pick<RunTestsInput, "filter">;
69
+ } | { ok: false; error: string; field: string; hint: string } {
70
+ const target = raw.target ?? "all";
71
+ if (typeof target !== "string" || !VALID_TARGETS.has(target as RunTarget)) {
72
+ return {
73
+ ok: false,
74
+ error: "Invalid 'target' — expected 'unit', 'integration', 'e2e', or 'all'",
75
+ field: "target",
76
+ hint: "Omit to default to 'all'",
77
+ };
78
+ }
79
+
80
+ const filter = raw.filter;
81
+ if (filter !== undefined && typeof filter !== "string") {
82
+ return {
83
+ ok: false,
84
+ error: "'filter' must be a string",
85
+ field: "filter",
86
+ hint: "Pass a bun-test filter pattern, e.g. 'my-describe > my-case'",
87
+ };
88
+ }
89
+
90
+ const coverage = raw.coverage;
91
+ if (coverage !== undefined && typeof coverage !== "boolean") {
92
+ return {
93
+ ok: false,
94
+ error: "'coverage' must be a boolean",
95
+ field: "coverage",
96
+ hint: "Pass true to emit a coverage report",
97
+ };
98
+ }
99
+
100
+ return {
101
+ ok: true,
102
+ value: {
103
+ target: target as RunTarget,
104
+ coverage: coverage === true,
105
+ ...(typeof filter === "string" && filter.length > 0 ? { filter } : {}),
106
+ },
107
+ };
108
+ }
109
+
110
+ // ─────────────────────────────────────────────────────────────────────────
111
+ // Parser — Bun test output → RunTestsResult
112
+ // ─────────────────────────────────────────────────────────────────────────
113
+
114
+ /**
115
+ * Parse bun-test style output. Bun emits:
116
+ * `(pass) describe > test`
117
+ * `(fail) describe > test`
118
+ * `(skip) describe > test`
119
+ *
120
+ * And a trailing summary block:
121
+ * `N pass`
122
+ * `M fail`
123
+ * `K skipped`
124
+ * `Ran ... tests across ... files. [x.xxs]`
125
+ *
126
+ * This parser is intentionally forgiving: counts are taken from the
127
+ * explicit summary lines when present, else derived from `(pass|fail|skip)`
128
+ * markers.
129
+ */
130
+ export function parseBunTestOutput(raw: string): {
131
+ passed: number;
132
+ failed: number;
133
+ skipped: number;
134
+ duration_ms?: number;
135
+ failing_tests: FailingTest[];
136
+ } {
137
+ const lines = raw.split(/\r?\n/);
138
+ let passed = 0;
139
+ let failed = 0;
140
+ let skipped = 0;
141
+ let duration_ms: number | undefined;
142
+ const failing_tests: FailingTest[] = [];
143
+
144
+ let currentFile: string | undefined;
145
+ let pendingFailure: FailingTest | null = null;
146
+
147
+ for (const line of lines) {
148
+ const trimmed = line.trim();
149
+
150
+ // Track the current file heading (e.g. "src/foo.test.ts:"):
151
+ const fileMatch = /^([^\s()]+\.(?:test|spec)\.(?:ts|tsx|js|jsx|mjs|cjs)):$/.exec(trimmed);
152
+ if (fileMatch) {
153
+ currentFile = fileMatch[1];
154
+ continue;
155
+ }
156
+
157
+ // `(fail) ...` → start a failing test record.
158
+ const failMatch = /^\(fail\)\s+(.+)$/.exec(trimmed);
159
+ if (failMatch) {
160
+ if (pendingFailure) {
161
+ failing_tests.push(pendingFailure);
162
+ }
163
+ pendingFailure = {
164
+ name: failMatch[1].trim(),
165
+ file: currentFile,
166
+ };
167
+ continue;
168
+ }
169
+
170
+ // `(skip) ...` counts as skipped but doesn't emit a record.
171
+ if (/^\(skip\)\s+/.test(trimmed)) {
172
+ continue;
173
+ }
174
+
175
+ // If we're inside a failure block, capture the first few non-empty
176
+ // lines that follow as error context.
177
+ if (pendingFailure && trimmed.length > 0) {
178
+ const isNextTestMarker = /^\(pass|fail|skip\)/.test(trimmed);
179
+ if (!isNextTestMarker) {
180
+ pendingFailure.error = pendingFailure.error
181
+ ? `${pendingFailure.error}\n${trimmed}`
182
+ : trimmed;
183
+ // Cap the captured error to keep payloads tight.
184
+ if (pendingFailure.error.length > 800) {
185
+ pendingFailure.error = pendingFailure.error.slice(0, 800);
186
+ }
187
+ continue;
188
+ }
189
+ }
190
+
191
+ // End-of-block marker flushes the current failure record.
192
+ if (pendingFailure && (trimmed.length === 0 || /^\d+\s+(pass|fail|skipped)\b/.test(trimmed))) {
193
+ failing_tests.push(pendingFailure);
194
+ pendingFailure = null;
195
+ }
196
+
197
+ // Totals block — authoritative if present.
198
+ const passMatch = /^(\d+)\s+pass\b/.exec(trimmed);
199
+ if (passMatch) {
200
+ passed = Number(passMatch[1]);
201
+ continue;
202
+ }
203
+ const failSumMatch = /^(\d+)\s+fail\b/.exec(trimmed);
204
+ if (failSumMatch) {
205
+ failed = Number(failSumMatch[1]);
206
+ continue;
207
+ }
208
+ const skipMatch = /^(\d+)\s+skipped\b/.exec(trimmed);
209
+ if (skipMatch) {
210
+ skipped = Number(skipMatch[1]);
211
+ continue;
212
+ }
213
+
214
+ // Duration: `Ran 123 tests across 10 files. [1.23s]`
215
+ const dur = /\[([\d.]+)s\]/.exec(trimmed);
216
+ if (dur && /Ran\s+\d+\s+tests/.test(trimmed)) {
217
+ duration_ms = Math.round(Number(dur[1]) * 1000);
218
+ }
219
+ }
220
+
221
+ if (pendingFailure) {
222
+ failing_tests.push(pendingFailure);
223
+ }
224
+
225
+ return { passed, failed, skipped, duration_ms, failing_tests };
226
+ }
227
+
228
+ // ─────────────────────────────────────────────────────────────────────────
229
+ // Child process invocation
230
+ // ─────────────────────────────────────────────────────────────────────────
231
+
232
+ function tailString(s: string, max = 2000): string {
233
+ if (s.length <= max) return s;
234
+ return s.slice(-max);
235
+ }
236
+
237
+ function isNoTestFilesSignal(stdout: string, stderr: string): boolean {
238
+ // Bun reports "0 tests" or exits with a "No tests found" banner depending
239
+ // on version. We match on both variants.
240
+ const combined = `${stdout}\n${stderr}`;
241
+ if (/Ran\s+0\s+tests/i.test(combined)) return true;
242
+ if (/No tests found/i.test(combined)) return true;
243
+ if (/no test files/i.test(combined)) return true;
244
+ return false;
245
+ }
246
+
247
+ /**
248
+ * Resolve the `mandu` CLI entry. We prefer the workspace binary
249
+ * (`packages/cli/src/main.ts`) when running inside the monorepo, else
250
+ * fall back to `mandu` on PATH.
251
+ *
252
+ * The CLI entry is invoked directly via `bun run <path>` so users get
253
+ * the version bundled with their project without relying on global installs.
254
+ */
255
+ async function resolveManduCommand(projectRoot: string): Promise<string[]> {
256
+ // Prefer a local `.bin/mandu` if the project installed `@mandujs/cli`.
257
+ const localBin = path.join(projectRoot, "node_modules", ".bin", "mandu");
258
+ try {
259
+ const f = Bun.file(localBin);
260
+ if (await f.exists()) {
261
+ return ["bun", "run", localBin];
262
+ }
263
+ } catch {}
264
+
265
+ // Monorepo: packages/cli/src/main.ts is directly executable via bun.
266
+ const monorepoCli = path.resolve(projectRoot, "packages", "cli", "src", "main.ts");
267
+ try {
268
+ const f = Bun.file(monorepoCli);
269
+ if (await f.exists()) {
270
+ return ["bun", "run", monorepoCli];
271
+ }
272
+ } catch {}
273
+
274
+ // Fallback: rely on PATH.
275
+ return ["mandu"];
276
+ }
277
+
278
+ async function runProcess(
279
+ cmd: string[],
280
+ cwd: string,
281
+ timeoutMs: number,
282
+ ): Promise<{ stdout: string; stderr: string; exitCode: number; timedOut: boolean }> {
283
+ const proc = spawn(cmd, {
284
+ cwd,
285
+ stdout: "pipe",
286
+ stderr: "pipe",
287
+ });
288
+
289
+ let timedOut = false;
290
+ const timeoutHandle: ReturnType<typeof setTimeout> = setTimeout(() => {
291
+ timedOut = true;
292
+ try {
293
+ proc.kill();
294
+ } catch {}
295
+ }, timeoutMs);
296
+
297
+ try {
298
+ const [stdout, stderr, exitCode] = await Promise.all([
299
+ new Response(proc.stdout).text(),
300
+ new Response(proc.stderr).text(),
301
+ proc.exited,
302
+ ]);
303
+ return { stdout, stderr, exitCode: exitCode ?? 1, timedOut };
304
+ } finally {
305
+ clearTimeout(timeoutHandle);
306
+ }
307
+ }
308
+
309
+ // ─────────────────────────────────────────────────────────────────────────
310
+ // Public handler
311
+ // ─────────────────────────────────────────────────────────────────────────
312
+
313
+ async function runManduTests(
314
+ projectRoot: string,
315
+ input: RunTestsInput,
316
+ ): Promise<RunTestsResult | { error: string; field?: string; hint?: string }> {
317
+ const validated = validateInput(input as Record<string, unknown>);
318
+ if (!validated.ok) {
319
+ return {
320
+ error: validated.error,
321
+ field: validated.field,
322
+ hint: validated.hint,
323
+ };
324
+ }
325
+
326
+ const { target, filter, coverage } = validated.value;
327
+
328
+ const base = await resolveManduCommand(projectRoot);
329
+ const args = [...base, "test"];
330
+ if (target !== "all") args.push(target);
331
+ if (filter) args.push("--filter", filter);
332
+ if (coverage) args.push("--coverage");
333
+
334
+ let proc: { stdout: string; stderr: string; exitCode: number; timedOut: boolean };
335
+ try {
336
+ proc = await runProcess(args, projectRoot, COMMAND_TIMEOUT_MS);
337
+ } catch (err) {
338
+ return {
339
+ error: `Failed to spawn test runner: ${err instanceof Error ? err.message : String(err)}`,
340
+ hint: "Verify that @mandujs/cli is installed and accessible",
341
+ };
342
+ }
343
+
344
+ // No-tests case: the caller gets a benign zeroed summary.
345
+ if (isNoTestFilesSignal(proc.stdout, proc.stderr) && proc.exitCode !== 0) {
346
+ return {
347
+ target,
348
+ passed: 0,
349
+ failed: 0,
350
+ skipped: 0,
351
+ failing_tests: [],
352
+ exit_code: proc.exitCode,
353
+ note: "no test files",
354
+ stdout_tail: tailString(proc.stdout),
355
+ stderr_tail: tailString(proc.stderr),
356
+ };
357
+ }
358
+
359
+ const parsed = parseBunTestOutput(`${proc.stdout}\n${proc.stderr}`);
360
+
361
+ const result: RunTestsResult = {
362
+ target,
363
+ passed: parsed.passed,
364
+ failed: parsed.failed,
365
+ skipped: parsed.skipped,
366
+ failing_tests: parsed.failing_tests,
367
+ exit_code: proc.exitCode,
368
+ stdout_tail: tailString(proc.stdout),
369
+ stderr_tail: tailString(proc.stderr),
370
+ };
371
+ if (parsed.duration_ms !== undefined) result.duration_ms = parsed.duration_ms;
372
+ if (proc.timedOut) result.note = "timed out";
373
+ if (parsed.passed === 0 && parsed.failed === 0 && parsed.skipped === 0) {
374
+ result.note = result.note ?? "no test files";
375
+ }
376
+
377
+ return result;
378
+ }
379
+
380
+ // ─────────────────────────────────────────────────────────────────────────
381
+ // MCP tool definition + handler map
382
+ // ─────────────────────────────────────────────────────────────────────────
383
+
384
+ export const runTestsToolDefinitions: Tool[] = [
385
+ {
386
+ name: "mandu.run.tests",
387
+ description:
388
+ "Run the project's tests via `mandu test` and return a structured summary: passed / failed / skipped counts plus a list of failing tests with file and error context. Safe to call repeatedly — no writes, just spawns the child process and parses its output.",
389
+ annotations: {
390
+ readOnlyHint: true,
391
+ },
392
+ inputSchema: {
393
+ type: "object",
394
+ properties: {
395
+ target: {
396
+ type: "string",
397
+ enum: ["unit", "integration", "e2e", "all"],
398
+ description:
399
+ "Which test target to run (default: 'all'). Maps directly to `mandu test <target>`.",
400
+ },
401
+ filter: {
402
+ type: "string",
403
+ description:
404
+ "Forward `--filter <pattern>` to `bun test` — restricts to matching describe/it names.",
405
+ },
406
+ coverage: {
407
+ type: "boolean",
408
+ description: "Pass `--coverage` to emit a coverage report (default: false).",
409
+ },
410
+ },
411
+ required: [],
412
+ },
413
+ },
414
+ ];
415
+
416
+ export function runTestsTools(projectRoot: string) {
417
+ const handlers: Record<string, (args: Record<string, unknown>) => Promise<unknown>> = {
418
+ "mandu.run.tests": async (args) => runManduTests(projectRoot, args as RunTestsInput),
419
+ };
420
+ return handlers;
421
+ }
422
+
423
+ // Re-export with canonical snake-case alias for parsimony (used by tests).
424
+ export { parseBunTestOutput as parseTestOutput };