@lushly-dev/afd-server 0.4.0 → 0.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.
- package/README.md +110 -0
- package/dist/bootstrap/afd-context.d.ts +60 -0
- package/dist/bootstrap/afd-context.d.ts.map +1 -0
- package/dist/bootstrap/afd-context.js +132 -0
- package/dist/bootstrap/afd-context.js.map +1 -0
- 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 -1
- package/dist/bootstrap/afd-help.js.map +1 -1
- package/dist/bootstrap/index.d.ts +1 -0
- package/dist/bootstrap/index.d.ts.map +1 -1
- package/dist/bootstrap/index.js +1 -0
- package/dist/bootstrap/index.js.map +1 -1
- package/dist/bootstrap/registry.d.ts +4 -0
- package/dist/bootstrap/registry.d.ts.map +1 -1
- package/dist/bootstrap/registry.js +8 -1
- package/dist/bootstrap/registry.js.map +1 -1
- package/dist/execution.d.ts +19 -0
- package/dist/execution.d.ts.map +1 -0
- package/dist/execution.js +389 -0
- package/dist/execution.js.map +1 -0
- package/dist/handoff-schema.d.ts +14 -14
- package/dist/http-handler.d.ts +28 -0
- package/dist/http-handler.d.ts.map +1 -0
- package/dist/http-handler.js +292 -0
- package/dist/http-handler.js.map +1 -0
- package/dist/index.d.ts +2 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/lazy-tools.d.ts +64 -0
- package/dist/lazy-tools.d.ts.map +1 -0
- package/dist/lazy-tools.js +144 -0
- package/dist/lazy-tools.js.map +1 -0
- package/dist/schema.d.ts +25 -1
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +20 -1
- package/dist/schema.js.map +1 -1
- package/dist/server-types.d.ts +138 -0
- package/dist/server-types.d.ts.map +1 -0
- package/dist/server-types.js +13 -0
- package/dist/server-types.js.map +1 -0
- package/dist/server.d.ts +6 -121
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +67 -1125
- package/dist/server.js.map +1 -1
- package/dist/tool-router.d.ts +36 -0
- package/dist/tool-router.d.ts.map +1 -0
- package/dist/tool-router.js +246 -0
- package/dist/tool-router.js.map +1 -0
- package/dist/tools.d.ts +428 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +244 -0
- package/dist/tools.js.map +1 -0
- package/package.json +3 -3
package/dist/server.js
CHANGED
|
@@ -1,24 +1,21 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @fileoverview MCP Server factory for AFD commands
|
|
2
|
+
* @fileoverview MCP Server factory for AFD commands.
|
|
3
3
|
*
|
|
4
|
-
* This module provides
|
|
5
|
-
*
|
|
4
|
+
* This module provides the `createMcpServer` factory that wires together
|
|
5
|
+
* execution, tool routing, and transport layers into a single MCP server.
|
|
6
6
|
*/
|
|
7
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
8
|
import { Server as McpSdkServer } from '@modelcontextprotocol/sdk/server/index.js';
|
|
10
9
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
11
10
|
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
export
|
|
20
|
-
return !process.stdin.isTTY;
|
|
21
|
-
}
|
|
11
|
+
import { createContextState } from './bootstrap/afd-context.js';
|
|
12
|
+
import { createExecutionEngine } from './execution.js';
|
|
13
|
+
import { createHttpHandler } from './http-handler.js';
|
|
14
|
+
import { isStdinPiped } from './server-types.js';
|
|
15
|
+
import { createToolRouter } from './tool-router.js';
|
|
16
|
+
import { getToolsList } from './tools.js';
|
|
17
|
+
// Re-export public types so existing imports from './server.js' still work
|
|
18
|
+
export { isStdinPiped } from './server-types.js';
|
|
22
19
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
23
20
|
// SERVER FACTORY
|
|
24
21
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
@@ -40,1133 +37,90 @@ export function isStdinPiped() {
|
|
|
40
37
|
* ```
|
|
41
38
|
*/
|
|
42
39
|
export function createMcpServer(options) {
|
|
43
|
-
const { name, version, commands, port = 3100, host = 'localhost', devMode = false,
|
|
44
|
-
//
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
// Resolve transport mode
|
|
48
|
-
// - If explicit transport is set, use it
|
|
49
|
-
// - If deprecated stdio option is set, use it for backward compatibility
|
|
50
|
-
// - Otherwise, auto-detect based on environment
|
|
40
|
+
const { name, version, commands, port = 3100, host = 'localhost', devMode = false, cors = devMode, transport = 'auto', stdio, middleware = [], onCommand, onError, toolStrategy = 'grouped', groupByFn, contexts, } = options;
|
|
41
|
+
// ── Context state (when contexts are configured) ─────────────────────────
|
|
42
|
+
const contextState = contexts?.length ? createContextState() : undefined;
|
|
43
|
+
// ── Transport resolution ────────────────────────────────────────────────
|
|
51
44
|
function resolveTransport() {
|
|
52
|
-
// Handle deprecated stdio option for backward compatibility
|
|
53
45
|
if (stdio !== undefined) {
|
|
54
46
|
return stdio ? 'stdio' : 'http';
|
|
55
47
|
}
|
|
56
|
-
// Auto-detect: use stdio if stdin is piped (not a TTY), otherwise use HTTP
|
|
57
48
|
if (transport === 'auto') {
|
|
58
49
|
return isStdinPiped() ? 'stdio' : 'http';
|
|
59
50
|
}
|
|
60
|
-
// Explicit transport mode (stdio or http)
|
|
61
51
|
return transport;
|
|
62
52
|
}
|
|
63
53
|
const resolvedTransport = resolveTransport();
|
|
64
54
|
const useStdio = resolvedTransport === 'stdio';
|
|
65
55
|
const useHttp = resolvedTransport === 'http';
|
|
66
|
-
//
|
|
56
|
+
// ── Command map ─────────────────────────────────────────────────────────
|
|
67
57
|
const commandMap = new Map();
|
|
68
58
|
for (const cmd of commands) {
|
|
69
59
|
commandMap.set(cmd.name, cmd);
|
|
70
60
|
}
|
|
71
|
-
//
|
|
72
|
-
const
|
|
73
|
-
|
|
74
|
-
|
|
61
|
+
// ── Wire up execution, routing, and tools ───────────────────────────────
|
|
62
|
+
const engine = createExecutionEngine({
|
|
63
|
+
commandMap,
|
|
64
|
+
middleware,
|
|
65
|
+
devMode,
|
|
66
|
+
onCommand,
|
|
67
|
+
onError,
|
|
68
|
+
});
|
|
69
|
+
const exposedCommandNames = new Set(commands.map((c) => c.name));
|
|
70
|
+
const routeToolCall = createToolRouter({
|
|
71
|
+
executeCommand: engine.executeCommand,
|
|
72
|
+
executeBatch: engine.executeBatch,
|
|
73
|
+
executePipeline: engine.executePipeline,
|
|
74
|
+
commands,
|
|
75
|
+
toolStrategy,
|
|
76
|
+
groupByFn,
|
|
77
|
+
devMode,
|
|
78
|
+
allCommands: commands,
|
|
79
|
+
exposedCommandNames,
|
|
80
|
+
contextState,
|
|
81
|
+
});
|
|
82
|
+
const boundGetToolsList = () => getToolsList(commands, toolStrategy, groupByFn, contextState?.getActive());
|
|
83
|
+
// ── Server state ────────────────────────────────────────────────────────
|
|
75
84
|
let httpServer = null;
|
|
76
|
-
let isRunning = false;
|
|
77
|
-
/**
|
|
78
|
-
* Execute a command with validation and middleware.
|
|
79
|
-
*/
|
|
80
|
-
async function executeCommand(commandName, input, context = {}) {
|
|
81
|
-
const command = commandMap.get(commandName);
|
|
82
|
-
if (!command) {
|
|
83
|
-
return failure({
|
|
84
|
-
code: 'COMMAND_NOT_FOUND',
|
|
85
|
-
message: `Command '${commandName}' not found`,
|
|
86
|
-
suggestion: `Available commands: ${Array.from(commandMap.keys()).join(', ')}`,
|
|
87
|
-
});
|
|
88
|
-
}
|
|
89
|
-
// Validate input with enhanced error messages
|
|
90
|
-
const validation = validateInputEnhanced(command.inputSchema, input);
|
|
91
|
-
if (!validation.success) {
|
|
92
|
-
return failure({
|
|
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
|
-
},
|
|
106
|
-
});
|
|
107
|
-
}
|
|
108
|
-
// Build middleware chain
|
|
109
|
-
const runHandler = async () => {
|
|
110
|
-
const startTime = Date.now();
|
|
111
|
-
const result = await command.handler(validation.data, context);
|
|
112
|
-
// Add metadata if not present
|
|
113
|
-
if (!result.metadata) {
|
|
114
|
-
result.metadata = {};
|
|
115
|
-
}
|
|
116
|
-
result.metadata.executionTimeMs = Date.now() - startTime;
|
|
117
|
-
result.metadata.commandVersion = command.version;
|
|
118
|
-
if (context.traceId) {
|
|
119
|
-
result.metadata.traceId = context.traceId;
|
|
120
|
-
}
|
|
121
|
-
return result;
|
|
122
|
-
};
|
|
123
|
-
// Apply middleware in reverse order
|
|
124
|
-
let next = runHandler;
|
|
125
|
-
for (let i = middleware.length - 1; i >= 0; i--) {
|
|
126
|
-
const mw = middleware[i];
|
|
127
|
-
if (!mw)
|
|
128
|
-
continue;
|
|
129
|
-
const currentNext = next;
|
|
130
|
-
next = () => mw(commandName, validation.data, context, currentNext);
|
|
131
|
-
}
|
|
132
|
-
try {
|
|
133
|
-
const result = await next();
|
|
134
|
-
onCommand?.(commandName, input, result);
|
|
135
|
-
return result;
|
|
136
|
-
}
|
|
137
|
-
catch (error) {
|
|
138
|
-
const err = error instanceof Error ? error : new Error(String(error));
|
|
139
|
-
onError?.(err);
|
|
140
|
-
return failure({
|
|
141
|
-
code: 'COMMAND_EXECUTION_ERROR',
|
|
142
|
-
message: devMode ? err.message : 'An internal error occurred',
|
|
143
|
-
suggestion: devMode
|
|
144
|
-
? 'Check the command implementation'
|
|
145
|
-
: 'Contact support if this persists',
|
|
146
|
-
// Only include stack traces in dev mode to prevent information leakage
|
|
147
|
-
...(devMode ? { details: { stack: err.stack } } : {}),
|
|
148
|
-
});
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
/**
|
|
152
|
-
* Execute multiple commands in a batch with partial success semantics.
|
|
153
|
-
*/
|
|
154
|
-
async function executeBatch(request, context = {}) {
|
|
155
|
-
const startedAt = new Date().toISOString();
|
|
156
|
-
const startTime = performance.now();
|
|
157
|
-
// Validate request
|
|
158
|
-
if (!request.commands || request.commands.length === 0) {
|
|
159
|
-
return createFailedBatchResult({
|
|
160
|
-
code: 'INVALID_BATCH_REQUEST',
|
|
161
|
-
message: 'Batch request must contain at least one command',
|
|
162
|
-
suggestion: 'Provide an array of commands to execute',
|
|
163
|
-
}, { startedAt });
|
|
164
|
-
}
|
|
165
|
-
const options = request.options ?? {};
|
|
166
|
-
const results = [];
|
|
167
|
-
let stopped = false;
|
|
168
|
-
// Execute commands sequentially
|
|
169
|
-
for (let i = 0; i < request.commands.length; i++) {
|
|
170
|
-
const cmd = request.commands[i];
|
|
171
|
-
if (!cmd)
|
|
172
|
-
continue;
|
|
173
|
-
if (stopped) {
|
|
174
|
-
results.push({
|
|
175
|
-
id: cmd.id ?? `cmd-${i}`,
|
|
176
|
-
index: i,
|
|
177
|
-
command: cmd.command,
|
|
178
|
-
result: {
|
|
179
|
-
success: false,
|
|
180
|
-
error: {
|
|
181
|
-
code: 'COMMAND_SKIPPED',
|
|
182
|
-
message: 'Command skipped due to previous error (stopOnError enabled)',
|
|
183
|
-
},
|
|
184
|
-
},
|
|
185
|
-
durationMs: 0,
|
|
186
|
-
});
|
|
187
|
-
continue;
|
|
188
|
-
}
|
|
189
|
-
const cmdStartTime = performance.now();
|
|
190
|
-
const result = await executeCommand(cmd.command, cmd.input, {
|
|
191
|
-
...context,
|
|
192
|
-
traceId: context.traceId ?? `batch-${Date.now()}-${i}`,
|
|
193
|
-
});
|
|
194
|
-
const cmdDuration = performance.now() - cmdStartTime;
|
|
195
|
-
results.push({
|
|
196
|
-
id: cmd.id ?? `cmd-${i}`,
|
|
197
|
-
index: i,
|
|
198
|
-
command: cmd.command,
|
|
199
|
-
result,
|
|
200
|
-
durationMs: Math.round(cmdDuration * 100) / 100,
|
|
201
|
-
});
|
|
202
|
-
if (!result.success && options.stopOnError) {
|
|
203
|
-
stopped = true;
|
|
204
|
-
}
|
|
205
|
-
// Check timeout
|
|
206
|
-
if (options.timeout && performance.now() - startTime > options.timeout) {
|
|
207
|
-
for (let j = i + 1; j < request.commands.length; j++) {
|
|
208
|
-
const remainingCmd = request.commands[j];
|
|
209
|
-
if (!remainingCmd)
|
|
210
|
-
continue;
|
|
211
|
-
results.push({
|
|
212
|
-
id: remainingCmd.id ?? `cmd-${j}`,
|
|
213
|
-
index: j,
|
|
214
|
-
command: remainingCmd.command,
|
|
215
|
-
result: {
|
|
216
|
-
success: false,
|
|
217
|
-
error: {
|
|
218
|
-
code: 'BATCH_TIMEOUT',
|
|
219
|
-
message: `Batch timeout exceeded (${options.timeout}ms)`,
|
|
220
|
-
retryable: true,
|
|
221
|
-
},
|
|
222
|
-
},
|
|
223
|
-
durationMs: 0,
|
|
224
|
-
});
|
|
225
|
-
}
|
|
226
|
-
break;
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
const completedAt = new Date().toISOString();
|
|
230
|
-
const totalMs = performance.now() - startTime;
|
|
231
|
-
const timing = {
|
|
232
|
-
totalMs: Math.round(totalMs * 100) / 100,
|
|
233
|
-
averageMs: results.length > 0 ? Math.round((totalMs / results.length) * 100) / 100 : 0,
|
|
234
|
-
startedAt,
|
|
235
|
-
completedAt,
|
|
236
|
-
};
|
|
237
|
-
return createBatchResult(results, timing, {
|
|
238
|
-
traceId: context.traceId ?? `batch-${Date.now()}`,
|
|
239
|
-
});
|
|
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
|
-
}
|
|
400
|
-
/**
|
|
401
|
-
* Execute a command as a stream, yielding chunks.
|
|
402
|
-
*/
|
|
403
|
-
async function* executeStream(commandName, input, context = {}) {
|
|
404
|
-
const startTime = performance.now();
|
|
405
|
-
let chunksEmitted = 0;
|
|
406
|
-
try {
|
|
407
|
-
const result = await executeCommand(commandName, input, context);
|
|
408
|
-
if (!result.success) {
|
|
409
|
-
yield createErrorChunk(result.error ?? {
|
|
410
|
-
code: 'COMMAND_FAILED',
|
|
411
|
-
message: 'Command execution failed',
|
|
412
|
-
}, chunksEmitted, result.error?.retryable ?? false);
|
|
413
|
-
return;
|
|
414
|
-
}
|
|
415
|
-
const data = result.data;
|
|
416
|
-
// If result is an array, emit each item as a chunk
|
|
417
|
-
if (Array.isArray(data)) {
|
|
418
|
-
for (let i = 0; i < data.length; i++) {
|
|
419
|
-
yield {
|
|
420
|
-
type: 'data',
|
|
421
|
-
data: data[i],
|
|
422
|
-
index: i,
|
|
423
|
-
isLast: i === data.length - 1,
|
|
424
|
-
};
|
|
425
|
-
chunksEmitted++;
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
else {
|
|
429
|
-
yield {
|
|
430
|
-
type: 'data',
|
|
431
|
-
data: data,
|
|
432
|
-
index: 0,
|
|
433
|
-
isLast: true,
|
|
434
|
-
};
|
|
435
|
-
chunksEmitted++;
|
|
436
|
-
}
|
|
437
|
-
// Emit completion
|
|
438
|
-
const totalDurationMs = performance.now() - startTime;
|
|
439
|
-
yield createCompleteChunk(chunksEmitted, totalDurationMs, {
|
|
440
|
-
confidence: result.confidence,
|
|
441
|
-
reasoning: result.reasoning,
|
|
442
|
-
metadata: result.metadata,
|
|
443
|
-
});
|
|
444
|
-
}
|
|
445
|
-
catch (error) {
|
|
446
|
-
yield createErrorChunk({
|
|
447
|
-
code: 'STREAM_ERROR',
|
|
448
|
-
message: error instanceof Error ? error.message : String(error),
|
|
449
|
-
retryable: true,
|
|
450
|
-
}, chunksEmitted, true);
|
|
451
|
-
}
|
|
452
|
-
}
|
|
453
|
-
/**
|
|
454
|
-
* Get the tools list based on toolStrategy.
|
|
455
|
-
*/
|
|
456
|
-
function getToolsList() {
|
|
457
|
-
// Built-in afd-batch tool (always individual)
|
|
458
|
-
const batchTool = {
|
|
459
|
-
name: 'afd-batch',
|
|
460
|
-
description: 'Execute multiple commands in a single batch request with partial success semantics',
|
|
461
|
-
inputSchema: {
|
|
462
|
-
type: 'object',
|
|
463
|
-
properties: {
|
|
464
|
-
commands: {
|
|
465
|
-
type: 'array',
|
|
466
|
-
description: 'Array of commands to execute',
|
|
467
|
-
items: {
|
|
468
|
-
type: 'object',
|
|
469
|
-
properties: {
|
|
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' },
|
|
476
|
-
},
|
|
477
|
-
required: ['command'],
|
|
478
|
-
},
|
|
479
|
-
},
|
|
480
|
-
options: {
|
|
481
|
-
type: 'object',
|
|
482
|
-
description: 'Batch execution options',
|
|
483
|
-
properties: {
|
|
484
|
-
stopOnError: { type: 'boolean', description: 'Stop execution on first error' },
|
|
485
|
-
timeout: { type: 'number', description: 'Timeout in milliseconds for entire batch' },
|
|
486
|
-
},
|
|
487
|
-
},
|
|
488
|
-
},
|
|
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'],
|
|
538
|
-
},
|
|
539
|
-
};
|
|
540
|
-
// Individual strategy: each command is its own tool
|
|
541
|
-
if (toolStrategy === 'individual') {
|
|
542
|
-
return [
|
|
543
|
-
batchTool,
|
|
544
|
-
pipeTool,
|
|
545
|
-
...commands.map((cmd) => {
|
|
546
|
-
const { type: _type, ...restSchema } = cmd.jsonSchema;
|
|
547
|
-
const hasMeta = (cmd.requires && cmd.requires.length > 0) || cmd.mutation != null;
|
|
548
|
-
return {
|
|
549
|
-
name: cmd.name,
|
|
550
|
-
description: cmd.description,
|
|
551
|
-
inputSchema: {
|
|
552
|
-
type: 'object',
|
|
553
|
-
...restSchema,
|
|
554
|
-
},
|
|
555
|
-
...(hasMeta && {
|
|
556
|
-
_meta: {
|
|
557
|
-
...(cmd.requires?.length && { requires: cmd.requires }),
|
|
558
|
-
...(cmd.mutation != null && { mutation: cmd.mutation }),
|
|
559
|
-
},
|
|
560
|
-
}),
|
|
561
|
-
};
|
|
562
|
-
}),
|
|
563
|
-
];
|
|
564
|
-
}
|
|
565
|
-
// Grouped strategy: commands grouped by category/entity
|
|
566
|
-
const defaultGroupFn = (cmd) => {
|
|
567
|
-
return cmd.category || cmd.name.split('-')[0] || 'general';
|
|
568
|
-
};
|
|
569
|
-
const getGroup = groupByFn || defaultGroupFn;
|
|
570
|
-
// Group commands by their group key
|
|
571
|
-
const groups = {};
|
|
572
|
-
for (const cmd of commands) {
|
|
573
|
-
const group = getGroup(cmd) || 'general';
|
|
574
|
-
if (!groups[group]) {
|
|
575
|
-
groups[group] = [];
|
|
576
|
-
}
|
|
577
|
-
groups[group].push(cmd);
|
|
578
|
-
}
|
|
579
|
-
// Create a consolidated tool for each group
|
|
580
|
-
const groupedTools = Object.entries(groups).map(([groupName, groupCmds]) => {
|
|
581
|
-
// Build action enum from command names
|
|
582
|
-
const actions = groupCmds.map((cmd) => {
|
|
583
|
-
// Extract action from command name (e.g., "todo-create" -> "create")
|
|
584
|
-
const parts = cmd.name.split('-');
|
|
585
|
-
return parts.length > 1 ? parts.slice(1).join('-') : cmd.name;
|
|
586
|
-
});
|
|
587
|
-
return {
|
|
588
|
-
name: groupName,
|
|
589
|
-
description: `${groupName} operations: ${actions.join(', ')}`,
|
|
590
|
-
inputSchema: {
|
|
591
|
-
type: 'object',
|
|
592
|
-
properties: {
|
|
593
|
-
action: {
|
|
594
|
-
type: 'string',
|
|
595
|
-
enum: actions,
|
|
596
|
-
description: `Action to perform: ${actions.join(' | ')}`,
|
|
597
|
-
},
|
|
598
|
-
// Note: Full discriminated union would require merging all command schemas
|
|
599
|
-
// For now, we use a generic "params" object
|
|
600
|
-
params: {
|
|
601
|
-
type: 'object',
|
|
602
|
-
description: 'Parameters for the action (varies by action)',
|
|
603
|
-
},
|
|
604
|
-
},
|
|
605
|
-
required: ['action'],
|
|
606
|
-
},
|
|
607
|
-
};
|
|
608
|
-
});
|
|
609
|
-
return [batchTool, pipeTool, ...groupedTools];
|
|
610
|
-
}
|
|
611
|
-
/**
|
|
612
|
-
* Handle MCP JSON-RPC request.
|
|
613
|
-
*/
|
|
614
|
-
function handleMcpRequest(request) {
|
|
615
|
-
const { id, method } = request;
|
|
616
|
-
switch (method) {
|
|
617
|
-
case 'initialize':
|
|
618
|
-
return {
|
|
619
|
-
jsonrpc: '2.0',
|
|
620
|
-
id,
|
|
621
|
-
result: {
|
|
622
|
-
protocolVersion: '2024-11-05',
|
|
623
|
-
capabilities: {
|
|
624
|
-
tools: {},
|
|
625
|
-
},
|
|
626
|
-
serverInfo: {
|
|
627
|
-
name,
|
|
628
|
-
version,
|
|
629
|
-
},
|
|
630
|
-
},
|
|
631
|
-
};
|
|
632
|
-
case 'tools/list':
|
|
633
|
-
return {
|
|
634
|
-
jsonrpc: '2.0',
|
|
635
|
-
id,
|
|
636
|
-
result: {
|
|
637
|
-
tools: getToolsList(),
|
|
638
|
-
},
|
|
639
|
-
};
|
|
640
|
-
case 'notifications/initialized':
|
|
641
|
-
// Client notification, no response needed for notifications
|
|
642
|
-
// but we return a success for acknowledgment
|
|
643
|
-
return {
|
|
644
|
-
jsonrpc: '2.0',
|
|
645
|
-
id,
|
|
646
|
-
result: {},
|
|
647
|
-
};
|
|
648
|
-
default:
|
|
649
|
-
return {
|
|
650
|
-
jsonrpc: '2.0',
|
|
651
|
-
id,
|
|
652
|
-
error: {
|
|
653
|
-
code: -32601,
|
|
654
|
-
message: `Method not found: ${method}`,
|
|
655
|
-
},
|
|
656
|
-
};
|
|
657
|
-
}
|
|
658
|
-
}
|
|
659
|
-
/**
|
|
660
|
-
* Handle async MCP request (tools/call).
|
|
661
|
-
*/
|
|
662
|
-
async function handleAsyncMcpRequest(request) {
|
|
663
|
-
const { id, method, params } = request;
|
|
664
|
-
if (method === 'tools/call') {
|
|
665
|
-
const { name: toolName, arguments: args } = params;
|
|
666
|
-
// Handle built-in afd-batch tool
|
|
667
|
-
if (toolName === 'afd-batch') {
|
|
668
|
-
const batchRequest = args;
|
|
669
|
-
const result = await executeBatch(batchRequest, {
|
|
670
|
-
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
671
|
-
});
|
|
672
|
-
return {
|
|
673
|
-
jsonrpc: '2.0',
|
|
674
|
-
id,
|
|
675
|
-
result: {
|
|
676
|
-
content: [
|
|
677
|
-
{
|
|
678
|
-
type: 'text',
|
|
679
|
-
text: JSON.stringify(result, null, 2),
|
|
680
|
-
},
|
|
681
|
-
],
|
|
682
|
-
isError: !result.success,
|
|
683
|
-
},
|
|
684
|
-
};
|
|
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
|
-
}
|
|
737
|
-
// Handle grouped tool calls (when toolStrategy === "grouped")
|
|
738
|
-
if (toolStrategy === 'grouped') {
|
|
739
|
-
const typedArgs = args;
|
|
740
|
-
const action = typedArgs?.action;
|
|
741
|
-
const commandParams = typedArgs?.params ?? {};
|
|
742
|
-
if (action && typeof action === 'string') {
|
|
743
|
-
// Construct actual command name: groupName-action
|
|
744
|
-
const actualCommandName = `${toolName}-${action}`;
|
|
745
|
-
const result = await executeCommand(actualCommandName, commandParams, {
|
|
746
|
-
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
747
|
-
});
|
|
748
|
-
return {
|
|
749
|
-
jsonrpc: '2.0',
|
|
750
|
-
id,
|
|
751
|
-
result: {
|
|
752
|
-
content: [
|
|
753
|
-
{
|
|
754
|
-
type: 'text',
|
|
755
|
-
text: JSON.stringify(result, null, 2),
|
|
756
|
-
},
|
|
757
|
-
],
|
|
758
|
-
isError: !result.success,
|
|
759
|
-
},
|
|
760
|
-
};
|
|
761
|
-
}
|
|
762
|
-
}
|
|
763
|
-
// Handle user-defined commands (individual mode)
|
|
764
|
-
const result = await executeCommand(toolName, args ?? {}, {
|
|
765
|
-
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
766
|
-
});
|
|
767
|
-
return {
|
|
768
|
-
jsonrpc: '2.0',
|
|
769
|
-
id,
|
|
770
|
-
result: {
|
|
771
|
-
content: [
|
|
772
|
-
{
|
|
773
|
-
type: 'text',
|
|
774
|
-
text: JSON.stringify(result, null, 2),
|
|
775
|
-
},
|
|
776
|
-
],
|
|
777
|
-
isError: !result.success,
|
|
778
|
-
},
|
|
779
|
-
};
|
|
780
|
-
}
|
|
781
|
-
// Fall back to sync handler for other methods
|
|
782
|
-
return handleMcpRequest(request);
|
|
783
|
-
}
|
|
784
|
-
/**
|
|
785
|
-
* Send SSE event to a client.
|
|
786
|
-
*/
|
|
787
|
-
function sendSseEvent(client, event, data) {
|
|
788
|
-
const message = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
789
|
-
client.response.write(message);
|
|
790
|
-
}
|
|
791
|
-
/**
|
|
792
|
-
* Create HTTP request handler.
|
|
793
|
-
*/
|
|
794
|
-
function createRequestHandler() {
|
|
795
|
-
return async (req, res) => {
|
|
796
|
-
// CORS headers - restrictive in production, permissive in dev mode
|
|
797
|
-
if (cors) {
|
|
798
|
-
// In dev mode, allow all origins; in production, allow same-origin or configured origins
|
|
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');
|
|
802
|
-
}
|
|
803
|
-
// Handle preflight
|
|
804
|
-
if (req.method === 'OPTIONS') {
|
|
805
|
-
res.writeHead(204);
|
|
806
|
-
res.end();
|
|
807
|
-
return;
|
|
808
|
-
}
|
|
809
|
-
const url = new URL(req.url ?? '/', `http://${req.headers.host}`);
|
|
810
|
-
// SSE endpoint
|
|
811
|
-
if (url.pathname === '/sse' && req.method === 'GET') {
|
|
812
|
-
const clientId = `client-${++clientIdCounter}`;
|
|
813
|
-
res.writeHead(200, {
|
|
814
|
-
'Content-Type': 'text/event-stream',
|
|
815
|
-
'Cache-Control': 'no-cache',
|
|
816
|
-
Connection: 'keep-alive',
|
|
817
|
-
});
|
|
818
|
-
const client = { id: clientId, response: res };
|
|
819
|
-
sseClients.set(clientId, client);
|
|
820
|
-
// Send endpoint info
|
|
821
|
-
sendSseEvent(client, 'endpoint', {
|
|
822
|
-
url: `http://${host}:${port}/message`,
|
|
823
|
-
});
|
|
824
|
-
// Handle client disconnect
|
|
825
|
-
req.on('close', () => {
|
|
826
|
-
sseClients.delete(clientId);
|
|
827
|
-
});
|
|
828
|
-
return;
|
|
829
|
-
}
|
|
830
|
-
// Message endpoint
|
|
831
|
-
if (url.pathname === '/message' && req.method === 'POST') {
|
|
832
|
-
let body = '';
|
|
833
|
-
for await (const chunk of req) {
|
|
834
|
-
body += chunk;
|
|
835
|
-
}
|
|
836
|
-
try {
|
|
837
|
-
const request = JSON.parse(body);
|
|
838
|
-
const response = await handleAsyncMcpRequest(request);
|
|
839
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
840
|
-
res.end(JSON.stringify(response));
|
|
841
|
-
}
|
|
842
|
-
catch (_error) {
|
|
843
|
-
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
844
|
-
res.end(JSON.stringify({
|
|
845
|
-
jsonrpc: '2.0',
|
|
846
|
-
id: null,
|
|
847
|
-
error: {
|
|
848
|
-
code: -32700,
|
|
849
|
-
message: 'Parse error',
|
|
850
|
-
},
|
|
851
|
-
}));
|
|
852
|
-
}
|
|
853
|
-
return;
|
|
854
|
-
}
|
|
855
|
-
// Health check
|
|
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
|
-
}
|
|
906
|
-
return;
|
|
907
|
-
}
|
|
908
|
-
// Batch endpoint
|
|
909
|
-
if (url.pathname === '/batch' && req.method === 'POST') {
|
|
910
|
-
let body = '';
|
|
911
|
-
for await (const chunk of req) {
|
|
912
|
-
body += chunk;
|
|
913
|
-
}
|
|
914
|
-
try {
|
|
915
|
-
const batchRequest = JSON.parse(body);
|
|
916
|
-
if (!isBatchRequest(batchRequest)) {
|
|
917
|
-
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
918
|
-
res.end(JSON.stringify({
|
|
919
|
-
success: false,
|
|
920
|
-
error: {
|
|
921
|
-
code: 'INVALID_BATCH_REQUEST',
|
|
922
|
-
message: 'Invalid batch request format',
|
|
923
|
-
suggestion: 'Provide { commands: [...] } with command objects',
|
|
924
|
-
},
|
|
925
|
-
}));
|
|
926
|
-
return;
|
|
927
|
-
}
|
|
928
|
-
const result = await executeBatch(batchRequest, {
|
|
929
|
-
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
930
|
-
});
|
|
931
|
-
res.writeHead(200, { 'Content-Type': 'application/json' });
|
|
932
|
-
res.end(JSON.stringify(result));
|
|
933
|
-
}
|
|
934
|
-
catch (_error) {
|
|
935
|
-
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
936
|
-
res.end(JSON.stringify({
|
|
937
|
-
success: false,
|
|
938
|
-
error: {
|
|
939
|
-
code: 'PARSE_ERROR',
|
|
940
|
-
message: 'Failed to parse batch request',
|
|
941
|
-
suggestion: 'Ensure request body is valid JSON',
|
|
942
|
-
},
|
|
943
|
-
}));
|
|
944
|
-
}
|
|
945
|
-
return;
|
|
946
|
-
}
|
|
947
|
-
// Stream endpoint - SSE for streaming command results
|
|
948
|
-
if (url.pathname.startsWith('/stream/') && req.method === 'GET') {
|
|
949
|
-
const commandName = url.pathname.slice('/stream/'.length);
|
|
950
|
-
const inputParam = url.searchParams.get('input');
|
|
951
|
-
let input = {};
|
|
952
|
-
if (inputParam) {
|
|
953
|
-
try {
|
|
954
|
-
input = JSON.parse(inputParam);
|
|
955
|
-
}
|
|
956
|
-
catch {
|
|
957
|
-
res.writeHead(400, { 'Content-Type': 'application/json' });
|
|
958
|
-
res.end(JSON.stringify({
|
|
959
|
-
success: false,
|
|
960
|
-
error: {
|
|
961
|
-
code: 'INVALID_INPUT',
|
|
962
|
-
message: 'Failed to parse input parameter',
|
|
963
|
-
suggestion: 'Ensure input is valid JSON',
|
|
964
|
-
},
|
|
965
|
-
}));
|
|
966
|
-
return;
|
|
967
|
-
}
|
|
968
|
-
}
|
|
969
|
-
// Set up SSE response
|
|
970
|
-
res.writeHead(200, {
|
|
971
|
-
'Content-Type': 'text/event-stream',
|
|
972
|
-
'Cache-Control': 'no-cache',
|
|
973
|
-
Connection: 'keep-alive',
|
|
974
|
-
});
|
|
975
|
-
const context = {
|
|
976
|
-
traceId: `stream-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
977
|
-
};
|
|
978
|
-
// Handle client disconnect
|
|
979
|
-
let aborted = false;
|
|
980
|
-
req.on('close', () => {
|
|
981
|
-
aborted = true;
|
|
982
|
-
});
|
|
983
|
-
// Stream the command execution
|
|
984
|
-
try {
|
|
985
|
-
for await (const chunk of executeStream(commandName, input, context)) {
|
|
986
|
-
if (aborted)
|
|
987
|
-
break;
|
|
988
|
-
res.write(`event: chunk\ndata: ${JSON.stringify(chunk)}\n\n`);
|
|
989
|
-
}
|
|
990
|
-
}
|
|
991
|
-
catch (error) {
|
|
992
|
-
const errorChunk = createErrorChunk({
|
|
993
|
-
code: 'STREAM_ERROR',
|
|
994
|
-
message: error instanceof Error ? error.message : String(error),
|
|
995
|
-
retryable: true,
|
|
996
|
-
}, 0, true);
|
|
997
|
-
res.write(`event: chunk\ndata: ${JSON.stringify(errorChunk)}\n\n`);
|
|
998
|
-
}
|
|
999
|
-
res.end();
|
|
1000
|
-
return;
|
|
1001
|
-
}
|
|
1002
|
-
// Not found
|
|
1003
|
-
res.writeHead(404, { 'Content-Type': 'application/json' });
|
|
1004
|
-
res.end(JSON.stringify({ error: 'Not found' }));
|
|
1005
|
-
};
|
|
1006
|
-
}
|
|
1007
|
-
// Track MCP SDK server for stdio transport cleanup
|
|
1008
85
|
let mcpSdkServer = null;
|
|
86
|
+
let isRunning = false;
|
|
87
|
+
// ── Public API ──────────────────────────────────────────────────────────
|
|
1009
88
|
return {
|
|
1010
89
|
async start() {
|
|
1011
|
-
if (isRunning)
|
|
90
|
+
if (isRunning)
|
|
1012
91
|
return;
|
|
1013
|
-
|
|
1014
|
-
// Start stdio transport if enabled using official MCP SDK
|
|
92
|
+
// Stdio transport via MCP SDK
|
|
1015
93
|
if (useStdio) {
|
|
1016
94
|
mcpSdkServer = new McpSdkServer({ name, version }, { capabilities: { tools: {} } });
|
|
1017
|
-
// Register tools/list handler - use shared getToolsList() for consistency
|
|
1018
95
|
mcpSdkServer.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
1019
|
-
tools:
|
|
96
|
+
tools: boundGetToolsList(),
|
|
1020
97
|
}));
|
|
1021
|
-
// Register tools/call handler
|
|
1022
98
|
mcpSdkServer.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
// Handle built-in afd.batch tool
|
|
1026
|
-
if (toolName === 'afd-batch') {
|
|
1027
|
-
// Validate that args looks like a BatchRequest before processing
|
|
1028
|
-
if (!isBatchRequest(args)) {
|
|
1029
|
-
return {
|
|
1030
|
-
content: [
|
|
1031
|
-
{
|
|
1032
|
-
type: 'text',
|
|
1033
|
-
text: JSON.stringify({
|
|
1034
|
-
success: false,
|
|
1035
|
-
error: {
|
|
1036
|
-
code: 'INVALID_BATCH_REQUEST',
|
|
1037
|
-
message: 'Invalid batch request format',
|
|
1038
|
-
suggestion: 'Provide { commands: [...] } with command objects',
|
|
1039
|
-
},
|
|
1040
|
-
}, null, 2),
|
|
1041
|
-
},
|
|
1042
|
-
],
|
|
1043
|
-
isError: true,
|
|
1044
|
-
};
|
|
1045
|
-
}
|
|
1046
|
-
const result = await executeBatch(args, {
|
|
1047
|
-
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
1048
|
-
});
|
|
1049
|
-
return {
|
|
1050
|
-
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
1051
|
-
isError: !result.success,
|
|
1052
|
-
};
|
|
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
|
-
}
|
|
1092
|
-
// Handle grouped tool calls (when toolStrategy === "grouped")
|
|
1093
|
-
// Grouped tools have format: { action: "create", params: {...} }
|
|
1094
|
-
if (toolStrategy === 'grouped') {
|
|
1095
|
-
const action = args.action;
|
|
1096
|
-
const params = args.params ?? {};
|
|
1097
|
-
// Debug logging when enabled
|
|
1098
|
-
if (devMode) {
|
|
1099
|
-
console.error(`[MCP Debug] Grouped tool call: toolName=${toolName}, action=${action}, args=${JSON.stringify(args)}`);
|
|
1100
|
-
}
|
|
1101
|
-
// Check if this is a grouped tool call (has action property)
|
|
1102
|
-
if (action && typeof action === 'string') {
|
|
1103
|
-
// Construct the actual command name: groupName-action
|
|
1104
|
-
// e.g., "todo" + "create" = "todo-create"
|
|
1105
|
-
const actualCommandName = `${toolName}-${action}`;
|
|
1106
|
-
// Execute the actual command
|
|
1107
|
-
const result = await executeCommand(actualCommandName, params, {
|
|
1108
|
-
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
1109
|
-
});
|
|
1110
|
-
return {
|
|
1111
|
-
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
1112
|
-
isError: !result.success,
|
|
1113
|
-
};
|
|
1114
|
-
}
|
|
1115
|
-
// In grouped mode, if tool is a known group but action is missing/invalid,
|
|
1116
|
-
// return a helpful error instead of falling through
|
|
1117
|
-
const groupNames = new Set(commands.map((cmd) => {
|
|
1118
|
-
const defaultGroupFn = (c) => c.category || c.name.split('-')[0] || 'general';
|
|
1119
|
-
return (groupByFn || defaultGroupFn)(cmd);
|
|
1120
|
-
}));
|
|
1121
|
-
if (groupNames.has(toolName)) {
|
|
1122
|
-
const groupCommands = commands.filter((cmd) => {
|
|
1123
|
-
const defaultGroupFn = (c) => c.category || c.name.split('-')[0] || 'general';
|
|
1124
|
-
return (groupByFn || defaultGroupFn)(cmd) === toolName;
|
|
1125
|
-
});
|
|
1126
|
-
const availableActions = groupCommands.map((cmd) => {
|
|
1127
|
-
const parts = cmd.name.split('-');
|
|
1128
|
-
return parts.length > 1 ? parts.slice(1).join('-') : cmd.name;
|
|
1129
|
-
});
|
|
1130
|
-
return {
|
|
1131
|
-
content: [
|
|
1132
|
-
{
|
|
1133
|
-
type: 'text',
|
|
1134
|
-
text: JSON.stringify({
|
|
1135
|
-
success: false,
|
|
1136
|
-
error: {
|
|
1137
|
-
code: 'INVALID_GROUPED_CALL',
|
|
1138
|
-
message: `Grouped tool '${toolName}' requires an 'action' parameter`,
|
|
1139
|
-
suggestion: `Provide { action: "<action>", params: {...} }. Available actions: ${availableActions.join(', ')}`,
|
|
1140
|
-
},
|
|
1141
|
-
_debug: devMode ? { receivedArgs: args } : undefined,
|
|
1142
|
-
}, null, 2),
|
|
1143
|
-
},
|
|
1144
|
-
],
|
|
1145
|
-
isError: true,
|
|
1146
|
-
};
|
|
1147
|
-
}
|
|
1148
|
-
}
|
|
1149
|
-
// Handle user-defined commands (individual mode or direct command calls)
|
|
1150
|
-
const result = await executeCommand(toolName, args, {
|
|
1151
|
-
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
1152
|
-
});
|
|
1153
|
-
return {
|
|
1154
|
-
content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
|
|
1155
|
-
isError: !result.success,
|
|
1156
|
-
};
|
|
99
|
+
// Spread into anonymous object for MCP SDK index signature compatibility
|
|
100
|
+
return { ...(await routeToolCall(request.params.name, request.params.arguments ?? {})) };
|
|
1157
101
|
});
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
await mcpSdkServer.connect(transport);
|
|
102
|
+
const stdioTransport = new StdioServerTransport();
|
|
103
|
+
await mcpSdkServer.connect(stdioTransport);
|
|
1161
104
|
isRunning = true;
|
|
1162
|
-
|
|
1163
|
-
if (!useHttp) {
|
|
105
|
+
if (!useHttp)
|
|
1164
106
|
return;
|
|
1165
|
-
}
|
|
1166
107
|
}
|
|
1167
|
-
//
|
|
108
|
+
// HTTP transport
|
|
1168
109
|
if (useHttp) {
|
|
1169
|
-
|
|
110
|
+
const { handler } = createHttpHandler({
|
|
111
|
+
name,
|
|
112
|
+
version,
|
|
113
|
+
host,
|
|
114
|
+
port,
|
|
115
|
+
cors,
|
|
116
|
+
devMode,
|
|
117
|
+
getToolsList: boundGetToolsList,
|
|
118
|
+
routeToolCall,
|
|
119
|
+
executeCommand: engine.executeCommand,
|
|
120
|
+
executeBatch: engine.executeBatch,
|
|
121
|
+
executeStream: engine.executeStream,
|
|
122
|
+
});
|
|
123
|
+
httpServer = createServer(handler);
|
|
1170
124
|
await new Promise((resolve, reject) => {
|
|
1171
125
|
httpServer?.on('error', reject);
|
|
1172
126
|
httpServer?.listen(port, host, () => {
|
|
@@ -1177,21 +131,13 @@ export function createMcpServer(options) {
|
|
|
1177
131
|
}
|
|
1178
132
|
},
|
|
1179
133
|
async stop() {
|
|
1180
|
-
if (!isRunning)
|
|
134
|
+
if (!isRunning)
|
|
1181
135
|
return;
|
|
1182
|
-
}
|
|
1183
|
-
// Close MCP SDK server if it exists
|
|
1184
136
|
if (mcpSdkServer) {
|
|
1185
137
|
await mcpSdkServer.close();
|
|
1186
138
|
mcpSdkServer = null;
|
|
1187
139
|
}
|
|
1188
|
-
// Close HTTP server if it exists
|
|
1189
140
|
if (httpServer) {
|
|
1190
|
-
// Close all SSE clients
|
|
1191
|
-
for (const client of sseClients.values()) {
|
|
1192
|
-
client.response.end();
|
|
1193
|
-
}
|
|
1194
|
-
sseClients.clear();
|
|
1195
141
|
await new Promise((resolve, reject) => {
|
|
1196
142
|
httpServer?.close((err) => {
|
|
1197
143
|
if (err)
|
|
@@ -1210,15 +156,11 @@ export function createMcpServer(options) {
|
|
|
1210
156
|
getCommands() {
|
|
1211
157
|
return commands;
|
|
1212
158
|
},
|
|
1213
|
-
/**
|
|
1214
|
-
* Get the resolved transport mode.
|
|
1215
|
-
* Useful for debugging and logging.
|
|
1216
|
-
*/
|
|
1217
159
|
getTransport() {
|
|
1218
160
|
return resolvedTransport;
|
|
1219
161
|
},
|
|
1220
|
-
execute: executeCommand,
|
|
1221
|
-
executePipeline,
|
|
162
|
+
execute: engine.executeCommand,
|
|
163
|
+
executePipeline: engine.executePipeline,
|
|
1222
164
|
};
|
|
1223
165
|
}
|
|
1224
166
|
//# sourceMappingURL=server.js.map
|