@lushly-dev/afd-server 0.1.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 +26 -0
- package/README.md +381 -0
- package/dist/bootstrap/afd-docs.d.ts +27 -0
- package/dist/bootstrap/afd-docs.d.ts.map +1 -0
- package/dist/bootstrap/afd-docs.js +93 -0
- package/dist/bootstrap/afd-docs.js.map +1 -0
- package/dist/bootstrap/afd-help.d.ts +39 -0
- package/dist/bootstrap/afd-help.d.ts.map +1 -0
- package/dist/bootstrap/afd-help.js +77 -0
- package/dist/bootstrap/afd-help.js.map +1 -0
- package/dist/bootstrap/afd-schema.d.ts +34 -0
- package/dist/bootstrap/afd-schema.d.ts.map +1 -0
- package/dist/bootstrap/afd-schema.js +78 -0
- package/dist/bootstrap/afd-schema.js.map +1 -0
- package/dist/bootstrap/index.d.ts +11 -0
- package/dist/bootstrap/index.d.ts.map +1 -0
- package/dist/bootstrap/index.js +11 -0
- package/dist/bootstrap/index.js.map +1 -0
- package/dist/bootstrap/registry.d.ts +17 -0
- package/dist/bootstrap/registry.d.ts.map +1 -0
- package/dist/bootstrap/registry.js +23 -0
- package/dist/bootstrap/registry.js.map +1 -0
- package/dist/index.d.ts +54 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +60 -0
- package/dist/index.js.map +1 -0
- package/dist/middleware.d.ts +125 -0
- package/dist/middleware.d.ts.map +1 -0
- package/dist/middleware.js +182 -0
- package/dist/middleware.js.map +1 -0
- package/dist/schema.d.ts +105 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +132 -0
- package/dist/schema.js.map +1 -0
- package/dist/server.d.ts +141 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +846 -0
- package/dist/server.js.map +1 -0
- package/dist/validation.d.ts +137 -0
- package/dist/validation.d.ts.map +1 -0
- package/dist/validation.js +182 -0
- package/dist/validation.js.map +1 -0
- package/package.json +48 -0
package/dist/server.js
ADDED
|
@@ -0,0 +1,846 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @fileoverview MCP Server factory for AFD commands
|
|
3
|
+
*
|
|
4
|
+
* This module provides utilities for creating MCP-compliant servers
|
|
5
|
+
* from Zod-defined commands.
|
|
6
|
+
*/
|
|
7
|
+
import { createServer } from "node:http";
|
|
8
|
+
import { calculateBatchConfidence, createBatchResult, createCompleteChunk, createErrorChunk, createFailedBatchResult, failure, isBatchRequest, } 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 { ListToolsRequestSchema, CallToolRequestSchema, } from "@modelcontextprotocol/sdk/types.js";
|
|
12
|
+
import { validateInput } from "./validation.js";
|
|
13
|
+
/**
|
|
14
|
+
* Detect whether stdin is being piped (non-TTY).
|
|
15
|
+
* Used for auto-detection of transport mode.
|
|
16
|
+
*
|
|
17
|
+
* @returns true if stdin is a pipe (not interactive), false if it's a TTY
|
|
18
|
+
*/
|
|
19
|
+
export function isStdinPiped() {
|
|
20
|
+
return !process.stdin.isTTY;
|
|
21
|
+
}
|
|
22
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
23
|
+
// SERVER FACTORY
|
|
24
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
25
|
+
/**
|
|
26
|
+
* Create an MCP server from Zod-defined commands.
|
|
27
|
+
*
|
|
28
|
+
* @example
|
|
29
|
+
* ```typescript
|
|
30
|
+
* import { createMcpServer, defineCommand } from '@lushly-dev/afd-server';
|
|
31
|
+
*
|
|
32
|
+
* const server = createMcpServer({
|
|
33
|
+
* name: 'my-app',
|
|
34
|
+
* version: '1.0.0',
|
|
35
|
+
* commands: [createTodo, listTodos, deleteTodo],
|
|
36
|
+
* });
|
|
37
|
+
*
|
|
38
|
+
* await server.start();
|
|
39
|
+
* console.log(`Server running at ${server.getUrl()}`);
|
|
40
|
+
* ```
|
|
41
|
+
*/
|
|
42
|
+
export function createMcpServer(options) {
|
|
43
|
+
const { name, version, commands, port = 3100, host = "localhost", devMode = false,
|
|
44
|
+
// In dev mode, CORS is permissive by default; in production, it's off by default
|
|
45
|
+
cors = devMode, transport = "auto", stdio, // deprecated, for backward compatibility
|
|
46
|
+
middleware = [], onCommand, onError, toolStrategy = "grouped", groupByFn, } = options;
|
|
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
|
|
51
|
+
function resolveTransport() {
|
|
52
|
+
// Handle deprecated stdio option for backward compatibility
|
|
53
|
+
if (stdio !== undefined) {
|
|
54
|
+
return stdio ? "stdio" : "http";
|
|
55
|
+
}
|
|
56
|
+
// Auto-detect: use stdio if stdin is piped (not a TTY), otherwise use HTTP
|
|
57
|
+
if (transport === "auto") {
|
|
58
|
+
return isStdinPiped() ? "stdio" : "http";
|
|
59
|
+
}
|
|
60
|
+
// Explicit transport mode (stdio or http)
|
|
61
|
+
return transport;
|
|
62
|
+
}
|
|
63
|
+
const resolvedTransport = resolveTransport();
|
|
64
|
+
const useStdio = resolvedTransport === "stdio";
|
|
65
|
+
const useHttp = resolvedTransport === "http";
|
|
66
|
+
// Build command map for quick lookup
|
|
67
|
+
const commandMap = new Map();
|
|
68
|
+
for (const cmd of commands) {
|
|
69
|
+
commandMap.set(cmd.name, cmd);
|
|
70
|
+
}
|
|
71
|
+
// Track SSE clients
|
|
72
|
+
const sseClients = new Map();
|
|
73
|
+
let clientIdCounter = 0;
|
|
74
|
+
// HTTP Server
|
|
75
|
+
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
|
|
90
|
+
const validation = validateInput(command.inputSchema, input);
|
|
91
|
+
if (!validation.success) {
|
|
92
|
+
return failure({
|
|
93
|
+
code: "VALIDATION_ERROR",
|
|
94
|
+
message: "Input validation failed",
|
|
95
|
+
suggestion: validation.errors.map((e) => e.message).join("; "),
|
|
96
|
+
details: { errors: validation.errors },
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
// Build middleware chain
|
|
100
|
+
const runHandler = async () => {
|
|
101
|
+
const startTime = Date.now();
|
|
102
|
+
const result = await command.handler(validation.data, context);
|
|
103
|
+
// Add metadata if not present
|
|
104
|
+
if (!result.metadata) {
|
|
105
|
+
result.metadata = {};
|
|
106
|
+
}
|
|
107
|
+
result.metadata.executionTimeMs = Date.now() - startTime;
|
|
108
|
+
result.metadata.commandVersion = command.version;
|
|
109
|
+
if (context.traceId) {
|
|
110
|
+
result.metadata.traceId = context.traceId;
|
|
111
|
+
}
|
|
112
|
+
return result;
|
|
113
|
+
};
|
|
114
|
+
// Apply middleware in reverse order
|
|
115
|
+
let next = runHandler;
|
|
116
|
+
for (let i = middleware.length - 1; i >= 0; i--) {
|
|
117
|
+
const mw = middleware[i];
|
|
118
|
+
const currentNext = next;
|
|
119
|
+
next = () => mw(commandName, validation.data, context, currentNext);
|
|
120
|
+
}
|
|
121
|
+
try {
|
|
122
|
+
const result = await next();
|
|
123
|
+
onCommand?.(commandName, input, result);
|
|
124
|
+
return result;
|
|
125
|
+
}
|
|
126
|
+
catch (error) {
|
|
127
|
+
const err = error instanceof Error ? error : new Error(String(error));
|
|
128
|
+
onError?.(err);
|
|
129
|
+
return failure({
|
|
130
|
+
code: "COMMAND_EXECUTION_ERROR",
|
|
131
|
+
message: devMode ? err.message : "An internal error occurred",
|
|
132
|
+
suggestion: devMode
|
|
133
|
+
? "Check the command implementation"
|
|
134
|
+
: "Contact support if this persists",
|
|
135
|
+
// Only include stack traces in dev mode to prevent information leakage
|
|
136
|
+
...(devMode ? { details: { stack: err.stack } } : {}),
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* Execute multiple commands in a batch with partial success semantics.
|
|
142
|
+
*/
|
|
143
|
+
async function executeBatch(request, context = {}) {
|
|
144
|
+
const startedAt = new Date().toISOString();
|
|
145
|
+
const startTime = performance.now();
|
|
146
|
+
// Validate request
|
|
147
|
+
if (!request.commands || request.commands.length === 0) {
|
|
148
|
+
return createFailedBatchResult({
|
|
149
|
+
code: "INVALID_BATCH_REQUEST",
|
|
150
|
+
message: "Batch request must contain at least one command",
|
|
151
|
+
suggestion: "Provide an array of commands to execute",
|
|
152
|
+
}, { startedAt });
|
|
153
|
+
}
|
|
154
|
+
const options = request.options ?? {};
|
|
155
|
+
const results = [];
|
|
156
|
+
let stopped = false;
|
|
157
|
+
// Execute commands sequentially
|
|
158
|
+
for (let i = 0; i < request.commands.length; i++) {
|
|
159
|
+
const cmd = request.commands[i];
|
|
160
|
+
if (stopped) {
|
|
161
|
+
results.push({
|
|
162
|
+
id: cmd.id ?? `cmd-${i}`,
|
|
163
|
+
index: i,
|
|
164
|
+
command: cmd.command,
|
|
165
|
+
result: {
|
|
166
|
+
success: false,
|
|
167
|
+
error: {
|
|
168
|
+
code: "COMMAND_SKIPPED",
|
|
169
|
+
message: "Command skipped due to previous error (stopOnError enabled)",
|
|
170
|
+
},
|
|
171
|
+
},
|
|
172
|
+
durationMs: 0,
|
|
173
|
+
});
|
|
174
|
+
continue;
|
|
175
|
+
}
|
|
176
|
+
const cmdStartTime = performance.now();
|
|
177
|
+
const result = await executeCommand(cmd.command, cmd.input, {
|
|
178
|
+
...context,
|
|
179
|
+
traceId: context.traceId ?? `batch-${Date.now()}-${i}`,
|
|
180
|
+
});
|
|
181
|
+
const cmdDuration = performance.now() - cmdStartTime;
|
|
182
|
+
results.push({
|
|
183
|
+
id: cmd.id ?? `cmd-${i}`,
|
|
184
|
+
index: i,
|
|
185
|
+
command: cmd.command,
|
|
186
|
+
result,
|
|
187
|
+
durationMs: Math.round(cmdDuration * 100) / 100,
|
|
188
|
+
});
|
|
189
|
+
if (!result.success && options.stopOnError) {
|
|
190
|
+
stopped = true;
|
|
191
|
+
}
|
|
192
|
+
// Check timeout
|
|
193
|
+
if (options.timeout && performance.now() - startTime > options.timeout) {
|
|
194
|
+
for (let j = i + 1; j < request.commands.length; j++) {
|
|
195
|
+
const remainingCmd = request.commands[j];
|
|
196
|
+
results.push({
|
|
197
|
+
id: remainingCmd.id ?? `cmd-${j}`,
|
|
198
|
+
index: j,
|
|
199
|
+
command: remainingCmd.command,
|
|
200
|
+
result: {
|
|
201
|
+
success: false,
|
|
202
|
+
error: {
|
|
203
|
+
code: "BATCH_TIMEOUT",
|
|
204
|
+
message: `Batch timeout exceeded (${options.timeout}ms)`,
|
|
205
|
+
retryable: true,
|
|
206
|
+
},
|
|
207
|
+
},
|
|
208
|
+
durationMs: 0,
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
break;
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
const completedAt = new Date().toISOString();
|
|
215
|
+
const totalMs = performance.now() - startTime;
|
|
216
|
+
const timing = {
|
|
217
|
+
totalMs: Math.round(totalMs * 100) / 100,
|
|
218
|
+
averageMs: results.length > 0
|
|
219
|
+
? Math.round((totalMs / results.length) * 100) / 100
|
|
220
|
+
: 0,
|
|
221
|
+
startedAt,
|
|
222
|
+
completedAt,
|
|
223
|
+
};
|
|
224
|
+
return createBatchResult(results, timing, {
|
|
225
|
+
traceId: context.traceId ?? `batch-${Date.now()}`,
|
|
226
|
+
});
|
|
227
|
+
}
|
|
228
|
+
/**
|
|
229
|
+
* Execute a command as a stream, yielding chunks.
|
|
230
|
+
*/
|
|
231
|
+
async function* executeStream(commandName, input, context = {}) {
|
|
232
|
+
const startTime = performance.now();
|
|
233
|
+
let chunksEmitted = 0;
|
|
234
|
+
try {
|
|
235
|
+
const result = await executeCommand(commandName, input, context);
|
|
236
|
+
if (!result.success) {
|
|
237
|
+
yield createErrorChunk(result.error ?? {
|
|
238
|
+
code: "COMMAND_FAILED",
|
|
239
|
+
message: "Command execution failed",
|
|
240
|
+
}, chunksEmitted, result.error?.retryable ?? false);
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const data = result.data;
|
|
244
|
+
// If result is an array, emit each item as a chunk
|
|
245
|
+
if (Array.isArray(data)) {
|
|
246
|
+
for (let i = 0; i < data.length; i++) {
|
|
247
|
+
yield {
|
|
248
|
+
type: "data",
|
|
249
|
+
data: data[i],
|
|
250
|
+
index: i,
|
|
251
|
+
isLast: i === data.length - 1,
|
|
252
|
+
};
|
|
253
|
+
chunksEmitted++;
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
else {
|
|
257
|
+
yield {
|
|
258
|
+
type: "data",
|
|
259
|
+
data: data,
|
|
260
|
+
index: 0,
|
|
261
|
+
isLast: true,
|
|
262
|
+
};
|
|
263
|
+
chunksEmitted++;
|
|
264
|
+
}
|
|
265
|
+
// Emit completion
|
|
266
|
+
const totalDurationMs = performance.now() - startTime;
|
|
267
|
+
yield createCompleteChunk(chunksEmitted, totalDurationMs, {
|
|
268
|
+
confidence: result.confidence,
|
|
269
|
+
reasoning: result.reasoning,
|
|
270
|
+
metadata: result.metadata,
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
catch (error) {
|
|
274
|
+
yield createErrorChunk({
|
|
275
|
+
code: "STREAM_ERROR",
|
|
276
|
+
message: error instanceof Error ? error.message : String(error),
|
|
277
|
+
retryable: true,
|
|
278
|
+
}, chunksEmitted, true);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Get the tools list based on toolStrategy.
|
|
283
|
+
*/
|
|
284
|
+
function getToolsList() {
|
|
285
|
+
// Built-in afd-batch tool (always individual)
|
|
286
|
+
const batchTool = {
|
|
287
|
+
name: "afd-batch",
|
|
288
|
+
description: "Execute multiple commands in a single batch request with partial success semantics",
|
|
289
|
+
inputSchema: {
|
|
290
|
+
type: "object",
|
|
291
|
+
properties: {
|
|
292
|
+
commands: {
|
|
293
|
+
type: "array",
|
|
294
|
+
description: "Array of commands to execute",
|
|
295
|
+
items: {
|
|
296
|
+
type: "object",
|
|
297
|
+
properties: {
|
|
298
|
+
id: { type: "string", description: "Optional client-provided ID for correlating results" },
|
|
299
|
+
command: { type: "string", description: "The command name to execute" },
|
|
300
|
+
input: { type: "object", description: "Input parameters for the command" },
|
|
301
|
+
},
|
|
302
|
+
required: ["command"],
|
|
303
|
+
},
|
|
304
|
+
},
|
|
305
|
+
options: {
|
|
306
|
+
type: "object",
|
|
307
|
+
description: "Batch execution options",
|
|
308
|
+
properties: {
|
|
309
|
+
stopOnError: { type: "boolean", description: "Stop execution on first error" },
|
|
310
|
+
timeout: { type: "number", description: "Timeout in milliseconds for entire batch" },
|
|
311
|
+
},
|
|
312
|
+
},
|
|
313
|
+
},
|
|
314
|
+
required: ["commands"],
|
|
315
|
+
},
|
|
316
|
+
};
|
|
317
|
+
// Individual strategy: each command is its own tool
|
|
318
|
+
if (toolStrategy === "individual") {
|
|
319
|
+
return [
|
|
320
|
+
batchTool,
|
|
321
|
+
...commands.map((cmd) => {
|
|
322
|
+
const { type: _type, ...restSchema } = cmd.jsonSchema;
|
|
323
|
+
return {
|
|
324
|
+
name: cmd.name,
|
|
325
|
+
description: cmd.description,
|
|
326
|
+
inputSchema: {
|
|
327
|
+
type: "object",
|
|
328
|
+
...restSchema,
|
|
329
|
+
},
|
|
330
|
+
};
|
|
331
|
+
}),
|
|
332
|
+
];
|
|
333
|
+
}
|
|
334
|
+
// Grouped strategy: commands grouped by category/entity
|
|
335
|
+
const defaultGroupFn = (cmd) => {
|
|
336
|
+
return cmd.category || cmd.name.split("-")[0] || "general";
|
|
337
|
+
};
|
|
338
|
+
const getGroup = groupByFn || defaultGroupFn;
|
|
339
|
+
// Group commands by their group key
|
|
340
|
+
const groups = {};
|
|
341
|
+
for (const cmd of commands) {
|
|
342
|
+
const group = getGroup(cmd) || "general";
|
|
343
|
+
if (!groups[group]) {
|
|
344
|
+
groups[group] = [];
|
|
345
|
+
}
|
|
346
|
+
groups[group].push(cmd);
|
|
347
|
+
}
|
|
348
|
+
// Create a consolidated tool for each group
|
|
349
|
+
const groupedTools = Object.entries(groups).map(([groupName, groupCmds]) => {
|
|
350
|
+
// Build action enum from command names
|
|
351
|
+
const actions = groupCmds.map(cmd => {
|
|
352
|
+
// 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("-") : cmd.name;
|
|
355
|
+
});
|
|
356
|
+
return {
|
|
357
|
+
name: groupName,
|
|
358
|
+
description: `${groupName} operations: ${actions.join(", ")}`,
|
|
359
|
+
inputSchema: {
|
|
360
|
+
type: "object",
|
|
361
|
+
properties: {
|
|
362
|
+
action: {
|
|
363
|
+
type: "string",
|
|
364
|
+
enum: actions,
|
|
365
|
+
description: `Action to perform: ${actions.join(" | ")}`,
|
|
366
|
+
},
|
|
367
|
+
// Note: Full discriminated union would require merging all command schemas
|
|
368
|
+
// For now, we use a generic "params" object
|
|
369
|
+
params: {
|
|
370
|
+
type: "object",
|
|
371
|
+
description: "Parameters for the action (varies by action)",
|
|
372
|
+
},
|
|
373
|
+
},
|
|
374
|
+
required: ["action"],
|
|
375
|
+
},
|
|
376
|
+
};
|
|
377
|
+
});
|
|
378
|
+
return [batchTool, ...groupedTools];
|
|
379
|
+
}
|
|
380
|
+
/**
|
|
381
|
+
* Handle MCP JSON-RPC request.
|
|
382
|
+
*/
|
|
383
|
+
function handleMcpRequest(request) {
|
|
384
|
+
const { id, method } = request;
|
|
385
|
+
switch (method) {
|
|
386
|
+
case "initialize":
|
|
387
|
+
return {
|
|
388
|
+
jsonrpc: "2.0",
|
|
389
|
+
id,
|
|
390
|
+
result: {
|
|
391
|
+
protocolVersion: "2024-11-05",
|
|
392
|
+
capabilities: {
|
|
393
|
+
tools: {},
|
|
394
|
+
},
|
|
395
|
+
serverInfo: {
|
|
396
|
+
name,
|
|
397
|
+
version,
|
|
398
|
+
},
|
|
399
|
+
},
|
|
400
|
+
};
|
|
401
|
+
case "tools/list":
|
|
402
|
+
return {
|
|
403
|
+
jsonrpc: "2.0",
|
|
404
|
+
id,
|
|
405
|
+
result: {
|
|
406
|
+
tools: getToolsList(),
|
|
407
|
+
},
|
|
408
|
+
};
|
|
409
|
+
case "notifications/initialized":
|
|
410
|
+
// Client notification, no response needed for notifications
|
|
411
|
+
// but we return a success for acknowledgment
|
|
412
|
+
return {
|
|
413
|
+
jsonrpc: "2.0",
|
|
414
|
+
id,
|
|
415
|
+
result: {},
|
|
416
|
+
};
|
|
417
|
+
default:
|
|
418
|
+
return {
|
|
419
|
+
jsonrpc: "2.0",
|
|
420
|
+
id,
|
|
421
|
+
error: {
|
|
422
|
+
code: -32601,
|
|
423
|
+
message: `Method not found: ${method}`,
|
|
424
|
+
},
|
|
425
|
+
};
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Handle async MCP request (tools/call).
|
|
430
|
+
*/
|
|
431
|
+
async function handleAsyncMcpRequest(request) {
|
|
432
|
+
const { id, method, params } = request;
|
|
433
|
+
if (method === "tools/call") {
|
|
434
|
+
const { name: toolName, arguments: args } = params;
|
|
435
|
+
// Handle built-in afd-batch tool
|
|
436
|
+
if (toolName === "afd-batch") {
|
|
437
|
+
const batchRequest = args;
|
|
438
|
+
const result = await executeBatch(batchRequest, {
|
|
439
|
+
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
440
|
+
});
|
|
441
|
+
return {
|
|
442
|
+
jsonrpc: "2.0",
|
|
443
|
+
id,
|
|
444
|
+
result: {
|
|
445
|
+
content: [
|
|
446
|
+
{
|
|
447
|
+
type: "text",
|
|
448
|
+
text: JSON.stringify(result, null, 2),
|
|
449
|
+
},
|
|
450
|
+
],
|
|
451
|
+
isError: !result.success,
|
|
452
|
+
},
|
|
453
|
+
};
|
|
454
|
+
}
|
|
455
|
+
// Handle grouped tool calls (when toolStrategy === "grouped")
|
|
456
|
+
if (toolStrategy === "grouped") {
|
|
457
|
+
const typedArgs = args;
|
|
458
|
+
const action = typedArgs?.action;
|
|
459
|
+
const commandParams = typedArgs?.params ?? {};
|
|
460
|
+
if (action && typeof action === "string") {
|
|
461
|
+
// Construct actual command name: groupName-action
|
|
462
|
+
const actualCommandName = `${toolName}-${action}`;
|
|
463
|
+
const result = await executeCommand(actualCommandName, commandParams, {
|
|
464
|
+
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
465
|
+
});
|
|
466
|
+
return {
|
|
467
|
+
jsonrpc: "2.0",
|
|
468
|
+
id,
|
|
469
|
+
result: {
|
|
470
|
+
content: [
|
|
471
|
+
{
|
|
472
|
+
type: "text",
|
|
473
|
+
text: JSON.stringify(result, null, 2),
|
|
474
|
+
},
|
|
475
|
+
],
|
|
476
|
+
isError: !result.success,
|
|
477
|
+
},
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
}
|
|
481
|
+
// Handle user-defined commands (individual mode)
|
|
482
|
+
const result = await executeCommand(toolName, args ?? {}, {
|
|
483
|
+
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
484
|
+
});
|
|
485
|
+
return {
|
|
486
|
+
jsonrpc: "2.0",
|
|
487
|
+
id,
|
|
488
|
+
result: {
|
|
489
|
+
content: [
|
|
490
|
+
{
|
|
491
|
+
type: "text",
|
|
492
|
+
text: JSON.stringify(result, null, 2),
|
|
493
|
+
},
|
|
494
|
+
],
|
|
495
|
+
isError: !result.success,
|
|
496
|
+
},
|
|
497
|
+
};
|
|
498
|
+
}
|
|
499
|
+
// Fall back to sync handler for other methods
|
|
500
|
+
return handleMcpRequest(request);
|
|
501
|
+
}
|
|
502
|
+
/**
|
|
503
|
+
* Send SSE event to a client.
|
|
504
|
+
*/
|
|
505
|
+
function sendSseEvent(client, event, data) {
|
|
506
|
+
const message = `event: ${event}\ndata: ${JSON.stringify(data)}\n\n`;
|
|
507
|
+
client.response.write(message);
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Create HTTP request handler.
|
|
511
|
+
*/
|
|
512
|
+
function createRequestHandler() {
|
|
513
|
+
return async (req, res) => {
|
|
514
|
+
// CORS headers - restrictive in production, permissive in dev mode
|
|
515
|
+
if (cors) {
|
|
516
|
+
// In dev mode, allow all origins; in production, allow same-origin or configured origins
|
|
517
|
+
res.setHeader("Access-Control-Allow-Origin", devMode ? "*" : req.headers.origin ?? "");
|
|
518
|
+
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
|
|
519
|
+
res.setHeader("Access-Control-Allow-Headers", "Content-Type");
|
|
520
|
+
}
|
|
521
|
+
// Handle preflight
|
|
522
|
+
if (req.method === "OPTIONS") {
|
|
523
|
+
res.writeHead(204);
|
|
524
|
+
res.end();
|
|
525
|
+
return;
|
|
526
|
+
}
|
|
527
|
+
const url = new URL(req.url ?? "/", `http://${req.headers.host}`);
|
|
528
|
+
// SSE endpoint
|
|
529
|
+
if (url.pathname === "/sse" && req.method === "GET") {
|
|
530
|
+
const clientId = `client-${++clientIdCounter}`;
|
|
531
|
+
res.writeHead(200, {
|
|
532
|
+
"Content-Type": "text/event-stream",
|
|
533
|
+
"Cache-Control": "no-cache",
|
|
534
|
+
Connection: "keep-alive",
|
|
535
|
+
});
|
|
536
|
+
const client = { id: clientId, response: res };
|
|
537
|
+
sseClients.set(clientId, client);
|
|
538
|
+
// Send endpoint info
|
|
539
|
+
sendSseEvent(client, "endpoint", {
|
|
540
|
+
url: `http://${host}:${port}/message`,
|
|
541
|
+
});
|
|
542
|
+
// Handle client disconnect
|
|
543
|
+
req.on("close", () => {
|
|
544
|
+
sseClients.delete(clientId);
|
|
545
|
+
});
|
|
546
|
+
return;
|
|
547
|
+
}
|
|
548
|
+
// Message endpoint
|
|
549
|
+
if (url.pathname === "/message" && req.method === "POST") {
|
|
550
|
+
let body = "";
|
|
551
|
+
for await (const chunk of req) {
|
|
552
|
+
body += chunk;
|
|
553
|
+
}
|
|
554
|
+
try {
|
|
555
|
+
const request = JSON.parse(body);
|
|
556
|
+
const response = await handleAsyncMcpRequest(request);
|
|
557
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
558
|
+
res.end(JSON.stringify(response));
|
|
559
|
+
}
|
|
560
|
+
catch (error) {
|
|
561
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
562
|
+
res.end(JSON.stringify({
|
|
563
|
+
jsonrpc: "2.0",
|
|
564
|
+
id: null,
|
|
565
|
+
error: {
|
|
566
|
+
code: -32700,
|
|
567
|
+
message: "Parse error",
|
|
568
|
+
},
|
|
569
|
+
}));
|
|
570
|
+
}
|
|
571
|
+
return;
|
|
572
|
+
}
|
|
573
|
+
// Health check
|
|
574
|
+
if (url.pathname === "/health" && req.method === "GET") {
|
|
575
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
576
|
+
res.end(JSON.stringify({ status: "ok", name, version }));
|
|
577
|
+
return;
|
|
578
|
+
}
|
|
579
|
+
// Batch endpoint
|
|
580
|
+
if (url.pathname === "/batch" && req.method === "POST") {
|
|
581
|
+
let body = "";
|
|
582
|
+
for await (const chunk of req) {
|
|
583
|
+
body += chunk;
|
|
584
|
+
}
|
|
585
|
+
try {
|
|
586
|
+
const batchRequest = JSON.parse(body);
|
|
587
|
+
if (!isBatchRequest(batchRequest)) {
|
|
588
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
589
|
+
res.end(JSON.stringify({
|
|
590
|
+
success: false,
|
|
591
|
+
error: {
|
|
592
|
+
code: "INVALID_BATCH_REQUEST",
|
|
593
|
+
message: "Invalid batch request format",
|
|
594
|
+
suggestion: "Provide { commands: [...] } with command objects",
|
|
595
|
+
},
|
|
596
|
+
}));
|
|
597
|
+
return;
|
|
598
|
+
}
|
|
599
|
+
const result = await executeBatch(batchRequest, {
|
|
600
|
+
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
601
|
+
});
|
|
602
|
+
res.writeHead(200, { "Content-Type": "application/json" });
|
|
603
|
+
res.end(JSON.stringify(result));
|
|
604
|
+
}
|
|
605
|
+
catch (error) {
|
|
606
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
607
|
+
res.end(JSON.stringify({
|
|
608
|
+
success: false,
|
|
609
|
+
error: {
|
|
610
|
+
code: "PARSE_ERROR",
|
|
611
|
+
message: "Failed to parse batch request",
|
|
612
|
+
suggestion: "Ensure request body is valid JSON",
|
|
613
|
+
},
|
|
614
|
+
}));
|
|
615
|
+
}
|
|
616
|
+
return;
|
|
617
|
+
}
|
|
618
|
+
// Stream endpoint - SSE for streaming command results
|
|
619
|
+
if (url.pathname.startsWith("/stream/") && req.method === "GET") {
|
|
620
|
+
const commandName = url.pathname.slice("/stream/".length);
|
|
621
|
+
const inputParam = url.searchParams.get("input");
|
|
622
|
+
let input = {};
|
|
623
|
+
if (inputParam) {
|
|
624
|
+
try {
|
|
625
|
+
input = JSON.parse(inputParam);
|
|
626
|
+
}
|
|
627
|
+
catch {
|
|
628
|
+
res.writeHead(400, { "Content-Type": "application/json" });
|
|
629
|
+
res.end(JSON.stringify({
|
|
630
|
+
success: false,
|
|
631
|
+
error: {
|
|
632
|
+
code: "INVALID_INPUT",
|
|
633
|
+
message: "Failed to parse input parameter",
|
|
634
|
+
suggestion: "Ensure input is valid JSON",
|
|
635
|
+
},
|
|
636
|
+
}));
|
|
637
|
+
return;
|
|
638
|
+
}
|
|
639
|
+
}
|
|
640
|
+
// Set up SSE response
|
|
641
|
+
res.writeHead(200, {
|
|
642
|
+
"Content-Type": "text/event-stream",
|
|
643
|
+
"Cache-Control": "no-cache",
|
|
644
|
+
Connection: "keep-alive",
|
|
645
|
+
});
|
|
646
|
+
const context = {
|
|
647
|
+
traceId: `stream-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
648
|
+
};
|
|
649
|
+
// Handle client disconnect
|
|
650
|
+
let aborted = false;
|
|
651
|
+
req.on("close", () => {
|
|
652
|
+
aborted = true;
|
|
653
|
+
});
|
|
654
|
+
// Stream the command execution
|
|
655
|
+
try {
|
|
656
|
+
for await (const chunk of executeStream(commandName, input, context)) {
|
|
657
|
+
if (aborted)
|
|
658
|
+
break;
|
|
659
|
+
res.write(`event: chunk\ndata: ${JSON.stringify(chunk)}\n\n`);
|
|
660
|
+
}
|
|
661
|
+
}
|
|
662
|
+
catch (error) {
|
|
663
|
+
const errorChunk = createErrorChunk({
|
|
664
|
+
code: "STREAM_ERROR",
|
|
665
|
+
message: error instanceof Error ? error.message : String(error),
|
|
666
|
+
retryable: true,
|
|
667
|
+
}, 0, true);
|
|
668
|
+
res.write(`event: chunk\ndata: ${JSON.stringify(errorChunk)}\n\n`);
|
|
669
|
+
}
|
|
670
|
+
res.end();
|
|
671
|
+
return;
|
|
672
|
+
}
|
|
673
|
+
// Not found
|
|
674
|
+
res.writeHead(404, { "Content-Type": "application/json" });
|
|
675
|
+
res.end(JSON.stringify({ error: "Not found" }));
|
|
676
|
+
};
|
|
677
|
+
}
|
|
678
|
+
// Track MCP SDK server for stdio transport cleanup
|
|
679
|
+
let mcpSdkServer = null;
|
|
680
|
+
return {
|
|
681
|
+
async start() {
|
|
682
|
+
if (isRunning) {
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
// Start stdio transport if enabled using official MCP SDK
|
|
686
|
+
if (useStdio) {
|
|
687
|
+
mcpSdkServer = new McpSdkServer({ name, version }, { capabilities: { tools: {} } });
|
|
688
|
+
// Register tools/list handler - use shared getToolsList() for consistency
|
|
689
|
+
mcpSdkServer.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
690
|
+
tools: getToolsList(),
|
|
691
|
+
}));
|
|
692
|
+
// Register tools/call handler
|
|
693
|
+
mcpSdkServer.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
694
|
+
const toolName = request.params.name;
|
|
695
|
+
const args = request.params.arguments ?? {};
|
|
696
|
+
// Handle built-in afd.batch tool
|
|
697
|
+
if (toolName === "afd-batch") {
|
|
698
|
+
// Validate that args looks like a BatchRequest before processing
|
|
699
|
+
if (!isBatchRequest(args)) {
|
|
700
|
+
return {
|
|
701
|
+
content: [{ type: "text", text: JSON.stringify({
|
|
702
|
+
success: false,
|
|
703
|
+
error: {
|
|
704
|
+
code: "INVALID_BATCH_REQUEST",
|
|
705
|
+
message: "Invalid batch request format",
|
|
706
|
+
suggestion: "Provide { commands: [...] } with command objects",
|
|
707
|
+
},
|
|
708
|
+
}, null, 2) }],
|
|
709
|
+
isError: true,
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
const result = await executeBatch(args, {
|
|
713
|
+
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
714
|
+
});
|
|
715
|
+
return {
|
|
716
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
717
|
+
isError: !result.success,
|
|
718
|
+
};
|
|
719
|
+
}
|
|
720
|
+
// Handle grouped tool calls (when toolStrategy === "grouped")
|
|
721
|
+
// Grouped tools have format: { action: "create", params: {...} }
|
|
722
|
+
if (toolStrategy === "grouped") {
|
|
723
|
+
const action = args.action;
|
|
724
|
+
const params = args.params ?? {};
|
|
725
|
+
// Debug logging when enabled
|
|
726
|
+
if (devMode) {
|
|
727
|
+
console.error(`[MCP Debug] Grouped tool call: toolName=${toolName}, action=${action}, args=${JSON.stringify(args)}`);
|
|
728
|
+
}
|
|
729
|
+
// Check if this is a grouped tool call (has action property)
|
|
730
|
+
if (action && typeof action === "string") {
|
|
731
|
+
// Construct the actual command name: groupName-action
|
|
732
|
+
// e.g., "todo" + "create" = "todo-create"
|
|
733
|
+
const actualCommandName = `${toolName}-${action}`;
|
|
734
|
+
// Execute the actual command
|
|
735
|
+
const result = await executeCommand(actualCommandName, params, {
|
|
736
|
+
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
737
|
+
});
|
|
738
|
+
return {
|
|
739
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
740
|
+
isError: !result.success,
|
|
741
|
+
};
|
|
742
|
+
}
|
|
743
|
+
// In grouped mode, if tool is a known group but action is missing/invalid,
|
|
744
|
+
// 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("-")[0] || "general";
|
|
747
|
+
return (groupByFn || defaultGroupFn)(cmd);
|
|
748
|
+
}));
|
|
749
|
+
if (groupNames.has(toolName)) {
|
|
750
|
+
const groupCommands = commands.filter(cmd => {
|
|
751
|
+
const defaultGroupFn = (c) => c.category || c.name.split("-")[0] || "general";
|
|
752
|
+
return (groupByFn || defaultGroupFn)(cmd) === toolName;
|
|
753
|
+
});
|
|
754
|
+
const availableActions = groupCommands.map(cmd => {
|
|
755
|
+
const parts = cmd.name.split("-");
|
|
756
|
+
return parts.length > 1 ? parts.slice(1).join("-") : cmd.name;
|
|
757
|
+
});
|
|
758
|
+
return {
|
|
759
|
+
content: [{ type: "text", text: JSON.stringify({
|
|
760
|
+
success: false,
|
|
761
|
+
error: {
|
|
762
|
+
code: "INVALID_GROUPED_CALL",
|
|
763
|
+
message: `Grouped tool '${toolName}' requires an 'action' parameter`,
|
|
764
|
+
suggestion: `Provide { action: "<action>", params: {...} }. Available actions: ${availableActions.join(", ")}`,
|
|
765
|
+
},
|
|
766
|
+
_debug: devMode ? { receivedArgs: args } : undefined,
|
|
767
|
+
}, null, 2) }],
|
|
768
|
+
isError: true,
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
}
|
|
772
|
+
// Handle user-defined commands (individual mode or direct command calls)
|
|
773
|
+
const result = await executeCommand(toolName, args, {
|
|
774
|
+
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
775
|
+
});
|
|
776
|
+
return {
|
|
777
|
+
content: [{ type: "text", text: JSON.stringify(result, null, 2) }],
|
|
778
|
+
isError: !result.success,
|
|
779
|
+
};
|
|
780
|
+
});
|
|
781
|
+
// Connect to stdio transport
|
|
782
|
+
const transport = new StdioServerTransport();
|
|
783
|
+
await mcpSdkServer.connect(transport);
|
|
784
|
+
isRunning = true;
|
|
785
|
+
// For stdio-only mode, we're done
|
|
786
|
+
if (!useHttp) {
|
|
787
|
+
return;
|
|
788
|
+
}
|
|
789
|
+
}
|
|
790
|
+
// Start HTTP transport if enabled
|
|
791
|
+
if (useHttp) {
|
|
792
|
+
httpServer = createServer(createRequestHandler());
|
|
793
|
+
await new Promise((resolve, reject) => {
|
|
794
|
+
httpServer.on("error", reject);
|
|
795
|
+
httpServer.listen(port, host, () => {
|
|
796
|
+
isRunning = true;
|
|
797
|
+
resolve();
|
|
798
|
+
});
|
|
799
|
+
});
|
|
800
|
+
}
|
|
801
|
+
},
|
|
802
|
+
async stop() {
|
|
803
|
+
if (!isRunning) {
|
|
804
|
+
return;
|
|
805
|
+
}
|
|
806
|
+
// Close MCP SDK server if it exists
|
|
807
|
+
if (mcpSdkServer) {
|
|
808
|
+
await mcpSdkServer.close();
|
|
809
|
+
mcpSdkServer = null;
|
|
810
|
+
}
|
|
811
|
+
// Close HTTP server if it exists
|
|
812
|
+
if (httpServer) {
|
|
813
|
+
// Close all SSE clients
|
|
814
|
+
for (const client of sseClients.values()) {
|
|
815
|
+
client.response.end();
|
|
816
|
+
}
|
|
817
|
+
sseClients.clear();
|
|
818
|
+
await new Promise((resolve, reject) => {
|
|
819
|
+
httpServer.close((err) => {
|
|
820
|
+
if (err)
|
|
821
|
+
reject(err);
|
|
822
|
+
else
|
|
823
|
+
resolve();
|
|
824
|
+
});
|
|
825
|
+
});
|
|
826
|
+
httpServer = null;
|
|
827
|
+
}
|
|
828
|
+
isRunning = false;
|
|
829
|
+
},
|
|
830
|
+
getUrl() {
|
|
831
|
+
return useHttp ? `http://${host}:${port}` : "stdio://";
|
|
832
|
+
},
|
|
833
|
+
getCommands() {
|
|
834
|
+
return commands;
|
|
835
|
+
},
|
|
836
|
+
/**
|
|
837
|
+
* Get the resolved transport mode.
|
|
838
|
+
* Useful for debugging and logging.
|
|
839
|
+
*/
|
|
840
|
+
getTransport() {
|
|
841
|
+
return resolvedTransport;
|
|
842
|
+
},
|
|
843
|
+
execute: executeCommand,
|
|
844
|
+
};
|
|
845
|
+
}
|
|
846
|
+
//# sourceMappingURL=server.js.map
|