raiton 6.10.0-beta.28 → 6.11.0-beta.29

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 (96) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.md +19 -0
  3. package/benchmarks/README.md +15 -0
  4. package/benchmarks/ai-debug.json +145 -0
  5. package/benchmarks/ai-debug.md +64 -0
  6. package/benchmarks/latest.json +71 -71
  7. package/benchmarks/latest.md +25 -25
  8. package/build/bin/index.mjs +6028 -2098
  9. package/build/types/commands/call.command.d.ts +10 -0
  10. package/build/types/commands/debug.shared.d.ts +16 -0
  11. package/build/types/commands/explain.command.d.ts +8 -0
  12. package/build/types/commands/mcp.command.d.ts +1 -0
  13. package/build/types/commands/requests.command.d.ts +8 -0
  14. package/build/types/commands/verify.command.d.ts +8 -0
  15. package/build/types/contracts/decorators.d.ts +18 -0
  16. package/build/types/contracts/errors.d.ts +29 -3
  17. package/build/types/contracts/schema.d.ts +13 -0
  18. package/build/types/core/application.d.ts +8 -0
  19. package/build/types/debug/cli.d.ts +33 -0
  20. package/build/types/debug/collector.d.ts +41 -0
  21. package/build/types/debug/collector.internal.d.ts +27 -0
  22. package/build/types/debug/config.d.ts +19 -0
  23. package/build/types/debug/examples.d.ts +43 -0
  24. package/build/types/debug/explain.d.ts +9 -0
  25. package/build/types/debug/index.d.ts +15 -0
  26. package/build/types/debug/invocation.d.ts +53 -0
  27. package/build/types/debug/journal.d.ts +49 -0
  28. package/build/types/debug/mcp-http.d.ts +17 -0
  29. package/build/types/debug/mcp.d.ts +14 -0
  30. package/build/types/debug/redaction.d.ts +48 -0
  31. package/build/types/debug/requests.d.ts +37 -0
  32. package/build/types/debug/runtime.d.ts +52 -0
  33. package/build/types/debug/session.d.ts +21 -0
  34. package/build/types/debug/source.d.ts +17 -0
  35. package/build/types/debug/surface.d.ts +10 -0
  36. package/build/types/debug/types.d.ts +271 -0
  37. package/build/types/debug/verify.d.ts +23 -0
  38. package/build/types/framework/errors/catalog.d.ts +16 -1
  39. package/build/types/manifest/schema.d.ts +64 -0
  40. package/build/types/types/config.d.ts +50 -0
  41. package/docs/AGENTS.md +1 -1
  42. package/docs/CLAUDE.md +1 -1
  43. package/docs/generated/cli/commands.md +5 -0
  44. package/docs/generated/config-schema.json +93 -0
  45. package/docs/generated/manifest-schema.json +76 -0
  46. package/docs/generated/manifest.json +20 -3
  47. package/docs/llms-full.txt +183 -4
  48. package/docs/llms.txt +6 -1
  49. package/docs/user-guide/README.md +1 -0
  50. package/docs/user-guide/cli.md +5 -0
  51. package/docs/user-guide/config.md +18 -0
  52. package/docs/user-guide/debug.md +130 -0
  53. package/package.json +3 -1
  54. package/scripts/bench-ai-debug.ts +572 -0
  55. package/source/bin/commands.registry.ts +8 -0
  56. package/source/commands/call.command.ts +247 -0
  57. package/source/commands/debug.shared.ts +90 -0
  58. package/source/commands/docs.command.ts +6 -0
  59. package/source/commands/explain.command.ts +119 -0
  60. package/source/commands/mcp.command.ts +64 -0
  61. package/source/commands/requests.command.ts +137 -0
  62. package/source/commands/verify.command.ts +173 -0
  63. package/source/contracts/decorators.ts +67 -2
  64. package/source/contracts/errors.ts +64 -5
  65. package/source/contracts/schema.ts +61 -0
  66. package/source/core/application.ts +120 -12
  67. package/source/core/builder.ts +4 -0
  68. package/source/core/config/config.ts +11 -0
  69. package/source/core/config/schema.ts +143 -0
  70. package/source/core/router/handler.ts +162 -13
  71. package/source/debug/cli.ts +206 -0
  72. package/source/debug/collector.internal.ts +27 -0
  73. package/source/debug/collector.ts +294 -0
  74. package/source/debug/config.ts +142 -0
  75. package/source/debug/examples.ts +188 -0
  76. package/source/debug/explain.ts +187 -0
  77. package/source/debug/index.ts +15 -0
  78. package/source/debug/invocation.ts +695 -0
  79. package/source/debug/journal.ts +249 -0
  80. package/source/debug/mcp-http.ts +145 -0
  81. package/source/debug/mcp.ts +410 -0
  82. package/source/debug/redaction.ts +225 -0
  83. package/source/debug/requests.ts +136 -0
  84. package/source/debug/runtime.ts +181 -0
  85. package/source/debug/session.ts +107 -0
  86. package/source/debug/source.ts +95 -0
  87. package/source/debug/surface.ts +375 -0
  88. package/source/debug/types.ts +311 -0
  89. package/source/debug/verify.ts +186 -0
  90. package/source/framework/errors/catalog.ts +57 -11
  91. package/source/framework/mcp/handler.ts +9 -1
  92. package/source/framework/utilities/openapi.utils.impl.ts +28 -0
  93. package/source/manifest/introspect.ts +5 -0
  94. package/source/manifest/manifest.ts +24 -1
  95. package/source/manifest/schema.ts +52 -1
  96. package/source/types/config.ts +56 -0
@@ -0,0 +1,247 @@
1
+ import {RaitonCommand} from "../core/command.ts";
2
+ import {CliError, ExitCode, fail, print, silenceStdout} from "../bin/cli-output.ts";
3
+ import {loadProject} from "../bin/project-utils.ts";
4
+ import {
5
+ appendInvocationEntry,
6
+ enableCliDebug,
7
+ entryFromInvocation,
8
+ remoteDebug,
9
+ } from "../debug/cli.ts";
10
+ import {invokeRoute, compareReplay} from "../debug/invocation.ts";
11
+ import {findRequest, replayPath} from "../debug/requests.ts";
12
+ import type {DebugInvocationRequest, DebugInvocationResult} from "../debug/types.ts";
13
+ import {
14
+ asCliError,
15
+ collect,
16
+ isFailure,
17
+ parseData,
18
+ parseMethods,
19
+ parsePairs,
20
+ } from "./debug.shared.ts";
21
+
22
+ interface CallOptions {
23
+ data?: string;
24
+ param?: string[];
25
+ query?: string[];
26
+ header?: string[];
27
+ url?: string;
28
+ token?: string;
29
+ example?: string;
30
+ dryRun?: boolean;
31
+ validate?: boolean;
32
+ failOn?: string;
33
+ timeout?: string;
34
+ replay?: string;
35
+ force?: boolean;
36
+ json?: boolean;
37
+ }
38
+
39
+ export default class CallCommand extends RaitonCommand {
40
+ public readonly name = "call";
41
+ public readonly description = "Invoke a route with local validation and a structured result";
42
+
43
+ public register(): void {
44
+ this.cli
45
+ .command("call [method] [path]")
46
+ .description(this.description)
47
+ .option("--data <json>", "JSON body literal or @file")
48
+ .option("--param <k=v>", "Path parameter (repeatable)", collect, [])
49
+ .option("--query <k=v>", "Query parameter (repeatable)", collect, [])
50
+ .option("--header <k=v>", "Header (repeatable)", collect, [])
51
+ .option("--url <base>", "Target an already running application")
52
+ .option("--token <token>", "Bearer token sent to the target")
53
+ .option("--example <name>", "Use a declared route example")
54
+ .option("--dry-run", "Print the resolved request without sending it")
55
+ .option("--no-validate", "Skip local input validation (not recommended)")
56
+ .option("--fail-on <codes>", "Comma-separated status filters that fail the command (e.g. 4xx,5xx)")
57
+ .option("--timeout <ms>", "Request timeout in milliseconds", "10000")
58
+ .option("--replay <requestId>", "Replay a request captured in the journal")
59
+ .option("--force", "Allow replaying a non-idempotent method")
60
+ .option("--json", "Emit one JSON document on stdout")
61
+ .action((method: string | undefined, routePath: string | undefined, options: CallOptions) =>
62
+ this.action(method, routePath, options));
63
+ }
64
+
65
+ private async action(method: string | undefined, routePath: string | undefined, options: CallOptions): Promise<void> {
66
+ const json = options.json === true;
67
+ try {
68
+ const output = json
69
+ ? await silenceStdout(() => this.run(method, routePath, options, true))
70
+ : await this.run(method, routePath, options, false);
71
+
72
+ if (json) {
73
+ print(output.result, true);
74
+ } else {
75
+ print(output.text);
76
+ }
77
+
78
+ if (output.failed) process.exitCode = ExitCode.DIAGNOSTIC_FAILED;
79
+ } catch (error) {
80
+ fail(asCliError(error), json);
81
+ }
82
+ }
83
+
84
+ private async run(
85
+ method: string | undefined,
86
+ routePath: string | undefined,
87
+ options: CallOptions,
88
+ json: boolean,
89
+ ): Promise<{result: DebugInvocationResult; text: string; failed: boolean}> {
90
+ const {application, manifest} = await loadProject(this.workdir, json);
91
+ const runtime = enableCliDebug(application, this.workdir);
92
+ const baseUrl = options.url?.replace(/\/+$/, "");
93
+
94
+ let replayEntry;
95
+ if (options.replay) {
96
+ replayEntry = await this.resolveReplay(options.replay, baseUrl, options);
97
+ }
98
+
99
+ if (!method || !routePath) {
100
+ if (replayEntry) {
101
+ method = replayEntry.request.method;
102
+ routePath = replayPath(replayEntry);
103
+ } else {
104
+ throw new CliError("Missing route: pass <method> <path> or --replay <requestId>", {
105
+ code: "MISSING_ROUTE",
106
+ hint: "For example: raiton call GET /items/:id --param id=1",
107
+ exitCode: ExitCode.USAGE,
108
+ });
109
+ }
110
+ }
111
+
112
+ if (replayEntry) {
113
+ const replayMethod = String(replayEntry.request.method).toUpperCase();
114
+ const idempotent = replayMethod === "GET" || replayMethod === "HEAD" || replayMethod === "OPTIONS";
115
+ if (!idempotent && !options.force && !runtime.config.replay.allowUnsafeMethods) {
116
+ throw new CliError(`Replaying a ${replayMethod} request requires --force`, {
117
+ code: "UNSAFE_REPLAY",
118
+ hint: "Replay is restricted to idempotent methods by default. Pass --force to confirm.",
119
+ exitCode: ExitCode.USAGE,
120
+ });
121
+ }
122
+ }
123
+
124
+ const [pathname, search] = String(routePath).split("?");
125
+ const queryFromPath: Record<string, string> = {};
126
+ if (search) {
127
+ for (const [key, value] of new URLSearchParams(search)) queryFromPath[key] = value;
128
+ }
129
+
130
+ const headers: Record<string, string> = {
131
+ ...(replayEntry?.request.headers ?? {}),
132
+ ...parsePairs(options.header, "header"),
133
+ };
134
+ for (const [key, value] of Object.entries(headers)) {
135
+ if (value === "***") delete headers[key];
136
+ }
137
+ if (options.token) headers.authorization = `Bearer ${options.token}`;
138
+
139
+ const spec: DebugInvocationRequest = {
140
+ method: method!,
141
+ path: pathname!,
142
+ params: {
143
+ ...(replayEntry?.request.params ?? {}),
144
+ ...parsePairs(options.param, "param"),
145
+ },
146
+ query: {
147
+ ...queryFromPath,
148
+ ...(replayEntry?.request.query ?? {}),
149
+ ...parsePairs(options.query, "query"),
150
+ },
151
+ headers,
152
+ body: options.data !== undefined
153
+ ? parseData(options.data, this.workdir)
154
+ : replayEntry?.request.body,
155
+ example: options.example,
156
+ dryRun: options.dryRun === true,
157
+ validate: options.validate !== false,
158
+ timeoutMs: Number(options.timeout ?? 10_000),
159
+ baseUrl,
160
+ ...(options.replay ? {replayedFrom: options.replay} : {}),
161
+ };
162
+
163
+ const context = {
164
+ manifest,
165
+ application: baseUrl ? undefined : application,
166
+ config: runtime.config,
167
+ baseUrl,
168
+ workdir: this.workdir,
169
+ development: true,
170
+ };
171
+
172
+ const result = await invokeRoute(context, spec);
173
+ if (replayEntry) result.comparison = compareReplay(replayEntry, result);
174
+
175
+ // Persist the exchange in the bounded CLI session journal so a later
176
+ // `raiton explain <requestId>` works even when the call was in-process.
177
+ try {
178
+ if (runtime.config.journal.enabled) {
179
+ appendInvocationEntry(entryFromInvocation(manifest, spec, result), this.workdir);
180
+ }
181
+ } catch {
182
+ // The journal bridge is best effort.
183
+ }
184
+
185
+ const failOn = parseMethods(options.failOn);
186
+ const failed = isFailure(result, failOn);
187
+ const text = this.render(result);
188
+ return {result, text, failed};
189
+ }
190
+
191
+ private async resolveReplay(requestId: string, baseUrl: string | undefined, options: CallOptions) {
192
+ if (baseUrl) {
193
+ try {
194
+ const response = await remoteDebug({baseUrl, token: options.token}, `/__raiton/requests/${encodeURIComponent(requestId)}`);
195
+ if (response.status === 200 && response.body?.entry) return response.body.entry;
196
+ } catch {
197
+ // Fall back to the local session journal below.
198
+ }
199
+ }
200
+ const local = findRequest(requestId, this.workdir);
201
+ if (!local) {
202
+ throw new CliError(`Unknown requestId: ${requestId}`, {
203
+ code: "REQUEST_NOT_FOUND",
204
+ hint: "Run `raiton requests` to list captured requests; the journal is bounded and expires after 15 minutes.",
205
+ exitCode: ExitCode.PREREQUISITE_MISSING,
206
+ });
207
+ }
208
+ return local.entry;
209
+ }
210
+
211
+ private render(result: DebugInvocationResult): string {
212
+ const lines: string[] = [];
213
+ const status = result.response.status === 0 ? "not sent" : String(result.response.status);
214
+ lines.push(`${result.request.method} ${result.request.path} → ${status} (${result.response.durationMs}ms)`);
215
+ lines.push(`request_id: ${result.response.requestId}`);
216
+ lines.push(`trace_id: ${result.response.traceId}`);
217
+ lines.push(`contract: input=${result.contract.input} output=${result.contract.output}`);
218
+ if (result.comparison) {
219
+ lines.push(
220
+ `replay: status ${result.comparison.status} (${result.comparison.previousStatus} → ${result.comparison.currentStatus}), ` +
221
+ `body ${result.comparison.body}`,
222
+ );
223
+ for (const difference of result.comparison.differences) lines.push(` - ${difference}`);
224
+ }
225
+ for (const issue of result.contract.issues) {
226
+ lines.push(
227
+ ` - ${issue.path} (${issue.code}): ${issue.message}` +
228
+ (issue.expected ? ` expected ${issue.expected}` : "") +
229
+ (issue.received !== undefined ? ` received ${issue.received}` : "") +
230
+ (issue.location ? ` at ${issue.location}` : ""),
231
+ );
232
+ }
233
+ if (result.request.dryRun) {
234
+ lines.push(`dry-run: ${result.request.method} ${result.request.url ?? result.request.path}`);
235
+ if (result.request.body !== undefined) lines.push(`body: ${JSON.stringify(result.request.body)}`);
236
+ } else if (result.response.body !== undefined) {
237
+ lines.push(JSON.stringify(result.response.body, null, 2));
238
+ }
239
+ if (result.nextActions.length) {
240
+ lines.push("");
241
+ for (const action of result.nextActions) lines.push(`next: ${action}`);
242
+ }
243
+ return lines.join("\n");
244
+ }
245
+ }
246
+
247
+
@@ -0,0 +1,90 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import {CliError, ExitCode} from "../bin/cli-output.ts";
4
+ import {DebugInvocationError} from "../debug/invocation.ts";
5
+
6
+ export function collect(value: string, previous: string[] = []): string[] {
7
+ return [...previous, value];
8
+ }
9
+
10
+ export function parsePairs(values: string[] | undefined, label: string): Record<string, string> {
11
+ const output: Record<string, string> = {};
12
+ for (const entry of values ?? []) {
13
+ const index = entry.indexOf("=");
14
+ if (index <= 0) {
15
+ throw new CliError(`Invalid --${label} value: ${entry}`, {
16
+ code: "INVALID_OPTION",
17
+ hint: `Use --${label} key=value.`,
18
+ exitCode: ExitCode.USAGE,
19
+ });
20
+ }
21
+ output[entry.slice(0, index)] = entry.slice(index + 1);
22
+ }
23
+ return output;
24
+ }
25
+
26
+ export function parseData(value: string | undefined, workdir: string): any {
27
+ if (value === undefined) return undefined;
28
+ let content = value;
29
+ if (value.startsWith("@")) {
30
+ const filename = path.resolve(workdir, value.slice(1));
31
+ if (!fs.existsSync(filename)) {
32
+ throw new CliError(`Data file not found: ${value.slice(1)}`, {
33
+ code: "FILE_NOT_FOUND",
34
+ hint: "Check the --data @file path.",
35
+ location: filename,
36
+ exitCode: ExitCode.PREREQUISITE_MISSING,
37
+ });
38
+ }
39
+ content = fs.readFileSync(filename, "utf-8");
40
+ }
41
+ try {
42
+ return JSON.parse(content);
43
+ } catch (error: any) {
44
+ throw new CliError(`Invalid JSON payload: ${error.message}`, {
45
+ code: "INVALID_JSON",
46
+ hint: "Pass a JSON literal or --data @file.json.",
47
+ exitCode: ExitCode.USAGE,
48
+ });
49
+ }
50
+ }
51
+
52
+ export function asCliError(error: unknown, fallbackHint?: string): CliError {
53
+ if (error instanceof CliError) return error;
54
+ if (error instanceof DebugInvocationError) {
55
+ return new CliError(error.message, {
56
+ code: error.code,
57
+ hint: error.hint,
58
+ location: error.location,
59
+ exitCode: error.exitCode as ExitCode,
60
+ });
61
+ }
62
+ const anyError: any = error;
63
+ return new CliError(anyError?.message ?? String(error), {
64
+ code: anyError?.code ?? "COMMAND_FAILED",
65
+ hint: anyError?.hint ?? fallbackHint ?? "Run `raiton --help` to inspect available commands.",
66
+ location: anyError?.location,
67
+ exitCode: anyError?.exitCode ?? ExitCode.USAGE,
68
+ });
69
+ }
70
+
71
+ export function parseMethods(value?: string): string[] {
72
+ if (!value) return [];
73
+ return value.split(",").map(item => item.trim()).filter(Boolean);
74
+ }
75
+
76
+ export function isFailure(result: {contract: {input: string; output: string}; response: {status: number}}, failOn: string[]): boolean {
77
+ if (result.contract.input === "invalid" || result.contract.output === "invalid") return true;
78
+ return failOn.some(filter => matchStatus(result.response.status, filter));
79
+ }
80
+
81
+ export function matchStatus(status: number, filter: string): boolean {
82
+ const value = filter.trim().toLowerCase();
83
+ if (!value) return false;
84
+ if (/^\dxx$/.test(value)) return Math.floor(status / 100) === Number(value[0]);
85
+ if (value.includes("-")) {
86
+ const [min, max] = value.split("-").map(Number);
87
+ return status >= min && status <= max;
88
+ }
89
+ return status === Number(value);
90
+ }
@@ -20,6 +20,10 @@ const COMMANDS = [
20
20
  ["routes", "List mounted routes"],
21
21
  ["inspect", "Emit the versioned project manifest"],
22
22
  ["why <method> <path>", "Explain which file registered a route"],
23
+ ["call [method] [path]", "Invoke a route with local validation and a structured result"],
24
+ ["requests", "List recently captured requests"],
25
+ ["explain [requestId]", "Explain a request: timeline, root cause and next actions"],
26
+ ["verify", "Call route examples and validate status and output contracts"],
23
27
  ["doctor", "Diagnose runtime, configuration and prerequisites"],
24
28
  ["openapi export", "Export the OpenAPI document"],
25
29
  ["client", "Generate a typed client"],
@@ -30,6 +34,7 @@ const COMMANDS = [
30
34
  ["mcp test <server>.<tool>", "Call an MCP tool"],
31
35
  ["mcp serve [server]", "Serve an MCP server over stdio"],
32
36
  ["mcp conformance [server]", "Run the HTTP + stdio conformance suite"],
37
+ ["mcp debug", "Serve the AI-assisted debug MCP server (stdio or HTTP)"],
33
38
  ["docs agents", "Generate llms.txt, llms-full.txt, AGENTS.md and CLAUDE.md"],
34
39
  ["artifact --dump", "Inspect detected artifacts"],
35
40
  ["dev", "Run the application with HMR"],
@@ -48,6 +53,7 @@ const GUIDE_FILES = [
48
53
  "user-guide/contracts.md",
49
54
  "user-guide/mcp.md",
50
55
  "user-guide/observability.md",
56
+ "user-guide/debug.md",
51
57
  "user-guide/decorators/README.md",
52
58
  "user-guide/recipes/README.md",
53
59
  "user-guide/en/README.md",
@@ -0,0 +1,119 @@
1
+ import {RaitonCommand} from "../core/command.ts";
2
+ import {CliError, ExitCode, fail, print, silenceStdout} from "../bin/cli-output.ts";
3
+ import {RaitonConfig} from "../core/config/config.ts";
4
+ import {resolveDebugConfig} from "../debug/config.ts";
5
+ import {remoteDebug} from "../debug/cli.ts";
6
+ import {findRequest, lastRequest} from "../debug/requests.ts";
7
+ import {explainEntry, explainHuman} from "../debug/explain.ts";
8
+ import {asCliError} from "./debug.shared.ts";
9
+
10
+ interface ExplainOptions {
11
+ last?: boolean;
12
+ verbose?: boolean;
13
+ url?: string;
14
+ token?: string;
15
+ json?: boolean;
16
+ }
17
+
18
+ export default class ExplainCommand extends RaitonCommand {
19
+ public readonly name = "explain";
20
+ public readonly description = "Explain a captured request: timeline, root cause and next actions";
21
+
22
+ public register(): void {
23
+ this.cli
24
+ .command("explain [requestId]")
25
+ .description(this.description)
26
+ .option("--last", "Explain the most recent request")
27
+ .option("--verbose", "Include redacted request and response bodies")
28
+ .option("--url <base>", "Target an already running application")
29
+ .option("--token <token>", "Debug token for a protected surface")
30
+ .option("--json", "Emit one JSON document on stdout")
31
+ .action((requestId: string | undefined, options: ExplainOptions) =>
32
+ this.action(requestId, options));
33
+ }
34
+
35
+ private async action(requestId: string | undefined, options: ExplainOptions): Promise<void> {
36
+ const json = options.json === true;
37
+ try {
38
+ const output = json
39
+ ? await silenceStdout(() => this.run(requestId, options))
40
+ : await this.run(requestId, options);
41
+ if (json) print(output.explanation, true);
42
+ else print(output.text);
43
+ } catch (error) {
44
+ fail(asCliError(error), json);
45
+ }
46
+ }
47
+
48
+ private async run(requestId: string | undefined, options: ExplainOptions) {
49
+ if (!requestId && !options.last) {
50
+ throw new CliError("Missing request id", {
51
+ code: "MISSING_REQUEST_ID",
52
+ hint: "Pass a request id or --last (run `raiton requests` to list captured requests).",
53
+ exitCode: ExitCode.USAGE,
54
+ });
55
+ }
56
+
57
+ await RaitonConfig.sync(this.workdir, {force: true});
58
+ const debugConfig = resolveDebugConfig({development: true, workdir: this.workdir});
59
+ const target = options.url?.replace(/\/+$/, "") ?? configuredBaseUrl();
60
+ const remotePath = options.last || requestId === "last"
61
+ ? "/__raiton/explain/last"
62
+ : `/__raiton/explain/${encodeURIComponent(String(requestId))}`;
63
+
64
+ let explanation;
65
+ try {
66
+ const response = await remoteDebug(
67
+ {baseUrl: target, token: options.token, timeoutMs: options.url ? 1_500 : 300},
68
+ `${remotePath}${options.verbose ? "?verbose=true" : ""}`,
69
+ );
70
+ if (response.status === 200 && response.body?.diagnosis) {
71
+ explanation = response.body;
72
+ } else if (response.status === 401 || response.status === 403) {
73
+ throw new CliError("The running application rejected the debug token", {
74
+ code: "DEBUG_UNAUTHORIZED",
75
+ hint: "Pass --token or set RAITON_DEBUG_TOKEN.",
76
+ exitCode: ExitCode.PREREQUISITE_MISSING,
77
+ });
78
+ }
79
+ } catch (error) {
80
+ if (error instanceof CliError) throw error;
81
+ // Fall back to the bounded CLI session journal.
82
+ }
83
+
84
+ if (!explanation) {
85
+ const lookup = options.last || requestId === "last"
86
+ ? lastRequest(this.workdir)
87
+ : findRequest(String(requestId), this.workdir);
88
+ if (lookup) explanation = explainEntry(lookup.entry, {verbose: options.verbose});
89
+ }
90
+
91
+ if (!explanation) {
92
+ if (!debugConfig.journal.enabled) {
93
+ throw new CliError("The request journal is disabled", {
94
+ code: "DEBUG_JOURNAL_DISABLED",
95
+ hint: "Enable `debug.journal.enabled` in raiton.config.ts or set RAITON_DEBUG_JOURNAL=1, then reproduce the request.",
96
+ exitCode: ExitCode.PREREQUISITE_MISSING,
97
+ });
98
+ }
99
+ throw new CliError(`No captured request found${requestId ? `: ${requestId}` : ""}`, {
100
+ code: "REQUEST_NOT_FOUND",
101
+ hint: "Run `raiton requests` to list captured requests; entries expire after 15 minutes.",
102
+ exitCode: ExitCode.PREREQUISITE_MISSING,
103
+ });
104
+ }
105
+
106
+ return {explanation, text: explainHuman(explanation)};
107
+ }
108
+ }
109
+
110
+ function configuredBaseUrl(): string {
111
+ const protocol = (RaitonConfig.get("protocole") as string) || "http";
112
+ const host = RaitonConfig.get("hostname") || "localhost";
113
+ const port = RaitonConfig.get("port");
114
+ const pathname = RaitonConfig.get("pathname");
115
+ const prefix = RaitonConfig.get("prefix");
116
+ const path = pathname && pathname !== "/" ? pathname.replace(/\/+$/, "") : "";
117
+ const prefixed = prefix ? `/${String(prefix).replace(/^\/+|\/+$/g, "")}` : "";
118
+ return `${protocol}://${host === "0.0.0.0" ? "localhost" : host}${port ? `:${port}` : ""}${path}${prefixed}`;
119
+ }
@@ -7,6 +7,9 @@ import {handleMcpRequest} from "../framework/mcp/handler.ts";
7
7
  import {runAllConformance} from "../framework/mcp/conformance.ts";
8
8
  import {serveMcpStdio} from "../framework/mcp/stdio.ts";
9
9
  import type {McpInvocationContext} from "../types/index.ts";
10
+ import {createDebugMcpEntry} from "../debug/mcp.ts";
11
+ import {enableCliDebug} from "../debug/cli.ts";
12
+ import {serveDebugMcpHttp} from "../debug/mcp-http.ts";
10
13
 
11
14
  interface ListOptions {
12
15
  json?: boolean;
@@ -31,6 +34,15 @@ interface ConformanceOptions {
31
34
  json?: boolean;
32
35
  }
33
36
 
37
+ interface DebugOptions {
38
+ stdio?: boolean;
39
+ http?: boolean;
40
+ port?: string;
41
+ hostname?: string;
42
+ token?: string;
43
+ json?: boolean;
44
+ }
45
+
34
46
  function parseArgs(value?: string): Record<string, any> {
35
47
  if (!value) return {};
36
48
  try {
@@ -89,6 +101,17 @@ export default class McpCommand extends RaitonCommand {
89
101
  .description("Run the shared HTTP and stdio MCP conformance suite")
90
102
  .option("--json", "Emit JSON on stdout")
91
103
  .action((server: string | undefined, options: ConformanceOptions) => this.conformance(server, options).catch(error => fail(error, options.json)));
104
+
105
+ command
106
+ .command("debug")
107
+ .description("Serve the AI-assisted debug MCP server (stdio or HTTP)")
108
+ .option("--stdio", "Serve newline-delimited JSON-RPC over stdin/stdout")
109
+ .option("--http", "Serve streamable HTTP on a local port")
110
+ .option("--port <port>", "HTTP port", "5711")
111
+ .option("--hostname <host>", "HTTP host", "127.0.0.1")
112
+ .option("--token <token>", "Token required by the HTTP transport")
113
+ .option("--json", "Emit JSON (not compatible with a long-running server)")
114
+ .action((options: DebugOptions) => this.debug(options).catch(error => fail(error, options.json)));
92
115
  }
93
116
 
94
117
  private async list(options: ListOptions): Promise<void> {
@@ -255,4 +278,45 @@ export default class McpCommand extends RaitonCommand {
255
278
 
256
279
  if (!passed) process.exitCode = ExitCode.DIAGNOSTIC_FAILED;
257
280
  }
281
+
282
+ private async debug(options: DebugOptions): Promise<void> {
283
+ if (options.json) {
284
+ throw new CliError("`mcp debug` is a long-running server and cannot emit a single JSON document", {
285
+ code: "INVALID_OPTION",
286
+ hint: "Omit --json when serving the debug MCP server.",
287
+ exitCode: ExitCode.USAGE,
288
+ });
289
+ }
290
+
291
+ const {application} = await loadProject(this.workdir, true);
292
+ const runtime = enableCliDebug(application, this.workdir);
293
+ const entry = createDebugMcpEntry(runtime.config.mcp.path);
294
+ const scopes = ["debug:read", "debug:call", "debug:replay", "debug:admin"];
295
+ const context: McpInvocationContext = {
296
+ actor: "raiton-debug-cli",
297
+ transport: "stdio",
298
+ scopes,
299
+ };
300
+
301
+ if (options.http) {
302
+ const port = Number(options.port ?? 5711);
303
+ const server = await serveDebugMcpHttp(entry, {
304
+ hostname: options.hostname,
305
+ port,
306
+ token: options.token,
307
+ scopes,
308
+ });
309
+ process.stderr.write(`[raiton:debug] MCP HTTP listening on ${server.url}\n`);
310
+ await new Promise<void>(resolve => {
311
+ const stop = () => resolve();
312
+ process.once("SIGINT", stop);
313
+ process.once("SIGTERM", stop);
314
+ });
315
+ await server.close();
316
+ return;
317
+ }
318
+
319
+ process.stderr.write("[raiton:debug] serving debug MCP over stdio\n");
320
+ await serveMcpStdio(entry, {context});
321
+ }
258
322
  }