padrone 1.4.0 → 1.5.0

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 (82) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +105 -284
  3. package/dist/{args-CVDbyyzG.mjs → args-D5PNDyNu.mjs} +41 -18
  4. package/dist/args-D5PNDyNu.mjs.map +1 -0
  5. package/dist/chunk-CjcI7cDX.mjs +15 -0
  6. package/dist/codegen/index.d.mts +28 -3
  7. package/dist/codegen/index.d.mts.map +1 -1
  8. package/dist/codegen/index.mjs +169 -19
  9. package/dist/codegen/index.mjs.map +1 -1
  10. package/dist/command-utils-B1D-HqCd.mjs +1117 -0
  11. package/dist/command-utils-B1D-HqCd.mjs.map +1 -0
  12. package/dist/completion.d.mts +1 -1
  13. package/dist/completion.d.mts.map +1 -1
  14. package/dist/completion.mjs +77 -29
  15. package/dist/completion.mjs.map +1 -1
  16. package/dist/docs/index.d.mts +22 -2
  17. package/dist/docs/index.d.mts.map +1 -1
  18. package/dist/docs/index.mjs +94 -7
  19. package/dist/docs/index.mjs.map +1 -1
  20. package/dist/errors-BiVrBgi6.mjs +114 -0
  21. package/dist/errors-BiVrBgi6.mjs.map +1 -0
  22. package/dist/{formatter-ClUK5hcQ.d.mts → formatter-DtHzbP22.d.mts} +34 -5
  23. package/dist/formatter-DtHzbP22.d.mts.map +1 -0
  24. package/dist/help-bbmu9-qd.mjs +735 -0
  25. package/dist/help-bbmu9-qd.mjs.map +1 -0
  26. package/dist/index.d.mts +32 -3
  27. package/dist/index.d.mts.map +1 -1
  28. package/dist/index.mjs +493 -265
  29. package/dist/index.mjs.map +1 -1
  30. package/dist/mcp-mLWIdUIu.mjs +379 -0
  31. package/dist/mcp-mLWIdUIu.mjs.map +1 -0
  32. package/dist/serve-B0u43DK7.mjs +404 -0
  33. package/dist/serve-B0u43DK7.mjs.map +1 -0
  34. package/dist/stream-BcC146Ud.mjs +56 -0
  35. package/dist/stream-BcC146Ud.mjs.map +1 -0
  36. package/dist/test.d.mts +1 -1
  37. package/dist/test.mjs +4 -15
  38. package/dist/test.mjs.map +1 -1
  39. package/dist/{types-DjIdJN5G.d.mts → types-Ch8Mk6Qb.d.mts} +310 -62
  40. package/dist/types-Ch8Mk6Qb.d.mts.map +1 -0
  41. package/dist/{update-check-EbNDkzyV.mjs → update-check-CFX1FV3v.mjs} +2 -2
  42. package/dist/{update-check-EbNDkzyV.mjs.map → update-check-CFX1FV3v.mjs.map} +1 -1
  43. package/dist/zod.d.mts +32 -0
  44. package/dist/zod.d.mts.map +1 -0
  45. package/dist/zod.mjs +50 -0
  46. package/dist/zod.mjs.map +1 -0
  47. package/package.json +10 -2
  48. package/src/args.ts +68 -40
  49. package/src/cli/docs.ts +1 -7
  50. package/src/cli/doctor.ts +195 -10
  51. package/src/cli/index.ts +1 -1
  52. package/src/cli/init.ts +2 -3
  53. package/src/cli/link.ts +2 -2
  54. package/src/codegen/discovery.ts +80 -28
  55. package/src/codegen/index.ts +2 -1
  56. package/src/codegen/parsers/bash.ts +179 -0
  57. package/src/codegen/schema-to-code.ts +2 -1
  58. package/src/colorizer.ts +126 -13
  59. package/src/command-utils.ts +380 -30
  60. package/src/completion.ts +120 -47
  61. package/src/create.ts +480 -128
  62. package/src/docs/index.ts +122 -8
  63. package/src/formatter.ts +171 -125
  64. package/src/help.ts +45 -12
  65. package/src/index.ts +29 -1
  66. package/src/interactive.ts +45 -4
  67. package/src/mcp.ts +390 -0
  68. package/src/repl-loop.ts +16 -3
  69. package/src/runtime.ts +195 -2
  70. package/src/serve.ts +442 -0
  71. package/src/stream.ts +75 -0
  72. package/src/test.ts +7 -16
  73. package/src/type-utils.ts +28 -4
  74. package/src/types.ts +212 -30
  75. package/src/wrap.ts +23 -25
  76. package/src/zod.ts +50 -0
  77. package/dist/args-CVDbyyzG.mjs.map +0 -1
  78. package/dist/chunk-y_GBKt04.mjs +0 -5
  79. package/dist/formatter-ClUK5hcQ.d.mts.map +0 -1
  80. package/dist/help-CcBe91bV.mjs +0 -1254
  81. package/dist/help-CcBe91bV.mjs.map +0 -1
  82. package/dist/types-DjIdJN5G.d.mts.map +0 -1
package/src/index.ts CHANGED
@@ -1,10 +1,24 @@
1
+ export type { AnsiStyle, ColorConfig, ColorTheme } from './colorizer.ts';
2
+ export { colorThemes } from './colorizer.ts';
1
3
  export { asyncSchema, buildReplCompleter, createPadrone } from './create.ts';
2
4
  export type { PadroneErrorOptions } from './errors.ts';
3
5
  export { ActionError, ConfigError, PadroneError, RoutingError, ValidationError } from './errors.ts';
4
6
  export type { HelpInfo } from './formatter.ts';
5
- export type { InteractiveMode, InteractivePromptConfig, PadroneRuntime } from './runtime.ts';
7
+ export type { PadroneMcpPreferences } from './mcp.ts';
8
+ export type {
9
+ InteractiveMode,
10
+ InteractivePromptConfig,
11
+ PadroneProgressIndicator,
12
+ PadroneProgressOptions,
13
+ PadroneRuntime,
14
+ PadroneSpinnerConfig,
15
+ PadroneSpinnerPreset,
16
+ } from './runtime.ts';
6
17
  export { REPL_SIGINT } from './runtime.ts';
18
+ export type { AsyncStreamMeta } from './stream.ts';
19
+ export { asyncStream } from './stream.ts';
7
20
  export type { InferArgsInput, InferArgsOutput, InferCommand } from './type-helpers.ts';
21
+ export type { Drained } from './type-utils.ts';
8
22
  export type {
9
23
  AnyPadroneBuilder,
10
24
  AnyPadroneCommand,
@@ -14,10 +28,24 @@ export type {
14
28
  PadroneBuilder,
15
29
  PadroneCommand,
16
30
  PadroneCommandResult,
31
+ PadroneDrainResult,
17
32
  PadroneParseResult,
18
33
  PadronePlugin,
19
34
  PadroneProgram,
35
+ PadroneProgressMessage,
36
+ PadroneProgressPrefs as PadroneProgressConfig,
20
37
  PadroneSchema,
38
+ PluginBaseContext,
39
+ PluginErrorContext,
40
+ PluginErrorResult,
41
+ PluginExecuteContext,
42
+ PluginExecuteResult,
43
+ PluginParseContext,
44
+ PluginParseResult,
45
+ PluginShutdownContext,
46
+ PluginStartContext,
47
+ PluginValidateContext,
48
+ PluginValidateResult,
21
49
  } from './types.ts';
22
50
  export type { UpdateCheckConfig } from './update-check.ts';
23
51
  export type { WrapConfig, WrapResult } from './wrap.ts';
@@ -1,3 +1,4 @@
1
+ import { JSON_SCHEMA_OPTS } from './args.ts';
1
2
  import type { InteractivePromptConfig, ResolvedPadroneRuntime } from './runtime.ts';
2
3
  import type { AnyPadroneCommand } from './types.ts';
3
4
 
@@ -44,6 +45,46 @@ export function detectPromptConfig(
44
45
  return { name, message, type: 'input', default: propSchema.default };
45
46
  }
46
47
 
48
+ /**
49
+ * Prompt a single field and validate it against the command's schema.
50
+ * Re-prompts with a warning until the user provides a valid value.
51
+ */
52
+ async function promptWithValidation(
53
+ field: string,
54
+ config: InteractivePromptConfig,
55
+ currentData: Record<string, unknown>,
56
+ command: AnyPadroneCommand,
57
+ runtime: ResolvedPadroneRuntime,
58
+ ): Promise<unknown> {
59
+ let promptConfig = config;
60
+
61
+ // eslint-disable-next-line no-constant-condition
62
+ while (true) {
63
+ const value = await runtime.prompt!(promptConfig);
64
+
65
+ if (!command.argsSchema) return value;
66
+
67
+ // Validate the full object with the new value to catch field-level issues
68
+ const testData = { ...currentData, [field]: value };
69
+ const validated = await command.argsSchema['~standard'].validate(testData);
70
+
71
+ if (!validated.issues) return value;
72
+
73
+ // Only keep issues whose path starts with this field
74
+ const fieldIssues = validated.issues.filter((issue: { path?: ReadonlyArray<PropertyKey> }) => {
75
+ const rootKey = issue.path?.[0];
76
+ return rootKey !== undefined && String(rootKey) === field;
77
+ });
78
+
79
+ if (fieldIssues.length === 0) return value;
80
+
81
+ // Warn the user and re-prompt with the invalid value as default
82
+ const messages = fieldIssues.map((i: { message: string }) => i.message).join('; ');
83
+ runtime.error(`Invalid value for "${field}": ${messages}`);
84
+ promptConfig = { ...config, default: value };
85
+ }
86
+ }
87
+
47
88
  /**
48
89
  * Prompt for missing interactive fields.
49
90
  * Runs after env/config preprocessing and before schema validation.
@@ -69,7 +110,7 @@ export async function promptInteractiveFields(
69
110
  let requiredFields: Set<string> = new Set();
70
111
  if (command.argsSchema) {
71
112
  try {
72
- const jsonSchema = command.argsSchema['~standard'].jsonSchema.input({ target: 'draft-2020-12' }) as Record<string, any>;
113
+ const jsonSchema = command.argsSchema['~standard'].jsonSchema.input(JSON_SCHEMA_OPTS) as Record<string, any>;
73
114
  if (jsonSchema.type === 'object' && jsonSchema.properties) {
74
115
  jsonProperties = jsonSchema.properties;
75
116
  }
@@ -108,14 +149,14 @@ export async function promptInteractiveFields(
108
149
  }
109
150
  }
110
151
 
111
- // Prompt each required interactive field
152
+ // Prompt each required interactive field with per-field validation
112
153
  for (const field of fieldsToPrompt) {
113
154
  const config = detectPromptConfig(field, jsonProperties[field], fieldDescriptions[field]);
114
155
  // When forced, use the current value as the default
115
156
  if (force && result[field] !== undefined) {
116
157
  config.default = result[field];
117
158
  }
118
- result[field] = await runtime.prompt(config);
159
+ result[field] = await promptWithValidation(field, config, result, command, runtime);
119
160
  }
120
161
 
121
162
  // Determine optional interactive fields
@@ -160,7 +201,7 @@ export async function promptInteractiveFields(
160
201
  if (force && result[field] !== undefined) {
161
202
  config.default = result[field];
162
203
  }
163
- result[field] = await runtime.prompt(config);
204
+ result[field] = await promptWithValidation(field, config, result, command, runtime);
164
205
  }
165
206
  }
166
207
  }
package/src/mcp.ts ADDED
@@ -0,0 +1,390 @@
1
+ import { buildInputSchema, collectEndpoints, serializeArgsToFlags } from './command-utils.ts';
2
+ import { generateHelp } from './help.ts';
3
+ import type { AnyPadroneCommand, AnyPadroneProgram } from './types.ts';
4
+
5
+ export type PadroneMcpPreferences = {
6
+ /** Server name. Defaults to the program name. */
7
+ name?: string;
8
+ /** Server version. Defaults to the program version. */
9
+ version?: string;
10
+ /**
11
+ * Transport mode.
12
+ * - `'http'` — Start a Streamable HTTP server (default). Responds with `application/json` or `text/event-stream` based on the client's `Accept` header. Use `port` and `host` to configure.
13
+ * - `'stdio'` — Communicate over stdin/stdout with newline-delimited JSON.
14
+ */
15
+ transport?: 'http' | 'stdio';
16
+ /** HTTP port. Defaults to `3000`. Only used with `transport: 'http'`. */
17
+ port?: number;
18
+ /** HTTP host. Defaults to `'127.0.0.1'`. Only used with `transport: 'http'`. */
19
+ host?: string;
20
+ /** Base path for the MCP endpoint. Defaults to `'/mcp'`. Only used with `transport: 'http'`. */
21
+ basePath?: string;
22
+ /** CORS allowed origin. Defaults to `'*'`. Set to a specific origin or `false` to disable CORS headers. Only used with HTTP transports. */
23
+ cors?: string | false;
24
+ };
25
+
26
+ const PROTOCOL_VERSION = '2025-11-25';
27
+
28
+ type JsonRpcRequest = {
29
+ jsonrpc: '2.0';
30
+ id?: string | number;
31
+ method: string;
32
+ params?: Record<string, unknown>;
33
+ };
34
+
35
+ type JsonRpcResponse = {
36
+ jsonrpc: '2.0';
37
+ id: string | number | null;
38
+ result?: unknown;
39
+ error?: { code: number; message: string; data?: unknown };
40
+ };
41
+
42
+ /** Convert an endpoint dot-path to a valid MCP tool name. Spec allows: [A-Za-z0-9_\-\.] */
43
+ function toToolName(path: string): string {
44
+ return path.replace(/\s+/g, '.');
45
+ }
46
+
47
+ /** Convert a tool name back to a command path (dot → space). */
48
+ function toCommandPath(toolName: string): string {
49
+ return toolName.replace(/\./g, ' ');
50
+ }
51
+
52
+ /** Build MCP tool annotations from a command's metadata. */
53
+ function buildAnnotations(cmd: AnyPadroneCommand) {
54
+ if (cmd.mutation == null) return undefined;
55
+ return {
56
+ destructiveHint: cmd.mutation || undefined,
57
+ readOnlyHint: cmd.mutation === false || undefined,
58
+ };
59
+ }
60
+
61
+ /** Build an MCP tool definition from a command. */
62
+ function buildToolDefinition(name: string, cmd: AnyPadroneCommand) {
63
+ return {
64
+ name: toToolName(name),
65
+ title: cmd.title ?? undefined,
66
+ description: cmd.description || cmd.title || `Run the "${name}" command`,
67
+ inputSchema: buildInputSchema(cmd),
68
+ annotations: buildAnnotations(cmd),
69
+ };
70
+ }
71
+
72
+ /** Create the MCP request handler. Returns an async function that processes a JSON-RPC request and returns a response (or undefined for notifications). */
73
+ export function createMcpHandler(
74
+ existingCommand: AnyPadroneCommand,
75
+ evalCommand: AnyPadroneProgram['eval'],
76
+ prefs?: PadroneMcpPreferences,
77
+ ) {
78
+ const serverName = prefs?.name ?? existingCommand.name;
79
+ const serverVersion = prefs?.version ?? existingCommand.version ?? '0.0.0';
80
+
81
+ const rootTools = collectEndpoints(existingCommand.commands, '');
82
+ if (existingCommand.action || existingCommand.argsSchema) {
83
+ rootTools.unshift({ name: '', command: existingCommand });
84
+ }
85
+
86
+ const toolMap = new Map(rootTools.map((t) => [toToolName(t.name), t]));
87
+
88
+ const helpToolName = 'help';
89
+ const helpToolDef = {
90
+ name: helpToolName,
91
+ title: 'Help',
92
+ description: `Show help for the "${serverName}" program or a specific command`,
93
+ inputSchema: {
94
+ type: 'object' as const,
95
+ properties: { command: { type: 'string', description: 'Command name to get help for (omit for program help)' } },
96
+ additionalProperties: false,
97
+ },
98
+ };
99
+
100
+ return async function handleRequest(req: JsonRpcRequest): Promise<JsonRpcResponse | undefined> {
101
+ const { id, method, params } = req;
102
+
103
+ switch (method) {
104
+ case 'initialize':
105
+ return {
106
+ jsonrpc: '2.0',
107
+ id: id ?? null,
108
+ result: {
109
+ protocolVersion: PROTOCOL_VERSION,
110
+ capabilities: { tools: {} },
111
+ serverInfo: { name: serverName, version: serverVersion },
112
+ },
113
+ };
114
+
115
+ case 'notifications/initialized':
116
+ case 'notifications/cancelled':
117
+ return undefined;
118
+
119
+ case 'ping':
120
+ return { jsonrpc: '2.0', id: id ?? null, result: {} };
121
+
122
+ case 'tools/list': {
123
+ const tools = [...rootTools.map((t) => buildToolDefinition(t.name, t.command)), helpToolDef];
124
+ return { jsonrpc: '2.0', id: id ?? null, result: { tools } };
125
+ }
126
+
127
+ case 'tools/call': {
128
+ const toolName = params?.name as string;
129
+ const args = (params?.arguments ?? {}) as Record<string, unknown>;
130
+
131
+ // Built-in help tool
132
+ if (toolName === helpToolName) {
133
+ const cmdName = args.command as string | undefined;
134
+ const targetCmd = cmdName ? rootTools.find((t) => t.name === cmdName || toToolName(t.name) === cmdName)?.command : undefined;
135
+ const helpText = generateHelp(existingCommand, targetCmd ?? existingCommand, { format: 'text', detail: 'full' });
136
+ return {
137
+ jsonrpc: '2.0',
138
+ id: id ?? null,
139
+ result: { content: [{ type: 'text', text: helpText }], isError: false },
140
+ };
141
+ }
142
+
143
+ const tool = toolMap.get(toolName);
144
+ if (!tool) {
145
+ return {
146
+ jsonrpc: '2.0',
147
+ id: id ?? null,
148
+ error: { code: -32602, message: `Unknown tool: ${toolName}` },
149
+ };
150
+ }
151
+
152
+ // Build command string: convert tool name back to command path + serialize args as flags
153
+ const commandPath = toCommandPath(tool.name);
154
+ const argParts = serializeArgsToFlags(args);
155
+ const input = [commandPath, ...argParts].filter(Boolean).join(' ') || undefined;
156
+
157
+ try {
158
+ const output: string[] = [];
159
+ const errors: string[] = [];
160
+ const result = await evalCommand(input as any, {
161
+ autoOutput: false,
162
+ runtime: {
163
+ output: (...outArgs: unknown[]) => output.push(outArgs.map(String).join(' ')),
164
+ error: (text: string) => errors.push(text),
165
+ interactive: 'unsupported',
166
+ format: 'text',
167
+ },
168
+ });
169
+
170
+ const content: { type: string; text: string }[] = [];
171
+
172
+ if (result.error) {
173
+ const errorMsg = result.error instanceof Error ? result.error.message : String(result.error);
174
+ if (errors.length) content.push({ type: 'text', text: errors.join('\n') });
175
+ content.push({ type: 'text', text: errorMsg });
176
+ return { jsonrpc: '2.0', id: id ?? null, result: { content, isError: true } };
177
+ }
178
+
179
+ if (result.argsResult?.issues) {
180
+ const issueMessages = result.argsResult.issues.map((i: any) => `${i.path?.join('.') || 'root'}: ${i.message}`).join('\n');
181
+ content.push({ type: 'text', text: `Validation error:\n${issueMessages}` });
182
+ return { jsonrpc: '2.0', id: id ?? null, result: { content, isError: true } };
183
+ }
184
+
185
+ if (output.length) content.push({ type: 'text', text: output.join('\n') });
186
+ if (result.result !== undefined && result.result !== null) {
187
+ const resultText = typeof result.result === 'string' ? result.result : JSON.stringify(result.result, null, 2);
188
+ content.push({ type: 'text', text: resultText });
189
+ }
190
+ if (content.length === 0) content.push({ type: 'text', text: 'Done.' });
191
+ return { jsonrpc: '2.0', id: id ?? null, result: { content, isError: false } };
192
+ } catch (err) {
193
+ const errorMsg = err instanceof Error ? err.message : String(err);
194
+ return {
195
+ jsonrpc: '2.0',
196
+ id: id ?? null,
197
+ result: { content: [{ type: 'text', text: errorMsg }], isError: true },
198
+ };
199
+ }
200
+ }
201
+
202
+ default: {
203
+ if (id !== undefined) {
204
+ return { jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } };
205
+ }
206
+ return undefined;
207
+ }
208
+ }
209
+ };
210
+ }
211
+
212
+ /** stdio transport: newline-delimited JSON per 2025-11-25 spec. */
213
+ async function startStdioTransport(handleRequest: (req: JsonRpcRequest) => Promise<JsonRpcResponse | undefined>): Promise<void> {
214
+ const { stdin, stdout } = await import('node:process');
215
+ const { createInterface } = await import('node:readline');
216
+
217
+ function send(msg: JsonRpcResponse) {
218
+ stdout.write(`${JSON.stringify(msg)}\n`);
219
+ }
220
+
221
+ const rl = createInterface({ input: stdin, crlfDelay: Infinity });
222
+
223
+ for await (const line of rl) {
224
+ if (!line.trim()) continue;
225
+ try {
226
+ const req = JSON.parse(line) as JsonRpcRequest;
227
+ const res = await handleRequest(req);
228
+ if (res) send(res);
229
+ } catch {
230
+ // Ignore malformed JSON
231
+ }
232
+ }
233
+ }
234
+
235
+ /** Streamable HTTP transport per 2025-11-25 spec. Responds with JSON or SSE based on client's Accept header. */
236
+ async function startHttpTransport(
237
+ handleRequest: (req: JsonRpcRequest) => Promise<JsonRpcResponse | undefined>,
238
+ prefs: PadroneMcpPreferences,
239
+ log: (msg: string) => void,
240
+ ): Promise<void> {
241
+ const http = await import('node:http');
242
+ const crypto = await import('node:crypto');
243
+
244
+ const port = prefs.port ?? 3000;
245
+ const host = prefs.host ?? '127.0.0.1';
246
+ const endpoint = prefs.basePath ?? '/mcp';
247
+
248
+ // Session management
249
+ let sessionId: string | undefined;
250
+ let negotiatedVersion: string | undefined;
251
+
252
+ const corsOrigin = prefs.cors !== false ? (prefs.cors ?? '*') : undefined;
253
+
254
+ const server = http.createServer(async (req, res) => {
255
+ // CORS headers
256
+ if (corsOrigin) {
257
+ res.setHeader('Access-Control-Allow-Origin', corsOrigin);
258
+ res.setHeader('Access-Control-Allow-Methods', 'POST, GET, DELETE, OPTIONS');
259
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type, MCP-Session-Id, MCP-Protocol-Version');
260
+ res.setHeader('Access-Control-Expose-Headers', 'MCP-Session-Id');
261
+ }
262
+
263
+ if (req.method === 'OPTIONS') {
264
+ res.writeHead(corsOrigin ? 204 : 405);
265
+ res.end();
266
+ return;
267
+ }
268
+
269
+ if (req.url !== endpoint) {
270
+ res.writeHead(404, { 'Content-Type': 'application/json' });
271
+ res.end(JSON.stringify({ error: 'Not found' }));
272
+ return;
273
+ }
274
+
275
+ // DELETE: terminate session
276
+ if (req.method === 'DELETE') {
277
+ const reqSessionId = req.headers['mcp-session-id'] as string | undefined;
278
+ if (sessionId && reqSessionId === sessionId) {
279
+ sessionId = undefined;
280
+ negotiatedVersion = undefined;
281
+ res.writeHead(200);
282
+ res.end();
283
+ } else {
284
+ res.writeHead(404);
285
+ res.end();
286
+ }
287
+ return;
288
+ }
289
+
290
+ // GET: SSE stream (not implemented — return 405)
291
+ if (req.method === 'GET') {
292
+ res.writeHead(405, { 'Content-Type': 'application/json' });
293
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32601, message: 'SSE stream not supported' } }));
294
+ return;
295
+ }
296
+
297
+ if (req.method !== 'POST') {
298
+ res.writeHead(405);
299
+ res.end();
300
+ return;
301
+ }
302
+
303
+ // Validate session ID on non-initialize requests
304
+ const reqSessionId = req.headers['mcp-session-id'] as string | undefined;
305
+ if (sessionId && reqSessionId && reqSessionId !== sessionId) {
306
+ res.writeHead(404, { 'Content-Type': 'application/json' });
307
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Invalid session' } }));
308
+ return;
309
+ }
310
+
311
+ // Validate MCP-Protocol-Version header on post-init requests
312
+ const reqProtocolVersion = req.headers['mcp-protocol-version'] as string | undefined;
313
+ if (negotiatedVersion && reqProtocolVersion && reqProtocolVersion !== negotiatedVersion) {
314
+ res.writeHead(400, { 'Content-Type': 'application/json' });
315
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Protocol version mismatch' } }));
316
+ return;
317
+ }
318
+
319
+ // Read request body
320
+ const chunks: Buffer[] = [];
321
+ for await (const chunk of req) {
322
+ chunks.push(chunk);
323
+ }
324
+ const body = Buffer.concat(chunks).toString('utf-8');
325
+
326
+ let rpcRequest: JsonRpcRequest;
327
+ try {
328
+ rpcRequest = JSON.parse(body);
329
+ } catch {
330
+ res.writeHead(400, { 'Content-Type': 'application/json' });
331
+ res.end(JSON.stringify({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }));
332
+ return;
333
+ }
334
+
335
+ const response = await handleRequest(rpcRequest);
336
+
337
+ // On initialize response: create session and set header
338
+ if (rpcRequest.method === 'initialize' && response?.result) {
339
+ sessionId = crypto.randomUUID();
340
+ negotiatedVersion = PROTOCOL_VERSION;
341
+ res.setHeader('MCP-Session-Id', sessionId);
342
+ }
343
+
344
+ if (response) {
345
+ const accept = req.headers.accept ?? '';
346
+ if (accept.includes('text/event-stream')) {
347
+ res.writeHead(200, { 'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache', Connection: 'keep-alive' });
348
+ res.write(`event: message\ndata: ${JSON.stringify(response)}\n\n`);
349
+ res.end();
350
+ } else {
351
+ res.writeHead(200, { 'Content-Type': 'application/json' });
352
+ res.end(JSON.stringify(response));
353
+ }
354
+ } else {
355
+ // Notification or response from client — no body
356
+ res.writeHead(202);
357
+ res.end();
358
+ }
359
+ });
360
+
361
+ return new Promise<void>((resolve, reject) => {
362
+ server.listen(port, host, () => {
363
+ log(`MCP server listening on http://${host}:${port}${endpoint}`);
364
+ });
365
+ server.on('error', reject);
366
+ const onSignal = () => {
367
+ server.close(() => resolve());
368
+ };
369
+ process.on('SIGINT', onSignal);
370
+ process.on('SIGTERM', onSignal);
371
+ });
372
+ }
373
+
374
+ export async function startMcpServer(
375
+ _program: AnyPadroneProgram,
376
+ existingCommand: AnyPadroneCommand,
377
+ evalCommand: AnyPadroneProgram['eval'],
378
+ prefs?: PadroneMcpPreferences,
379
+ ): Promise<void> {
380
+ const handleRequest = createMcpHandler(existingCommand, evalCommand, prefs);
381
+ const transport = prefs?.transport ?? 'http';
382
+
383
+ if (transport === 'stdio') {
384
+ return startStdioTransport(handleRequest);
385
+ }
386
+
387
+ const { getCommandRuntime } = await import('./command-utils.ts');
388
+ const runtime = getCommandRuntime(existingCommand);
389
+ return startHttpTransport(handleRequest, prefs ?? {}, (msg) => runtime.error(msg));
390
+ }
package/src/repl-loop.ts CHANGED
@@ -13,7 +13,7 @@ export type ReplDeps = {
13
13
  /**
14
14
  * Creates a REPL async iterable for running commands interactively.
15
15
  */
16
- export function createReplIterator(deps: ReplDeps, options?: PadroneReplPreferences): AsyncIterable<any> {
16
+ export function createReplIterator(deps: ReplDeps, options?: PadroneReplPreferences): AsyncIterable<any> & { drain: () => Promise<any> } {
17
17
  const { existingCommand, evalCommand, replActiveRef } = deps;
18
18
 
19
19
  if (replActiveRef.value) {
@@ -291,7 +291,10 @@ export function createReplIterator(deps: ReplDeps, options?: PadroneReplPreferen
291
291
  try {
292
292
  const replEvalPrefs: PadroneEvalPreferences | undefined = options?.autoOutput === false ? { autoOutput: false } : undefined;
293
293
  const result = await evalCommand(scopedInput, replEvalPrefs);
294
- if (result.argsResult?.issues) {
294
+ if (result.error) {
295
+ const msg = result.error instanceof Error ? result.error.message : String(result.error);
296
+ runtime.error(prefixLines ? prefixLines(msg) : msg);
297
+ } else if (result.argsResult?.issues) {
295
298
  const issueMessages = result.argsResult.issues
296
299
  .map((i: StandardSchemaV1.Issue) => ` - ${i.path?.join('.') || 'root'}: ${i.message}`)
297
300
  .join('\n');
@@ -313,5 +316,15 @@ export function createReplIterator(deps: ReplDeps, options?: PadroneReplPreferen
313
316
  }
314
317
  }
315
318
 
316
- return replIterator() as any;
319
+ const iterable = replIterator();
320
+ (iterable as any).drain = async () => {
321
+ try {
322
+ const results: any[] = [];
323
+ for await (const result of iterable) results.push(result);
324
+ return { value: results };
325
+ } catch (err) {
326
+ return { error: err };
327
+ }
328
+ };
329
+ return iterable as any;
317
330
  }