@lushly-dev/afd-server 0.1.0 → 0.3.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.
- package/LICENSE +21 -26
- package/README.md +475 -381
- package/dist/bootstrap/afd-docs.d.ts +1 -1
- package/dist/bootstrap/afd-docs.d.ts.map +1 -1
- package/dist/bootstrap/afd-docs.js +3 -3
- package/dist/bootstrap/afd-docs.js.map +1 -1
- package/dist/bootstrap/afd-help.d.ts +2 -1
- package/dist/bootstrap/afd-help.d.ts.map +1 -1
- package/dist/bootstrap/afd-help.js +4 -3
- package/dist/bootstrap/afd-help.js.map +1 -1
- package/dist/bootstrap/afd-schema.d.ts +1 -1
- package/dist/bootstrap/afd-schema.d.ts.map +1 -1
- package/dist/bootstrap/afd-schema.js +13 -13
- package/dist/bootstrap/afd-schema.js.map +1 -1
- package/dist/bootstrap/index.d.ts +1 -1
- package/dist/bootstrap/index.js +1 -1
- package/dist/bootstrap/registry.d.ts.map +1 -1
- package/dist/bootstrap/registry.js +3 -1
- package/dist/bootstrap/registry.js.map +1 -1
- package/dist/handoff-schema.d.ts +245 -0
- package/dist/handoff-schema.d.ts.map +1 -0
- package/dist/handoff-schema.js +97 -0
- package/dist/handoff-schema.js.map +1 -0
- package/dist/index.d.ts +8 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -8
- package/dist/index.js.map +1 -1
- package/dist/middleware.d.ts +217 -3
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +266 -4
- package/dist/middleware.js.map +1 -1
- package/dist/schema.d.ts +49 -4
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +37 -4
- package/dist/schema.js.map +1 -1
- package/dist/server.d.ts +11 -9
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +539 -161
- package/dist/server.js.map +1 -1
- package/dist/validation.d.ts +68 -79
- package/dist/validation.d.ts.map +1 -1
- package/dist/validation.js +96 -102
- package/dist/validation.js.map +1 -1
- package/package.json +18 -4
package/dist/server.js
CHANGED
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
* This module provides utilities for creating MCP-compliant servers
|
|
5
5
|
* from Zod-defined commands.
|
|
6
6
|
*/
|
|
7
|
-
import { createServer } from
|
|
8
|
-
import {
|
|
9
|
-
import { Server as McpSdkServer } from
|
|
10
|
-
import { StdioServerTransport } from
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
7
|
+
import { createServer } from 'node:http';
|
|
8
|
+
import { aggregatePipelineAlternatives, aggregatePipelineConfidence, aggregatePipelineReasoning, aggregatePipelineSources, aggregatePipelineWarnings, buildConfidenceBreakdown, createBatchResult, createCompleteChunk, createErrorChunk, createFailedBatchResult, evaluateCondition, failure, isBatchRequest, isPipelineRequest, resolveVariables, } from '@lushly-dev/afd-core';
|
|
9
|
+
import { Server as McpSdkServer } from '@modelcontextprotocol/sdk/server/index.js';
|
|
10
|
+
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
11
|
+
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
12
|
+
import { formatEnhancedValidationError, validateInputEnhanced } from './validation.js';
|
|
13
13
|
/**
|
|
14
14
|
* Detect whether stdin is being piped (non-TTY).
|
|
15
15
|
* Used for auto-detection of transport mode.
|
|
@@ -40,10 +40,10 @@ export function isStdinPiped() {
|
|
|
40
40
|
* ```
|
|
41
41
|
*/
|
|
42
42
|
export function createMcpServer(options) {
|
|
43
|
-
const { name, version, commands, port = 3100, host =
|
|
43
|
+
const { name, version, commands, port = 3100, host = 'localhost', devMode = false,
|
|
44
44
|
// In dev mode, CORS is permissive by default; in production, it's off by default
|
|
45
|
-
cors = devMode, transport =
|
|
46
|
-
middleware = [], onCommand, onError, toolStrategy =
|
|
45
|
+
cors = devMode, transport = 'auto', stdio, // deprecated, for backward compatibility
|
|
46
|
+
middleware = [], onCommand, onError, toolStrategy = 'grouped', groupByFn, } = options;
|
|
47
47
|
// Resolve transport mode
|
|
48
48
|
// - If explicit transport is set, use it
|
|
49
49
|
// - If deprecated stdio option is set, use it for backward compatibility
|
|
@@ -51,18 +51,18 @@ export function createMcpServer(options) {
|
|
|
51
51
|
function resolveTransport() {
|
|
52
52
|
// Handle deprecated stdio option for backward compatibility
|
|
53
53
|
if (stdio !== undefined) {
|
|
54
|
-
return stdio ?
|
|
54
|
+
return stdio ? 'stdio' : 'http';
|
|
55
55
|
}
|
|
56
56
|
// Auto-detect: use stdio if stdin is piped (not a TTY), otherwise use HTTP
|
|
57
|
-
if (transport ===
|
|
58
|
-
return isStdinPiped() ?
|
|
57
|
+
if (transport === 'auto') {
|
|
58
|
+
return isStdinPiped() ? 'stdio' : 'http';
|
|
59
59
|
}
|
|
60
60
|
// Explicit transport mode (stdio or http)
|
|
61
61
|
return transport;
|
|
62
62
|
}
|
|
63
63
|
const resolvedTransport = resolveTransport();
|
|
64
|
-
const useStdio = resolvedTransport ===
|
|
65
|
-
const useHttp = resolvedTransport ===
|
|
64
|
+
const useStdio = resolvedTransport === 'stdio';
|
|
65
|
+
const useHttp = resolvedTransport === 'http';
|
|
66
66
|
// Build command map for quick lookup
|
|
67
67
|
const commandMap = new Map();
|
|
68
68
|
for (const cmd of commands) {
|
|
@@ -81,19 +81,28 @@ export function createMcpServer(options) {
|
|
|
81
81
|
const command = commandMap.get(commandName);
|
|
82
82
|
if (!command) {
|
|
83
83
|
return failure({
|
|
84
|
-
code:
|
|
84
|
+
code: 'COMMAND_NOT_FOUND',
|
|
85
85
|
message: `Command '${commandName}' not found`,
|
|
86
|
-
suggestion: `Available commands: ${Array.from(commandMap.keys()).join(
|
|
86
|
+
suggestion: `Available commands: ${Array.from(commandMap.keys()).join(', ')}`,
|
|
87
87
|
});
|
|
88
88
|
}
|
|
89
|
-
// Validate input
|
|
90
|
-
const validation =
|
|
89
|
+
// Validate input with enhanced error messages
|
|
90
|
+
const validation = validateInputEnhanced(command.inputSchema, input);
|
|
91
91
|
if (!validation.success) {
|
|
92
92
|
return failure({
|
|
93
|
-
code:
|
|
94
|
-
message:
|
|
95
|
-
suggestion: validation.errors
|
|
96
|
-
|
|
93
|
+
code: 'VALIDATION_ERROR',
|
|
94
|
+
message: 'Input validation failed',
|
|
95
|
+
suggestion: formatEnhancedValidationError(validation.errors, {
|
|
96
|
+
expectedFields: validation.expectedFields,
|
|
97
|
+
unexpectedFields: validation.unexpectedFields,
|
|
98
|
+
missingFields: validation.missingFields,
|
|
99
|
+
}),
|
|
100
|
+
details: {
|
|
101
|
+
errors: validation.errors,
|
|
102
|
+
expectedFields: validation.expectedFields,
|
|
103
|
+
unexpectedFields: validation.unexpectedFields,
|
|
104
|
+
missingFields: validation.missingFields,
|
|
105
|
+
},
|
|
97
106
|
});
|
|
98
107
|
}
|
|
99
108
|
// Build middleware chain
|
|
@@ -115,6 +124,8 @@ export function createMcpServer(options) {
|
|
|
115
124
|
let next = runHandler;
|
|
116
125
|
for (let i = middleware.length - 1; i >= 0; i--) {
|
|
117
126
|
const mw = middleware[i];
|
|
127
|
+
if (!mw)
|
|
128
|
+
continue;
|
|
118
129
|
const currentNext = next;
|
|
119
130
|
next = () => mw(commandName, validation.data, context, currentNext);
|
|
120
131
|
}
|
|
@@ -127,11 +138,11 @@ export function createMcpServer(options) {
|
|
|
127
138
|
const err = error instanceof Error ? error : new Error(String(error));
|
|
128
139
|
onError?.(err);
|
|
129
140
|
return failure({
|
|
130
|
-
code:
|
|
131
|
-
message: devMode ? err.message :
|
|
141
|
+
code: 'COMMAND_EXECUTION_ERROR',
|
|
142
|
+
message: devMode ? err.message : 'An internal error occurred',
|
|
132
143
|
suggestion: devMode
|
|
133
|
-
?
|
|
134
|
-
:
|
|
144
|
+
? 'Check the command implementation'
|
|
145
|
+
: 'Contact support if this persists',
|
|
135
146
|
// Only include stack traces in dev mode to prevent information leakage
|
|
136
147
|
...(devMode ? { details: { stack: err.stack } } : {}),
|
|
137
148
|
});
|
|
@@ -146,9 +157,9 @@ export function createMcpServer(options) {
|
|
|
146
157
|
// Validate request
|
|
147
158
|
if (!request.commands || request.commands.length === 0) {
|
|
148
159
|
return createFailedBatchResult({
|
|
149
|
-
code:
|
|
150
|
-
message:
|
|
151
|
-
suggestion:
|
|
160
|
+
code: 'INVALID_BATCH_REQUEST',
|
|
161
|
+
message: 'Batch request must contain at least one command',
|
|
162
|
+
suggestion: 'Provide an array of commands to execute',
|
|
152
163
|
}, { startedAt });
|
|
153
164
|
}
|
|
154
165
|
const options = request.options ?? {};
|
|
@@ -157,6 +168,8 @@ export function createMcpServer(options) {
|
|
|
157
168
|
// Execute commands sequentially
|
|
158
169
|
for (let i = 0; i < request.commands.length; i++) {
|
|
159
170
|
const cmd = request.commands[i];
|
|
171
|
+
if (!cmd)
|
|
172
|
+
continue;
|
|
160
173
|
if (stopped) {
|
|
161
174
|
results.push({
|
|
162
175
|
id: cmd.id ?? `cmd-${i}`,
|
|
@@ -165,8 +178,8 @@ export function createMcpServer(options) {
|
|
|
165
178
|
result: {
|
|
166
179
|
success: false,
|
|
167
180
|
error: {
|
|
168
|
-
code:
|
|
169
|
-
message:
|
|
181
|
+
code: 'COMMAND_SKIPPED',
|
|
182
|
+
message: 'Command skipped due to previous error (stopOnError enabled)',
|
|
170
183
|
},
|
|
171
184
|
},
|
|
172
185
|
durationMs: 0,
|
|
@@ -193,6 +206,8 @@ export function createMcpServer(options) {
|
|
|
193
206
|
if (options.timeout && performance.now() - startTime > options.timeout) {
|
|
194
207
|
for (let j = i + 1; j < request.commands.length; j++) {
|
|
195
208
|
const remainingCmd = request.commands[j];
|
|
209
|
+
if (!remainingCmd)
|
|
210
|
+
continue;
|
|
196
211
|
results.push({
|
|
197
212
|
id: remainingCmd.id ?? `cmd-${j}`,
|
|
198
213
|
index: j,
|
|
@@ -200,7 +215,7 @@ export function createMcpServer(options) {
|
|
|
200
215
|
result: {
|
|
201
216
|
success: false,
|
|
202
217
|
error: {
|
|
203
|
-
code:
|
|
218
|
+
code: 'BATCH_TIMEOUT',
|
|
204
219
|
message: `Batch timeout exceeded (${options.timeout}ms)`,
|
|
205
220
|
retryable: true,
|
|
206
221
|
},
|
|
@@ -215,9 +230,7 @@ export function createMcpServer(options) {
|
|
|
215
230
|
const totalMs = performance.now() - startTime;
|
|
216
231
|
const timing = {
|
|
217
232
|
totalMs: Math.round(totalMs * 100) / 100,
|
|
218
|
-
averageMs: results.length > 0
|
|
219
|
-
? Math.round((totalMs / results.length) * 100) / 100
|
|
220
|
-
: 0,
|
|
233
|
+
averageMs: results.length > 0 ? Math.round((totalMs / results.length) * 100) / 100 : 0,
|
|
221
234
|
startedAt,
|
|
222
235
|
completedAt,
|
|
223
236
|
};
|
|
@@ -225,6 +238,165 @@ export function createMcpServer(options) {
|
|
|
225
238
|
traceId: context.traceId ?? `batch-${Date.now()}`,
|
|
226
239
|
});
|
|
227
240
|
}
|
|
241
|
+
/**
|
|
242
|
+
* Execute a pipeline of chained commands with variable resolution.
|
|
243
|
+
*/
|
|
244
|
+
async function executePipeline(request, context = {}) {
|
|
245
|
+
const startTime = performance.now();
|
|
246
|
+
const pipelineId = request.id ?? `pipeline-${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
247
|
+
// Validate request
|
|
248
|
+
if (!request.steps || request.steps.length === 0) {
|
|
249
|
+
return {
|
|
250
|
+
data: undefined,
|
|
251
|
+
metadata: {
|
|
252
|
+
confidence: 0,
|
|
253
|
+
confidenceBreakdown: [],
|
|
254
|
+
reasoning: [],
|
|
255
|
+
warnings: [],
|
|
256
|
+
sources: [],
|
|
257
|
+
alternatives: [],
|
|
258
|
+
executionTimeMs: 0,
|
|
259
|
+
completedSteps: 0,
|
|
260
|
+
totalSteps: 0,
|
|
261
|
+
},
|
|
262
|
+
steps: [],
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
const pipelineContext = {
|
|
266
|
+
pipelineInput: context,
|
|
267
|
+
previousResult: undefined,
|
|
268
|
+
steps: [],
|
|
269
|
+
};
|
|
270
|
+
const stepResults = [];
|
|
271
|
+
const options = request.options ?? {};
|
|
272
|
+
let stopped = false;
|
|
273
|
+
for (let i = 0; i < request.steps.length; i++) {
|
|
274
|
+
const step = request.steps[i];
|
|
275
|
+
if (!step)
|
|
276
|
+
continue;
|
|
277
|
+
const stepStartTime = performance.now();
|
|
278
|
+
// Check if pipeline was stopped by a previous failure
|
|
279
|
+
if (stopped) {
|
|
280
|
+
stepResults.push({
|
|
281
|
+
index: i,
|
|
282
|
+
alias: step.as,
|
|
283
|
+
command: step.command,
|
|
284
|
+
status: 'skipped',
|
|
285
|
+
executionTimeMs: 0,
|
|
286
|
+
});
|
|
287
|
+
continue;
|
|
288
|
+
}
|
|
289
|
+
// Evaluate when condition if present
|
|
290
|
+
if (step.when && !evaluateCondition(step.when, pipelineContext)) {
|
|
291
|
+
stepResults.push({
|
|
292
|
+
index: i,
|
|
293
|
+
alias: step.as,
|
|
294
|
+
command: step.command,
|
|
295
|
+
status: 'skipped',
|
|
296
|
+
executionTimeMs: 0,
|
|
297
|
+
});
|
|
298
|
+
continue;
|
|
299
|
+
}
|
|
300
|
+
// Resolve variables in step input
|
|
301
|
+
const resolvedInput = step.input ? resolveVariables(step.input, pipelineContext) : {};
|
|
302
|
+
// Execute the command
|
|
303
|
+
const result = await executeCommand(step.command, resolvedInput, {
|
|
304
|
+
...context,
|
|
305
|
+
traceId: context.traceId ?? `${pipelineId}-step-${i}`,
|
|
306
|
+
});
|
|
307
|
+
const stepExecutionTimeMs = performance.now() - stepStartTime;
|
|
308
|
+
if (result.success) {
|
|
309
|
+
const stepResult = {
|
|
310
|
+
index: i,
|
|
311
|
+
alias: step.as,
|
|
312
|
+
command: step.command,
|
|
313
|
+
status: 'success',
|
|
314
|
+
data: result.data,
|
|
315
|
+
executionTimeMs: Math.round(stepExecutionTimeMs * 100) / 100,
|
|
316
|
+
metadata: {
|
|
317
|
+
confidence: result.confidence,
|
|
318
|
+
reasoning: result.reasoning,
|
|
319
|
+
warnings: result.warnings,
|
|
320
|
+
sources: result.sources,
|
|
321
|
+
alternatives: result.alternatives,
|
|
322
|
+
},
|
|
323
|
+
};
|
|
324
|
+
stepResults.push(stepResult);
|
|
325
|
+
pipelineContext.steps.push(stepResult);
|
|
326
|
+
pipelineContext.previousResult = stepResult;
|
|
327
|
+
}
|
|
328
|
+
else {
|
|
329
|
+
const stepResult = {
|
|
330
|
+
index: i,
|
|
331
|
+
alias: step.as,
|
|
332
|
+
command: step.command,
|
|
333
|
+
status: 'failure',
|
|
334
|
+
error: result.error,
|
|
335
|
+
executionTimeMs: Math.round(stepExecutionTimeMs * 100) / 100,
|
|
336
|
+
};
|
|
337
|
+
stepResults.push(stepResult);
|
|
338
|
+
if (!options.continueOnFailure) {
|
|
339
|
+
stopped = true;
|
|
340
|
+
// Mark remaining steps as skipped
|
|
341
|
+
for (let j = i + 1; j < request.steps.length; j++) {
|
|
342
|
+
const remainingStep = request.steps[j];
|
|
343
|
+
if (!remainingStep)
|
|
344
|
+
continue;
|
|
345
|
+
stepResults.push({
|
|
346
|
+
index: j,
|
|
347
|
+
alias: remainingStep.as,
|
|
348
|
+
command: remainingStep.command,
|
|
349
|
+
status: 'skipped',
|
|
350
|
+
executionTimeMs: 0,
|
|
351
|
+
});
|
|
352
|
+
}
|
|
353
|
+
break;
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
// Check timeout
|
|
357
|
+
if (options.timeoutMs && performance.now() - startTime > options.timeoutMs) {
|
|
358
|
+
for (let j = i + 1; j < request.steps.length; j++) {
|
|
359
|
+
const remainingStep = request.steps[j];
|
|
360
|
+
if (!remainingStep)
|
|
361
|
+
continue;
|
|
362
|
+
stepResults.push({
|
|
363
|
+
index: j,
|
|
364
|
+
alias: remainingStep.as,
|
|
365
|
+
command: remainingStep.command,
|
|
366
|
+
status: 'skipped',
|
|
367
|
+
error: {
|
|
368
|
+
code: 'PIPELINE_TIMEOUT',
|
|
369
|
+
message: `Pipeline timeout exceeded (${options.timeoutMs}ms)`,
|
|
370
|
+
retryable: true,
|
|
371
|
+
},
|
|
372
|
+
executionTimeMs: 0,
|
|
373
|
+
});
|
|
374
|
+
}
|
|
375
|
+
break;
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
const totalExecutionTimeMs = performance.now() - startTime;
|
|
379
|
+
// Get the last successful step's data as the pipeline output
|
|
380
|
+
const lastSuccessfulStep = [...stepResults].reverse().find((s) => s.status === 'success');
|
|
381
|
+
const finalData = lastSuccessfulStep?.data;
|
|
382
|
+
// Build metadata using helper functions
|
|
383
|
+
const metadata = {
|
|
384
|
+
confidence: aggregatePipelineConfidence(stepResults),
|
|
385
|
+
confidenceBreakdown: buildConfidenceBreakdown(stepResults, request.steps),
|
|
386
|
+
reasoning: aggregatePipelineReasoning(stepResults),
|
|
387
|
+
warnings: aggregatePipelineWarnings(stepResults),
|
|
388
|
+
sources: aggregatePipelineSources(stepResults),
|
|
389
|
+
alternatives: aggregatePipelineAlternatives(stepResults),
|
|
390
|
+
executionTimeMs: Math.round(totalExecutionTimeMs * 100) / 100,
|
|
391
|
+
completedSteps: stepResults.filter((s) => s.status === 'success').length,
|
|
392
|
+
totalSteps: request.steps.length,
|
|
393
|
+
};
|
|
394
|
+
return {
|
|
395
|
+
data: finalData,
|
|
396
|
+
metadata,
|
|
397
|
+
steps: stepResults,
|
|
398
|
+
};
|
|
399
|
+
}
|
|
228
400
|
/**
|
|
229
401
|
* Execute a command as a stream, yielding chunks.
|
|
230
402
|
*/
|
|
@@ -235,8 +407,8 @@ export function createMcpServer(options) {
|
|
|
235
407
|
const result = await executeCommand(commandName, input, context);
|
|
236
408
|
if (!result.success) {
|
|
237
409
|
yield createErrorChunk(result.error ?? {
|
|
238
|
-
code:
|
|
239
|
-
message:
|
|
410
|
+
code: 'COMMAND_FAILED',
|
|
411
|
+
message: 'Command execution failed',
|
|
240
412
|
}, chunksEmitted, result.error?.retryable ?? false);
|
|
241
413
|
return;
|
|
242
414
|
}
|
|
@@ -245,7 +417,7 @@ export function createMcpServer(options) {
|
|
|
245
417
|
if (Array.isArray(data)) {
|
|
246
418
|
for (let i = 0; i < data.length; i++) {
|
|
247
419
|
yield {
|
|
248
|
-
type:
|
|
420
|
+
type: 'data',
|
|
249
421
|
data: data[i],
|
|
250
422
|
index: i,
|
|
251
423
|
isLast: i === data.length - 1,
|
|
@@ -255,7 +427,7 @@ export function createMcpServer(options) {
|
|
|
255
427
|
}
|
|
256
428
|
else {
|
|
257
429
|
yield {
|
|
258
|
-
type:
|
|
430
|
+
type: 'data',
|
|
259
431
|
data: data,
|
|
260
432
|
index: 0,
|
|
261
433
|
isLast: true,
|
|
@@ -272,7 +444,7 @@ export function createMcpServer(options) {
|
|
|
272
444
|
}
|
|
273
445
|
catch (error) {
|
|
274
446
|
yield createErrorChunk({
|
|
275
|
-
code:
|
|
447
|
+
code: 'STREAM_ERROR',
|
|
276
448
|
message: error instanceof Error ? error.message : String(error),
|
|
277
449
|
retryable: true,
|
|
278
450
|
}, chunksEmitted, true);
|
|
@@ -284,62 +456,121 @@ export function createMcpServer(options) {
|
|
|
284
456
|
function getToolsList() {
|
|
285
457
|
// Built-in afd-batch tool (always individual)
|
|
286
458
|
const batchTool = {
|
|
287
|
-
name:
|
|
288
|
-
description:
|
|
459
|
+
name: 'afd-batch',
|
|
460
|
+
description: 'Execute multiple commands in a single batch request with partial success semantics',
|
|
289
461
|
inputSchema: {
|
|
290
|
-
type:
|
|
462
|
+
type: 'object',
|
|
291
463
|
properties: {
|
|
292
464
|
commands: {
|
|
293
|
-
type:
|
|
294
|
-
description:
|
|
465
|
+
type: 'array',
|
|
466
|
+
description: 'Array of commands to execute',
|
|
295
467
|
items: {
|
|
296
|
-
type:
|
|
468
|
+
type: 'object',
|
|
297
469
|
properties: {
|
|
298
|
-
id: {
|
|
299
|
-
|
|
300
|
-
|
|
470
|
+
id: {
|
|
471
|
+
type: 'string',
|
|
472
|
+
description: 'Optional client-provided ID for correlating results',
|
|
473
|
+
},
|
|
474
|
+
command: { type: 'string', description: 'The command name to execute' },
|
|
475
|
+
input: { type: 'object', description: 'Input parameters for the command' },
|
|
301
476
|
},
|
|
302
|
-
required: [
|
|
477
|
+
required: ['command'],
|
|
303
478
|
},
|
|
304
479
|
},
|
|
305
480
|
options: {
|
|
306
|
-
type:
|
|
307
|
-
description:
|
|
481
|
+
type: 'object',
|
|
482
|
+
description: 'Batch execution options',
|
|
308
483
|
properties: {
|
|
309
|
-
stopOnError: { type:
|
|
310
|
-
timeout: { type:
|
|
484
|
+
stopOnError: { type: 'boolean', description: 'Stop execution on first error' },
|
|
485
|
+
timeout: { type: 'number', description: 'Timeout in milliseconds for entire batch' },
|
|
311
486
|
},
|
|
312
487
|
},
|
|
313
488
|
},
|
|
314
|
-
required: [
|
|
489
|
+
required: ['commands'],
|
|
490
|
+
},
|
|
491
|
+
};
|
|
492
|
+
// Built-in afd-pipe tool for pipeline execution
|
|
493
|
+
const pipeTool = {
|
|
494
|
+
name: 'afd-pipe',
|
|
495
|
+
description: 'Execute a pipeline of chained commands where the output of one becomes the input of the next',
|
|
496
|
+
inputSchema: {
|
|
497
|
+
type: 'object',
|
|
498
|
+
properties: {
|
|
499
|
+
steps: {
|
|
500
|
+
type: 'array',
|
|
501
|
+
description: 'Ordered list of pipeline steps to execute',
|
|
502
|
+
items: {
|
|
503
|
+
type: 'object',
|
|
504
|
+
properties: {
|
|
505
|
+
command: { type: 'string', description: 'Command name to execute' },
|
|
506
|
+
input: {
|
|
507
|
+
type: 'object',
|
|
508
|
+
description: 'Input parameters, can reference $prev, $first, $steps[n], or $steps.alias',
|
|
509
|
+
},
|
|
510
|
+
as: {
|
|
511
|
+
type: 'string',
|
|
512
|
+
description: "Optional alias for referencing this step's output",
|
|
513
|
+
},
|
|
514
|
+
when: {
|
|
515
|
+
type: 'object',
|
|
516
|
+
description: "Optional condition for running this step (e.g., { $exists: '$prev.id' })",
|
|
517
|
+
},
|
|
518
|
+
},
|
|
519
|
+
required: ['command'],
|
|
520
|
+
},
|
|
521
|
+
},
|
|
522
|
+
options: {
|
|
523
|
+
type: 'object',
|
|
524
|
+
description: 'Pipeline execution options',
|
|
525
|
+
properties: {
|
|
526
|
+
continueOnFailure: {
|
|
527
|
+
type: 'boolean',
|
|
528
|
+
description: 'Continue on failure or stop immediately',
|
|
529
|
+
},
|
|
530
|
+
timeoutMs: {
|
|
531
|
+
type: 'number',
|
|
532
|
+
description: 'Timeout for entire pipeline in milliseconds',
|
|
533
|
+
},
|
|
534
|
+
},
|
|
535
|
+
},
|
|
536
|
+
},
|
|
537
|
+
required: ['steps'],
|
|
315
538
|
},
|
|
316
539
|
};
|
|
317
540
|
// Individual strategy: each command is its own tool
|
|
318
|
-
if (toolStrategy ===
|
|
541
|
+
if (toolStrategy === 'individual') {
|
|
319
542
|
return [
|
|
320
543
|
batchTool,
|
|
544
|
+
pipeTool,
|
|
321
545
|
...commands.map((cmd) => {
|
|
322
546
|
const { type: _type, ...restSchema } = cmd.jsonSchema;
|
|
547
|
+
const hasMeta = (cmd.requires && cmd.requires.length > 0) || cmd.mutation != null;
|
|
323
548
|
return {
|
|
324
549
|
name: cmd.name,
|
|
325
550
|
description: cmd.description,
|
|
326
551
|
inputSchema: {
|
|
327
|
-
type:
|
|
552
|
+
type: 'object',
|
|
328
553
|
...restSchema,
|
|
329
554
|
},
|
|
555
|
+
...(hasMeta && {
|
|
556
|
+
_meta: {
|
|
557
|
+
...(cmd.requires?.length && { requires: cmd.requires }),
|
|
558
|
+
...(cmd.mutation != null && { mutation: cmd.mutation }),
|
|
559
|
+
},
|
|
560
|
+
}),
|
|
330
561
|
};
|
|
331
562
|
}),
|
|
332
563
|
];
|
|
333
564
|
}
|
|
334
565
|
// Grouped strategy: commands grouped by category/entity
|
|
335
566
|
const defaultGroupFn = (cmd) => {
|
|
336
|
-
return cmd.category || cmd.name.split(
|
|
567
|
+
return cmd.category || cmd.name.split('-')[0] || 'general';
|
|
337
568
|
};
|
|
338
569
|
const getGroup = groupByFn || defaultGroupFn;
|
|
339
570
|
// Group commands by their group key
|
|
340
571
|
const groups = {};
|
|
341
572
|
for (const cmd of commands) {
|
|
342
|
-
const group = getGroup(cmd) ||
|
|
573
|
+
const group = getGroup(cmd) || 'general';
|
|
343
574
|
if (!groups[group]) {
|
|
344
575
|
groups[group] = [];
|
|
345
576
|
}
|
|
@@ -348,34 +579,34 @@ export function createMcpServer(options) {
|
|
|
348
579
|
// Create a consolidated tool for each group
|
|
349
580
|
const groupedTools = Object.entries(groups).map(([groupName, groupCmds]) => {
|
|
350
581
|
// Build action enum from command names
|
|
351
|
-
const actions = groupCmds.map(cmd => {
|
|
582
|
+
const actions = groupCmds.map((cmd) => {
|
|
352
583
|
// Extract action from command name (e.g., "todo-create" -> "create")
|
|
353
|
-
const parts = cmd.name.split(
|
|
354
|
-
return parts.length > 1 ? parts.slice(1).join(
|
|
584
|
+
const parts = cmd.name.split('-');
|
|
585
|
+
return parts.length > 1 ? parts.slice(1).join('-') : cmd.name;
|
|
355
586
|
});
|
|
356
587
|
return {
|
|
357
588
|
name: groupName,
|
|
358
|
-
description: `${groupName} operations: ${actions.join(
|
|
589
|
+
description: `${groupName} operations: ${actions.join(', ')}`,
|
|
359
590
|
inputSchema: {
|
|
360
|
-
type:
|
|
591
|
+
type: 'object',
|
|
361
592
|
properties: {
|
|
362
593
|
action: {
|
|
363
|
-
type:
|
|
594
|
+
type: 'string',
|
|
364
595
|
enum: actions,
|
|
365
|
-
description: `Action to perform: ${actions.join(
|
|
596
|
+
description: `Action to perform: ${actions.join(' | ')}`,
|
|
366
597
|
},
|
|
367
598
|
// Note: Full discriminated union would require merging all command schemas
|
|
368
599
|
// For now, we use a generic "params" object
|
|
369
600
|
params: {
|
|
370
|
-
type:
|
|
371
|
-
description:
|
|
601
|
+
type: 'object',
|
|
602
|
+
description: 'Parameters for the action (varies by action)',
|
|
372
603
|
},
|
|
373
604
|
},
|
|
374
|
-
required: [
|
|
605
|
+
required: ['action'],
|
|
375
606
|
},
|
|
376
607
|
};
|
|
377
608
|
});
|
|
378
|
-
return [batchTool, ...groupedTools];
|
|
609
|
+
return [batchTool, pipeTool, ...groupedTools];
|
|
379
610
|
}
|
|
380
611
|
/**
|
|
381
612
|
* Handle MCP JSON-RPC request.
|
|
@@ -383,12 +614,12 @@ export function createMcpServer(options) {
|
|
|
383
614
|
function handleMcpRequest(request) {
|
|
384
615
|
const { id, method } = request;
|
|
385
616
|
switch (method) {
|
|
386
|
-
case
|
|
617
|
+
case 'initialize':
|
|
387
618
|
return {
|
|
388
|
-
jsonrpc:
|
|
619
|
+
jsonrpc: '2.0',
|
|
389
620
|
id,
|
|
390
621
|
result: {
|
|
391
|
-
protocolVersion:
|
|
622
|
+
protocolVersion: '2024-11-05',
|
|
392
623
|
capabilities: {
|
|
393
624
|
tools: {},
|
|
394
625
|
},
|
|
@@ -398,25 +629,25 @@ export function createMcpServer(options) {
|
|
|
398
629
|
},
|
|
399
630
|
},
|
|
400
631
|
};
|
|
401
|
-
case
|
|
632
|
+
case 'tools/list':
|
|
402
633
|
return {
|
|
403
|
-
jsonrpc:
|
|
634
|
+
jsonrpc: '2.0',
|
|
404
635
|
id,
|
|
405
636
|
result: {
|
|
406
637
|
tools: getToolsList(),
|
|
407
638
|
},
|
|
408
639
|
};
|
|
409
|
-
case
|
|
640
|
+
case 'notifications/initialized':
|
|
410
641
|
// Client notification, no response needed for notifications
|
|
411
642
|
// but we return a success for acknowledgment
|
|
412
643
|
return {
|
|
413
|
-
jsonrpc:
|
|
644
|
+
jsonrpc: '2.0',
|
|
414
645
|
id,
|
|
415
646
|
result: {},
|
|
416
647
|
};
|
|
417
648
|
default:
|
|
418
649
|
return {
|
|
419
|
-
jsonrpc:
|
|
650
|
+
jsonrpc: '2.0',
|
|
420
651
|
id,
|
|
421
652
|
error: {
|
|
422
653
|
code: -32601,
|
|
@@ -430,21 +661,21 @@ export function createMcpServer(options) {
|
|
|
430
661
|
*/
|
|
431
662
|
async function handleAsyncMcpRequest(request) {
|
|
432
663
|
const { id, method, params } = request;
|
|
433
|
-
if (method ===
|
|
664
|
+
if (method === 'tools/call') {
|
|
434
665
|
const { name: toolName, arguments: args } = params;
|
|
435
666
|
// Handle built-in afd-batch tool
|
|
436
|
-
if (toolName ===
|
|
667
|
+
if (toolName === 'afd-batch') {
|
|
437
668
|
const batchRequest = args;
|
|
438
669
|
const result = await executeBatch(batchRequest, {
|
|
439
670
|
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
440
671
|
});
|
|
441
672
|
return {
|
|
442
|
-
jsonrpc:
|
|
673
|
+
jsonrpc: '2.0',
|
|
443
674
|
id,
|
|
444
675
|
result: {
|
|
445
676
|
content: [
|
|
446
677
|
{
|
|
447
|
-
type:
|
|
678
|
+
type: 'text',
|
|
448
679
|
text: JSON.stringify(result, null, 2),
|
|
449
680
|
},
|
|
450
681
|
],
|
|
@@ -452,24 +683,75 @@ export function createMcpServer(options) {
|
|
|
452
683
|
},
|
|
453
684
|
};
|
|
454
685
|
}
|
|
686
|
+
// Handle built-in afd-pipe tool
|
|
687
|
+
if (toolName === 'afd-pipe') {
|
|
688
|
+
const pipelineRequest = args;
|
|
689
|
+
if (!isPipelineRequest(pipelineRequest)) {
|
|
690
|
+
return {
|
|
691
|
+
jsonrpc: '2.0',
|
|
692
|
+
id,
|
|
693
|
+
result: {
|
|
694
|
+
content: [
|
|
695
|
+
{
|
|
696
|
+
type: 'text',
|
|
697
|
+
text: JSON.stringify({
|
|
698
|
+
data: undefined,
|
|
699
|
+
metadata: {
|
|
700
|
+
confidence: 0,
|
|
701
|
+
confidenceBreakdown: [],
|
|
702
|
+
reasoning: [],
|
|
703
|
+
warnings: [],
|
|
704
|
+
sources: [],
|
|
705
|
+
alternatives: [],
|
|
706
|
+
executionTimeMs: 0,
|
|
707
|
+
completedSteps: 0,
|
|
708
|
+
totalSteps: 0,
|
|
709
|
+
},
|
|
710
|
+
steps: [],
|
|
711
|
+
}, null, 2),
|
|
712
|
+
},
|
|
713
|
+
],
|
|
714
|
+
isError: true,
|
|
715
|
+
},
|
|
716
|
+
};
|
|
717
|
+
}
|
|
718
|
+
const result = await executePipeline(pipelineRequest, {
|
|
719
|
+
traceId: `pipeline-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
720
|
+
});
|
|
721
|
+
// Determine if pipeline failed (any step failed)
|
|
722
|
+
const hasFailed = result.steps.some((s) => s.status === 'failure');
|
|
723
|
+
return {
|
|
724
|
+
jsonrpc: '2.0',
|
|
725
|
+
id,
|
|
726
|
+
result: {
|
|
727
|
+
content: [
|
|
728
|
+
{
|
|
729
|
+
type: 'text',
|
|
730
|
+
text: JSON.stringify(result, null, 2),
|
|
731
|
+
},
|
|
732
|
+
],
|
|
733
|
+
isError: hasFailed,
|
|
734
|
+
},
|
|
735
|
+
};
|
|
736
|
+
}
|
|
455
737
|
// Handle grouped tool calls (when toolStrategy === "grouped")
|
|
456
|
-
if (toolStrategy ===
|
|
738
|
+
if (toolStrategy === 'grouped') {
|
|
457
739
|
const typedArgs = args;
|
|
458
740
|
const action = typedArgs?.action;
|
|
459
741
|
const commandParams = typedArgs?.params ?? {};
|
|
460
|
-
if (action && typeof action ===
|
|
742
|
+
if (action && typeof action === 'string') {
|
|
461
743
|
// Construct actual command name: groupName-action
|
|
462
744
|
const actualCommandName = `${toolName}-${action}`;
|
|
463
745
|
const result = await executeCommand(actualCommandName, commandParams, {
|
|
464
746
|
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
465
747
|
});
|
|
466
748
|
return {
|
|
467
|
-
jsonrpc:
|
|
749
|
+
jsonrpc: '2.0',
|
|
468
750
|
id,
|
|
469
751
|
result: {
|
|
470
752
|
content: [
|
|
471
753
|
{
|
|
472
|
-
type:
|
|
754
|
+
type: 'text',
|
|
473
755
|
text: JSON.stringify(result, null, 2),
|
|
474
756
|
},
|
|
475
757
|
],
|
|
@@ -483,12 +765,12 @@ export function createMcpServer(options) {
|
|
|
483
765
|
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
484
766
|
});
|
|
485
767
|
return {
|
|
486
|
-
jsonrpc:
|
|
768
|
+
jsonrpc: '2.0',
|
|
487
769
|
id,
|
|
488
770
|
result: {
|
|
489
771
|
content: [
|
|
490
772
|
{
|
|
491
|
-
type:
|
|
773
|
+
type: 'text',
|
|
492
774
|
text: JSON.stringify(result, null, 2),
|
|
493
775
|
},
|
|
494
776
|
],
|
|
@@ -514,84 +796,131 @@ export function createMcpServer(options) {
|
|
|
514
796
|
// CORS headers - restrictive in production, permissive in dev mode
|
|
515
797
|
if (cors) {
|
|
516
798
|
// In dev mode, allow all origins; in production, allow same-origin or configured origins
|
|
517
|
-
res.setHeader(
|
|
518
|
-
res.setHeader(
|
|
519
|
-
res.setHeader(
|
|
799
|
+
res.setHeader('Access-Control-Allow-Origin', devMode ? '*' : (req.headers.origin ?? ''));
|
|
800
|
+
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
|
|
801
|
+
res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
|
|
520
802
|
}
|
|
521
803
|
// Handle preflight
|
|
522
|
-
if (req.method ===
|
|
804
|
+
if (req.method === 'OPTIONS') {
|
|
523
805
|
res.writeHead(204);
|
|
524
806
|
res.end();
|
|
525
807
|
return;
|
|
526
808
|
}
|
|
527
|
-
const url = new URL(req.url ??
|
|
809
|
+
const url = new URL(req.url ?? '/', `http://${req.headers.host}`);
|
|
528
810
|
// SSE endpoint
|
|
529
|
-
if (url.pathname ===
|
|
811
|
+
if (url.pathname === '/sse' && req.method === 'GET') {
|
|
530
812
|
const clientId = `client-${++clientIdCounter}`;
|
|
531
813
|
res.writeHead(200, {
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
Connection:
|
|
814
|
+
'Content-Type': 'text/event-stream',
|
|
815
|
+
'Cache-Control': 'no-cache',
|
|
816
|
+
Connection: 'keep-alive',
|
|
535
817
|
});
|
|
536
818
|
const client = { id: clientId, response: res };
|
|
537
819
|
sseClients.set(clientId, client);
|
|
538
820
|
// Send endpoint info
|
|
539
|
-
sendSseEvent(client,
|
|
821
|
+
sendSseEvent(client, 'endpoint', {
|
|
540
822
|
url: `http://${host}:${port}/message`,
|
|
541
823
|
});
|
|
542
824
|
// Handle client disconnect
|
|
543
|
-
req.on(
|
|
825
|
+
req.on('close', () => {
|
|
544
826
|
sseClients.delete(clientId);
|
|
545
827
|
});
|
|
546
828
|
return;
|
|
547
829
|
}
|
|
548
830
|
// Message endpoint
|
|
549
|
-
if (url.pathname ===
|
|
550
|
-
let body =
|
|
831
|
+
if (url.pathname === '/message' && req.method === 'POST') {
|
|
832
|
+
let body = '';
|
|
551
833
|
for await (const chunk of req) {
|
|
552
834
|
body += chunk;
|
|
553
835
|
}
|
|
554
836
|
try {
|
|
555
837
|
const request = JSON.parse(body);
|
|
556
838
|
const response = await handleAsyncMcpRequest(request);
|
|
557
|
-
res.writeHead(200, {
|
|
839
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
558
840
|
res.end(JSON.stringify(response));
|
|
559
841
|
}
|
|
560
|
-
catch (
|
|
561
|
-
res.writeHead(400, {
|
|
842
|
+
catch (_error) {
|
|
843
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
562
844
|
res.end(JSON.stringify({
|
|
563
|
-
jsonrpc:
|
|
845
|
+
jsonrpc: '2.0',
|
|
564
846
|
id: null,
|
|
565
847
|
error: {
|
|
566
848
|
code: -32700,
|
|
567
|
-
message:
|
|
849
|
+
message: 'Parse error',
|
|
568
850
|
},
|
|
569
851
|
}));
|
|
570
852
|
}
|
|
571
853
|
return;
|
|
572
854
|
}
|
|
573
855
|
// Health check
|
|
574
|
-
if (url.pathname ===
|
|
575
|
-
res.writeHead(200, {
|
|
576
|
-
res.end(JSON.stringify({ status:
|
|
856
|
+
if (url.pathname === '/health' && req.method === 'GET') {
|
|
857
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
858
|
+
res.end(JSON.stringify({ status: 'ok', name, version }));
|
|
859
|
+
return;
|
|
860
|
+
}
|
|
861
|
+
// RPC endpoint - Simple JSON-RPC for browser clients
|
|
862
|
+
// This is a browser-friendly alternative to /message that calls commands directly
|
|
863
|
+
// Request format: { method: "command-name", params: {...}, id: 1 }
|
|
864
|
+
// Response format: { jsonrpc: "2.0", id: 1, result: CommandResult }
|
|
865
|
+
if (url.pathname === '/rpc' && req.method === 'POST') {
|
|
866
|
+
let body = '';
|
|
867
|
+
for await (const chunk of req) {
|
|
868
|
+
body += chunk;
|
|
869
|
+
}
|
|
870
|
+
try {
|
|
871
|
+
const request = JSON.parse(body);
|
|
872
|
+
const { method: commandName, params, id = null } = request;
|
|
873
|
+
if (!commandName || typeof commandName !== 'string') {
|
|
874
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
875
|
+
res.end(JSON.stringify({
|
|
876
|
+
jsonrpc: '2.0',
|
|
877
|
+
id,
|
|
878
|
+
error: {
|
|
879
|
+
code: -32600,
|
|
880
|
+
message: 'Invalid request: method is required',
|
|
881
|
+
},
|
|
882
|
+
}));
|
|
883
|
+
return;
|
|
884
|
+
}
|
|
885
|
+
const result = await executeCommand(commandName, params ?? {}, {
|
|
886
|
+
traceId: `rpc-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
887
|
+
});
|
|
888
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
889
|
+
res.end(JSON.stringify({
|
|
890
|
+
jsonrpc: '2.0',
|
|
891
|
+
id,
|
|
892
|
+
result,
|
|
893
|
+
}));
|
|
894
|
+
}
|
|
895
|
+
catch (_error) {
|
|
896
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
897
|
+
res.end(JSON.stringify({
|
|
898
|
+
jsonrpc: '2.0',
|
|
899
|
+
id: null,
|
|
900
|
+
error: {
|
|
901
|
+
code: -32700,
|
|
902
|
+
message: 'Parse error',
|
|
903
|
+
},
|
|
904
|
+
}));
|
|
905
|
+
}
|
|
577
906
|
return;
|
|
578
907
|
}
|
|
579
908
|
// Batch endpoint
|
|
580
|
-
if (url.pathname ===
|
|
581
|
-
let body =
|
|
909
|
+
if (url.pathname === '/batch' && req.method === 'POST') {
|
|
910
|
+
let body = '';
|
|
582
911
|
for await (const chunk of req) {
|
|
583
912
|
body += chunk;
|
|
584
913
|
}
|
|
585
914
|
try {
|
|
586
915
|
const batchRequest = JSON.parse(body);
|
|
587
916
|
if (!isBatchRequest(batchRequest)) {
|
|
588
|
-
res.writeHead(400, {
|
|
917
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
589
918
|
res.end(JSON.stringify({
|
|
590
919
|
success: false,
|
|
591
920
|
error: {
|
|
592
|
-
code:
|
|
593
|
-
message:
|
|
594
|
-
suggestion:
|
|
921
|
+
code: 'INVALID_BATCH_REQUEST',
|
|
922
|
+
message: 'Invalid batch request format',
|
|
923
|
+
suggestion: 'Provide { commands: [...] } with command objects',
|
|
595
924
|
},
|
|
596
925
|
}));
|
|
597
926
|
return;
|
|
@@ -599,39 +928,39 @@ export function createMcpServer(options) {
|
|
|
599
928
|
const result = await executeBatch(batchRequest, {
|
|
600
929
|
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
601
930
|
});
|
|
602
|
-
res.writeHead(200, {
|
|
931
|
+
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
603
932
|
res.end(JSON.stringify(result));
|
|
604
933
|
}
|
|
605
|
-
catch (
|
|
606
|
-
res.writeHead(400, {
|
|
934
|
+
catch (_error) {
|
|
935
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
607
936
|
res.end(JSON.stringify({
|
|
608
937
|
success: false,
|
|
609
938
|
error: {
|
|
610
|
-
code:
|
|
611
|
-
message:
|
|
612
|
-
suggestion:
|
|
939
|
+
code: 'PARSE_ERROR',
|
|
940
|
+
message: 'Failed to parse batch request',
|
|
941
|
+
suggestion: 'Ensure request body is valid JSON',
|
|
613
942
|
},
|
|
614
943
|
}));
|
|
615
944
|
}
|
|
616
945
|
return;
|
|
617
946
|
}
|
|
618
947
|
// Stream endpoint - SSE for streaming command results
|
|
619
|
-
if (url.pathname.startsWith(
|
|
620
|
-
const commandName = url.pathname.slice(
|
|
621
|
-
const inputParam = url.searchParams.get(
|
|
948
|
+
if (url.pathname.startsWith('/stream/') && req.method === 'GET') {
|
|
949
|
+
const commandName = url.pathname.slice('/stream/'.length);
|
|
950
|
+
const inputParam = url.searchParams.get('input');
|
|
622
951
|
let input = {};
|
|
623
952
|
if (inputParam) {
|
|
624
953
|
try {
|
|
625
954
|
input = JSON.parse(inputParam);
|
|
626
955
|
}
|
|
627
956
|
catch {
|
|
628
|
-
res.writeHead(400, {
|
|
957
|
+
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
629
958
|
res.end(JSON.stringify({
|
|
630
959
|
success: false,
|
|
631
960
|
error: {
|
|
632
|
-
code:
|
|
633
|
-
message:
|
|
634
|
-
suggestion:
|
|
961
|
+
code: 'INVALID_INPUT',
|
|
962
|
+
message: 'Failed to parse input parameter',
|
|
963
|
+
suggestion: 'Ensure input is valid JSON',
|
|
635
964
|
},
|
|
636
965
|
}));
|
|
637
966
|
return;
|
|
@@ -639,16 +968,16 @@ export function createMcpServer(options) {
|
|
|
639
968
|
}
|
|
640
969
|
// Set up SSE response
|
|
641
970
|
res.writeHead(200, {
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
Connection:
|
|
971
|
+
'Content-Type': 'text/event-stream',
|
|
972
|
+
'Cache-Control': 'no-cache',
|
|
973
|
+
Connection: 'keep-alive',
|
|
645
974
|
});
|
|
646
975
|
const context = {
|
|
647
976
|
traceId: `stream-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
648
977
|
};
|
|
649
978
|
// Handle client disconnect
|
|
650
979
|
let aborted = false;
|
|
651
|
-
req.on(
|
|
980
|
+
req.on('close', () => {
|
|
652
981
|
aborted = true;
|
|
653
982
|
});
|
|
654
983
|
// Stream the command execution
|
|
@@ -661,7 +990,7 @@ export function createMcpServer(options) {
|
|
|
661
990
|
}
|
|
662
991
|
catch (error) {
|
|
663
992
|
const errorChunk = createErrorChunk({
|
|
664
|
-
code:
|
|
993
|
+
code: 'STREAM_ERROR',
|
|
665
994
|
message: error instanceof Error ? error.message : String(error),
|
|
666
995
|
retryable: true,
|
|
667
996
|
}, 0, true);
|
|
@@ -671,8 +1000,8 @@ export function createMcpServer(options) {
|
|
|
671
1000
|
return;
|
|
672
1001
|
}
|
|
673
1002
|
// Not found
|
|
674
|
-
res.writeHead(404, {
|
|
675
|
-
res.end(JSON.stringify({ error:
|
|
1003
|
+
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
1004
|
+
res.end(JSON.stringify({ error: 'Not found' }));
|
|
676
1005
|
};
|
|
677
1006
|
}
|
|
678
1007
|
// Track MCP SDK server for stdio transport cleanup
|
|
@@ -694,18 +1023,23 @@ export function createMcpServer(options) {
|
|
|
694
1023
|
const toolName = request.params.name;
|
|
695
1024
|
const args = request.params.arguments ?? {};
|
|
696
1025
|
// Handle built-in afd.batch tool
|
|
697
|
-
if (toolName ===
|
|
1026
|
+
if (toolName === 'afd-batch') {
|
|
698
1027
|
// Validate that args looks like a BatchRequest before processing
|
|
699
1028
|
if (!isBatchRequest(args)) {
|
|
700
1029
|
return {
|
|
701
|
-
content: [
|
|
1030
|
+
content: [
|
|
1031
|
+
{
|
|
1032
|
+
type: 'text',
|
|
1033
|
+
text: JSON.stringify({
|
|
702
1034
|
success: false,
|
|
703
1035
|
error: {
|
|
704
|
-
code:
|
|
705
|
-
message:
|
|
706
|
-
suggestion:
|
|
1036
|
+
code: 'INVALID_BATCH_REQUEST',
|
|
1037
|
+
message: 'Invalid batch request format',
|
|
1038
|
+
suggestion: 'Provide { commands: [...] } with command objects',
|
|
707
1039
|
},
|
|
708
|
-
}, null, 2)
|
|
1040
|
+
}, null, 2),
|
|
1041
|
+
},
|
|
1042
|
+
],
|
|
709
1043
|
isError: true,
|
|
710
1044
|
};
|
|
711
1045
|
}
|
|
@@ -713,13 +1047,51 @@ export function createMcpServer(options) {
|
|
|
713
1047
|
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
714
1048
|
});
|
|
715
1049
|
return {
|
|
716
|
-
content: [{ type:
|
|
1050
|
+
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
717
1051
|
isError: !result.success,
|
|
718
1052
|
};
|
|
719
1053
|
}
|
|
1054
|
+
// Handle built-in afd-pipe tool
|
|
1055
|
+
if (toolName === 'afd-pipe') {
|
|
1056
|
+
// Validate that args looks like a PipelineRequest before processing
|
|
1057
|
+
if (!isPipelineRequest(args)) {
|
|
1058
|
+
return {
|
|
1059
|
+
content: [
|
|
1060
|
+
{
|
|
1061
|
+
type: 'text',
|
|
1062
|
+
text: JSON.stringify({
|
|
1063
|
+
data: undefined,
|
|
1064
|
+
metadata: {
|
|
1065
|
+
confidence: 0,
|
|
1066
|
+
confidenceBreakdown: [],
|
|
1067
|
+
reasoning: [],
|
|
1068
|
+
warnings: [],
|
|
1069
|
+
sources: [],
|
|
1070
|
+
alternatives: [],
|
|
1071
|
+
executionTimeMs: 0,
|
|
1072
|
+
completedSteps: 0,
|
|
1073
|
+
totalSteps: 0,
|
|
1074
|
+
},
|
|
1075
|
+
steps: [],
|
|
1076
|
+
}, null, 2),
|
|
1077
|
+
},
|
|
1078
|
+
],
|
|
1079
|
+
isError: true,
|
|
1080
|
+
};
|
|
1081
|
+
}
|
|
1082
|
+
const result = await executePipeline(args, {
|
|
1083
|
+
traceId: `pipeline-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
1084
|
+
});
|
|
1085
|
+
// Determine if pipeline failed (any step failed)
|
|
1086
|
+
const hasFailed = result.steps.some((s) => s.status === 'failure');
|
|
1087
|
+
return {
|
|
1088
|
+
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
1089
|
+
isError: hasFailed,
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
720
1092
|
// Handle grouped tool calls (when toolStrategy === "grouped")
|
|
721
1093
|
// Grouped tools have format: { action: "create", params: {...} }
|
|
722
|
-
if (toolStrategy ===
|
|
1094
|
+
if (toolStrategy === 'grouped') {
|
|
723
1095
|
const action = args.action;
|
|
724
1096
|
const params = args.params ?? {};
|
|
725
1097
|
// Debug logging when enabled
|
|
@@ -727,7 +1099,7 @@ export function createMcpServer(options) {
|
|
|
727
1099
|
console.error(`[MCP Debug] Grouped tool call: toolName=${toolName}, action=${action}, args=${JSON.stringify(args)}`);
|
|
728
1100
|
}
|
|
729
1101
|
// Check if this is a grouped tool call (has action property)
|
|
730
|
-
if (action && typeof action ===
|
|
1102
|
+
if (action && typeof action === 'string') {
|
|
731
1103
|
// Construct the actual command name: groupName-action
|
|
732
1104
|
// e.g., "todo" + "create" = "todo-create"
|
|
733
1105
|
const actualCommandName = `${toolName}-${action}`;
|
|
@@ -736,35 +1108,40 @@ export function createMcpServer(options) {
|
|
|
736
1108
|
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
737
1109
|
});
|
|
738
1110
|
return {
|
|
739
|
-
content: [{ type:
|
|
1111
|
+
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
740
1112
|
isError: !result.success,
|
|
741
1113
|
};
|
|
742
1114
|
}
|
|
743
1115
|
// In grouped mode, if tool is a known group but action is missing/invalid,
|
|
744
1116
|
// return a helpful error instead of falling through
|
|
745
|
-
const groupNames = new Set(commands.map(cmd => {
|
|
746
|
-
const defaultGroupFn = (c) => c.category || c.name.split(
|
|
1117
|
+
const groupNames = new Set(commands.map((cmd) => {
|
|
1118
|
+
const defaultGroupFn = (c) => c.category || c.name.split('-')[0] || 'general';
|
|
747
1119
|
return (groupByFn || defaultGroupFn)(cmd);
|
|
748
1120
|
}));
|
|
749
1121
|
if (groupNames.has(toolName)) {
|
|
750
|
-
const groupCommands = commands.filter(cmd => {
|
|
751
|
-
const defaultGroupFn = (c) => c.category || c.name.split(
|
|
1122
|
+
const groupCommands = commands.filter((cmd) => {
|
|
1123
|
+
const defaultGroupFn = (c) => c.category || c.name.split('-')[0] || 'general';
|
|
752
1124
|
return (groupByFn || defaultGroupFn)(cmd) === toolName;
|
|
753
1125
|
});
|
|
754
|
-
const availableActions = groupCommands.map(cmd => {
|
|
755
|
-
const parts = cmd.name.split(
|
|
756
|
-
return parts.length > 1 ? parts.slice(1).join(
|
|
1126
|
+
const availableActions = groupCommands.map((cmd) => {
|
|
1127
|
+
const parts = cmd.name.split('-');
|
|
1128
|
+
return parts.length > 1 ? parts.slice(1).join('-') : cmd.name;
|
|
757
1129
|
});
|
|
758
1130
|
return {
|
|
759
|
-
content: [
|
|
1131
|
+
content: [
|
|
1132
|
+
{
|
|
1133
|
+
type: 'text',
|
|
1134
|
+
text: JSON.stringify({
|
|
760
1135
|
success: false,
|
|
761
1136
|
error: {
|
|
762
|
-
code:
|
|
1137
|
+
code: 'INVALID_GROUPED_CALL',
|
|
763
1138
|
message: `Grouped tool '${toolName}' requires an 'action' parameter`,
|
|
764
|
-
suggestion: `Provide { action: "<action>", params: {...} }. Available actions: ${availableActions.join(
|
|
1139
|
+
suggestion: `Provide { action: "<action>", params: {...} }. Available actions: ${availableActions.join(', ')}`,
|
|
765
1140
|
},
|
|
766
1141
|
_debug: devMode ? { receivedArgs: args } : undefined,
|
|
767
|
-
}, null, 2)
|
|
1142
|
+
}, null, 2),
|
|
1143
|
+
},
|
|
1144
|
+
],
|
|
768
1145
|
isError: true,
|
|
769
1146
|
};
|
|
770
1147
|
}
|
|
@@ -774,7 +1151,7 @@ export function createMcpServer(options) {
|
|
|
774
1151
|
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
775
1152
|
});
|
|
776
1153
|
return {
|
|
777
|
-
content: [{ type:
|
|
1154
|
+
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
778
1155
|
isError: !result.success,
|
|
779
1156
|
};
|
|
780
1157
|
});
|
|
@@ -791,8 +1168,8 @@ export function createMcpServer(options) {
|
|
|
791
1168
|
if (useHttp) {
|
|
792
1169
|
httpServer = createServer(createRequestHandler());
|
|
793
1170
|
await new Promise((resolve, reject) => {
|
|
794
|
-
httpServer
|
|
795
|
-
httpServer
|
|
1171
|
+
httpServer?.on('error', reject);
|
|
1172
|
+
httpServer?.listen(port, host, () => {
|
|
796
1173
|
isRunning = true;
|
|
797
1174
|
resolve();
|
|
798
1175
|
});
|
|
@@ -816,7 +1193,7 @@ export function createMcpServer(options) {
|
|
|
816
1193
|
}
|
|
817
1194
|
sseClients.clear();
|
|
818
1195
|
await new Promise((resolve, reject) => {
|
|
819
|
-
httpServer
|
|
1196
|
+
httpServer?.close((err) => {
|
|
820
1197
|
if (err)
|
|
821
1198
|
reject(err);
|
|
822
1199
|
else
|
|
@@ -828,7 +1205,7 @@ export function createMcpServer(options) {
|
|
|
828
1205
|
isRunning = false;
|
|
829
1206
|
},
|
|
830
1207
|
getUrl() {
|
|
831
|
-
return useHttp ? `http://${host}:${port}` :
|
|
1208
|
+
return useHttp ? `http://${host}:${port}` : 'stdio://';
|
|
832
1209
|
},
|
|
833
1210
|
getCommands() {
|
|
834
1211
|
return commands;
|
|
@@ -841,6 +1218,7 @@ export function createMcpServer(options) {
|
|
|
841
1218
|
return resolvedTransport;
|
|
842
1219
|
},
|
|
843
1220
|
execute: executeCommand,
|
|
1221
|
+
executePipeline,
|
|
844
1222
|
};
|
|
845
1223
|
}
|
|
846
1224
|
//# sourceMappingURL=server.js.map
|