@lushly-dev/afd-server 1.0.0 → 2.0.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 +297 -14
- package/dist/bootstrap/afd-context.d.ts +11 -2
- package/dist/bootstrap/afd-context.d.ts.map +1 -1
- package/dist/bootstrap/afd-context.js +56 -11
- package/dist/bootstrap/afd-context.js.map +1 -1
- package/dist/bootstrap/afd-docs.d.ts +6 -3
- package/dist/bootstrap/afd-docs.d.ts.map +1 -1
- package/dist/bootstrap/afd-docs.js +14 -9
- package/dist/bootstrap/afd-docs.js.map +1 -1
- package/dist/bootstrap/afd-help.d.ts +6 -3
- package/dist/bootstrap/afd-help.d.ts.map +1 -1
- package/dist/bootstrap/afd-help.js +10 -8
- package/dist/bootstrap/afd-help.js.map +1 -1
- package/dist/bootstrap/afd-schema.d.ts +8 -4
- package/dist/bootstrap/afd-schema.d.ts.map +1 -1
- package/dist/bootstrap/afd-schema.js +55 -42
- package/dist/bootstrap/afd-schema.js.map +1 -1
- package/dist/bootstrap/described-command.d.ts +32 -0
- package/dist/bootstrap/described-command.d.ts.map +1 -0
- package/dist/bootstrap/described-command.js +12 -0
- package/dist/bootstrap/described-command.js.map +1 -0
- package/dist/bootstrap/index.d.ts +1 -0
- package/dist/bootstrap/index.d.ts.map +1 -1
- package/dist/bootstrap/index.js.map +1 -1
- package/dist/bootstrap/json-schema-to-ts.d.ts +27 -0
- package/dist/bootstrap/json-schema-to-ts.d.ts.map +1 -0
- package/dist/bootstrap/json-schema-to-ts.js +154 -0
- package/dist/bootstrap/json-schema-to-ts.js.map +1 -0
- package/dist/bootstrap/registry.d.ts +17 -6
- package/dist/bootstrap/registry.d.ts.map +1 -1
- package/dist/bootstrap/registry.js +32 -5
- package/dist/bootstrap/registry.js.map +1 -1
- package/dist/command-names.d.ts +19 -0
- package/dist/command-names.d.ts.map +1 -0
- package/dist/command-names.js +33 -0
- package/dist/command-names.js.map +1 -0
- package/dist/command-routing.d.ts +47 -0
- package/dist/command-routing.d.ts.map +1 -0
- package/dist/command-routing.js +75 -0
- package/dist/command-routing.js.map +1 -0
- package/dist/context-scope.d.ts +26 -0
- package/dist/context-scope.d.ts.map +1 -0
- package/dist/context-scope.js +31 -0
- package/dist/context-scope.js.map +1 -0
- package/dist/define.d.ts +42 -0
- package/dist/define.d.ts.map +1 -0
- package/dist/define.js +41 -0
- package/dist/define.js.map +1 -0
- package/dist/direct-registry.d.ts +103 -0
- package/dist/direct-registry.d.ts.map +1 -0
- package/dist/direct-registry.js +102 -0
- package/dist/direct-registry.js.map +1 -0
- package/dist/execution.d.ts +9 -0
- package/dist/execution.d.ts.map +1 -1
- package/dist/execution.js +105 -321
- package/dist/execution.js.map +1 -1
- package/dist/http-handler.d.ts +24 -17
- package/dist/http-handler.d.ts.map +1 -1
- package/dist/http-handler.js +282 -253
- package/dist/http-handler.js.map +1 -1
- package/dist/http-security.d.ts +23 -0
- package/dist/http-security.d.ts.map +1 -0
- package/dist/http-security.js +101 -0
- package/dist/http-security.js.map +1 -0
- package/dist/http-sessions.d.ts +33 -0
- package/dist/http-sessions.d.ts.map +1 -0
- package/dist/http-sessions.js +65 -0
- package/dist/http-sessions.js.map +1 -0
- package/dist/http-sse.d.ts +30 -0
- package/dist/http-sse.d.ts.map +1 -0
- package/dist/http-sse.js +70 -0
- package/dist/http-sse.js.map +1 -0
- package/dist/index.d.ts +4 -3
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/json-rpc.d.ts +56 -0
- package/dist/json-rpc.d.ts.map +1 -0
- package/dist/json-rpc.js +73 -0
- package/dist/json-rpc.js.map +1 -0
- package/dist/lazy-tools.d.ts +2 -12
- package/dist/lazy-tools.d.ts.map +1 -1
- package/dist/lazy-tools.js +9 -14
- package/dist/lazy-tools.js.map +1 -1
- package/dist/meta-tools.d.ts +122 -0
- package/dist/meta-tools.d.ts.map +1 -0
- package/dist/meta-tools.js +156 -0
- package/dist/meta-tools.js.map +1 -0
- package/dist/middleware.d.ts +34 -7
- package/dist/middleware.d.ts.map +1 -1
- package/dist/middleware.js +82 -40
- package/dist/middleware.js.map +1 -1
- package/dist/schema.d.ts +27 -6
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +17 -12
- package/dist/schema.js.map +1 -1
- package/dist/server-types.d.ts +90 -14
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server-types.js.map +1 -1
- package/dist/server.d.ts +1 -1
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +103 -21
- package/dist/server.js.map +1 -1
- package/dist/tool-router.d.ts +6 -5
- package/dist/tool-router.d.ts.map +1 -1
- package/dist/tool-router.js +104 -120
- package/dist/tool-router.js.map +1 -1
- package/dist/tools.d.ts +10 -420
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +99 -208
- package/dist/tools.js.map +1 -1
- package/package.json +13 -8
package/dist/server.js
CHANGED
|
@@ -5,12 +5,20 @@
|
|
|
5
5
|
* execution, tool routing, and transport layers into a single MCP server.
|
|
6
6
|
*/
|
|
7
7
|
import { createServer } from 'node:http';
|
|
8
|
+
import { isMcpExposed } from '@lushly-dev/afd-core';
|
|
8
9
|
import { Server as McpSdkServer } from '@modelcontextprotocol/sdk/server/index.js';
|
|
9
10
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
10
11
|
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js';
|
|
11
|
-
import {
|
|
12
|
+
import { z } from 'zod';
|
|
13
|
+
import { createAfdContextEnterCommand, createAfdContextExitCommand, createAfdContextListCommand, createContextState, } from './bootstrap/afd-context.js';
|
|
14
|
+
import { getBootstrapCommands } from './bootstrap/registry.js';
|
|
15
|
+
import { assertValidCommandNames } from './command-names.js';
|
|
16
|
+
import { filterByContext } from './command-routing.js';
|
|
17
|
+
import { resolveContextState } from './context-scope.js';
|
|
12
18
|
import { createExecutionEngine } from './execution.js';
|
|
13
19
|
import { createHttpHandler } from './http-handler.js';
|
|
20
|
+
import { createSessionStore } from './http-sessions.js';
|
|
21
|
+
import { defineCommand } from './schema.js';
|
|
14
22
|
import { isStdinPiped } from './server-types.js';
|
|
15
23
|
import { createToolRouter } from './tool-router.js';
|
|
16
24
|
import { getToolsList } from './tools.js';
|
|
@@ -20,10 +28,53 @@ export { isStdinPiped } from './server-types.js';
|
|
|
20
28
|
// SERVER FACTORY
|
|
21
29
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
22
30
|
function createSharedHttpRuntime(options) {
|
|
23
|
-
const { name, version, commands, port = 3100, host = 'localhost', devMode = false, cors = devMode, middleware = [], onCommand, onError, toolStrategy = 'grouped', groupByFn, contexts, } = options;
|
|
31
|
+
const { name, version, commands, port = 3100, host = 'localhost', devMode = false, cors = devMode, middleware = [], onCommand, onError, toolStrategy = 'grouped', groupByFn, contexts, bootstrap = false, } = options;
|
|
32
|
+
assertValidCommandNames(commands, { bootstrap, contexts: Boolean(contexts?.length) });
|
|
33
|
+
// stdio serves one client, so it uses this single state. HTTP callers each get a session
|
|
34
|
+
// state (or none), bound to their command context by the HTTP handler.
|
|
24
35
|
const contextState = contexts?.length ? createContextState() : undefined;
|
|
36
|
+
const sessions = contextState
|
|
37
|
+
? createSessionStore({
|
|
38
|
+
maxSessions: options.maxSessions,
|
|
39
|
+
idleTimeoutMs: options.sessionIdleTimeoutMs,
|
|
40
|
+
})
|
|
41
|
+
: undefined;
|
|
42
|
+
const registeredCommands = [...commands];
|
|
43
|
+
if (contextState && contexts) {
|
|
44
|
+
const getContexts = () => [...contexts];
|
|
45
|
+
const builtins = [
|
|
46
|
+
defineCommand({
|
|
47
|
+
...createAfdContextListCommand(getContexts, contextState),
|
|
48
|
+
input: z.object({}),
|
|
49
|
+
expose: { mcp: true },
|
|
50
|
+
}),
|
|
51
|
+
defineCommand({
|
|
52
|
+
...createAfdContextEnterCommand(getContexts, contextState),
|
|
53
|
+
input: z.object({ context: z.string().min(1) }),
|
|
54
|
+
expose: { mcp: true },
|
|
55
|
+
}),
|
|
56
|
+
defineCommand({
|
|
57
|
+
...createAfdContextExitCommand(contextState),
|
|
58
|
+
input: z.object({}),
|
|
59
|
+
expose: { mcp: true },
|
|
60
|
+
}),
|
|
61
|
+
];
|
|
62
|
+
for (const command of builtins) {
|
|
63
|
+
if (registeredCommands.some((existing) => existing.name === command.name)) {
|
|
64
|
+
throw new Error(`Reserved context command name: ${command.name}`);
|
|
65
|
+
}
|
|
66
|
+
registeredCommands.push(command);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
if (bootstrap) {
|
|
70
|
+
// afd-help/afd-docs/afd-schema describe what a remote agent can see and call:
|
|
71
|
+
// MCP-exposed commands in the active context (built-ins included).
|
|
72
|
+
// The caller's context state: the HTTP session's, or the single stdio state.
|
|
73
|
+
const describe = (context) => filterByContext(remoteCommands, resolveContextState(context, contextState)?.getActive());
|
|
74
|
+
registeredCommands.push(...getBootstrapCommands(describe));
|
|
75
|
+
}
|
|
25
76
|
const commandMap = new Map();
|
|
26
|
-
for (const cmd of
|
|
77
|
+
for (const cmd of registeredCommands) {
|
|
27
78
|
commandMap.set(cmd.name, cmd);
|
|
28
79
|
}
|
|
29
80
|
const engine = createExecutionEngine({
|
|
@@ -33,38 +84,57 @@ function createSharedHttpRuntime(options) {
|
|
|
33
84
|
onCommand,
|
|
34
85
|
onError,
|
|
35
86
|
});
|
|
36
|
-
const
|
|
87
|
+
const remoteCommands = registeredCommands.filter((command) => isMcpExposed(command));
|
|
88
|
+
const remoteEngine = createExecutionEngine({
|
|
89
|
+
commandMap: new Map(remoteCommands.map((command) => [command.name, command])),
|
|
90
|
+
middleware,
|
|
91
|
+
devMode,
|
|
92
|
+
onCommand,
|
|
93
|
+
onError,
|
|
94
|
+
contextState,
|
|
95
|
+
});
|
|
96
|
+
const exposedCommandNames = new Set(remoteCommands.map((c) => c.name));
|
|
97
|
+
const mutationNames = new Set(remoteCommands.filter((command) => command.mutation === true).map((command) => command.name));
|
|
37
98
|
const routeToolCall = createToolRouter({
|
|
38
|
-
executeCommand:
|
|
39
|
-
executeBatch:
|
|
40
|
-
executePipeline:
|
|
41
|
-
commands,
|
|
99
|
+
executeCommand: remoteEngine.executeCommand,
|
|
100
|
+
executeBatch: remoteEngine.executeBatch,
|
|
101
|
+
executePipeline: remoteEngine.executePipeline,
|
|
102
|
+
commands: remoteCommands,
|
|
42
103
|
toolStrategy,
|
|
43
104
|
groupByFn,
|
|
44
105
|
devMode,
|
|
45
|
-
allCommands:
|
|
106
|
+
allCommands: remoteCommands,
|
|
46
107
|
exposedCommandNames,
|
|
47
108
|
contextState,
|
|
48
109
|
});
|
|
49
|
-
const boundGetToolsList = () => getToolsList(
|
|
50
|
-
const { handler } = createHttpHandler({
|
|
110
|
+
const boundGetToolsList = (context = {}) => getToolsList(remoteCommands, toolStrategy, groupByFn, resolveContextState(context, contextState)?.getActive());
|
|
111
|
+
const { handler, dispose } = createHttpHandler({
|
|
51
112
|
name,
|
|
52
113
|
version,
|
|
53
114
|
host,
|
|
54
115
|
port,
|
|
55
116
|
cors,
|
|
56
117
|
devMode,
|
|
118
|
+
allowedHosts: options.allowedHosts,
|
|
119
|
+
allowedOrigins: options.allowedOrigins,
|
|
120
|
+
maxBodyBytes: options.maxBodyBytes,
|
|
121
|
+
maxSseConnections: options.maxSseConnections,
|
|
57
122
|
getToolsList: boundGetToolsList,
|
|
58
123
|
routeToolCall,
|
|
59
|
-
executeCommand:
|
|
60
|
-
executeBatch:
|
|
61
|
-
executeStream:
|
|
124
|
+
executeCommand: remoteEngine.executeCommand,
|
|
125
|
+
executeBatch: remoteEngine.executeBatch,
|
|
126
|
+
executeStream: remoteEngine.executeStream,
|
|
127
|
+
isMutation: (commandName) => mutationNames.has(commandName),
|
|
128
|
+
sessions,
|
|
129
|
+
createContext: options.createContext,
|
|
130
|
+
onError,
|
|
62
131
|
});
|
|
63
132
|
return {
|
|
64
133
|
engine,
|
|
65
134
|
routeToolCall,
|
|
66
135
|
getToolsList: boundGetToolsList,
|
|
67
136
|
handler,
|
|
137
|
+
dispose,
|
|
68
138
|
url: `http://${host}:${port}`,
|
|
69
139
|
};
|
|
70
140
|
}
|
|
@@ -76,7 +146,8 @@ function createSharedHttpRuntime(options) {
|
|
|
76
146
|
* any Node HTTP host that accepts `(req, res) => Promise<void>`.
|
|
77
147
|
*/
|
|
78
148
|
export function createMcpHandler(options) {
|
|
79
|
-
|
|
149
|
+
const runtime = createSharedHttpRuntime(options);
|
|
150
|
+
return Object.assign(runtime.handler, { dispose: runtime.dispose });
|
|
80
151
|
}
|
|
81
152
|
/**
|
|
82
153
|
* Create an MCP server from Zod-defined commands.
|
|
@@ -96,12 +167,14 @@ export function createMcpHandler(options) {
|
|
|
96
167
|
* ```
|
|
97
168
|
*/
|
|
98
169
|
export function createMcpServer(options) {
|
|
99
|
-
const { name, version, commands, port = 3100, host = 'localhost', devMode = false, cors = devMode, transport = 'auto',
|
|
170
|
+
const { name, version, commands, port = 3100, host = 'localhost', devMode = false, cors = devMode, transport = 'auto', middleware = [], onCommand, onError, toolStrategy = 'grouped', groupByFn, contexts, } = options;
|
|
100
171
|
// ── Transport resolution ────────────────────────────────────────────────
|
|
172
|
+
// Removed in 2.0. Fail loudly: silently ignoring it would switch `stdio: false` servers to
|
|
173
|
+
// auto-detection, which picks stdio whenever stdin is piped.
|
|
174
|
+
if ('stdio' in options) {
|
|
175
|
+
throw new Error('createMcpServer: the stdio option was removed in 2.0. Use transport: "stdio", "http" or "auto" instead.');
|
|
176
|
+
}
|
|
101
177
|
function resolveTransport() {
|
|
102
|
-
if (stdio !== undefined) {
|
|
103
|
-
return stdio ? 'stdio' : 'http';
|
|
104
|
-
}
|
|
105
178
|
if (transport === 'auto') {
|
|
106
179
|
return isStdinPiped() ? 'stdio' : 'http';
|
|
107
180
|
}
|
|
@@ -110,8 +183,10 @@ export function createMcpServer(options) {
|
|
|
110
183
|
const resolvedTransport = resolveTransport();
|
|
111
184
|
const useStdio = resolvedTransport === 'stdio';
|
|
112
185
|
const useHttp = resolvedTransport === 'http';
|
|
186
|
+
const autoDetected = transport === 'auto';
|
|
113
187
|
// ── Shared execution/runtime wiring ─────────────────────────────────────
|
|
114
188
|
const sharedRuntime = createSharedHttpRuntime({
|
|
189
|
+
...options,
|
|
115
190
|
name,
|
|
116
191
|
version,
|
|
117
192
|
commands,
|
|
@@ -141,15 +216,19 @@ export function createMcpServer(options) {
|
|
|
141
216
|
mcpSdkServer.setRequestHandler(ListToolsRequestSchema, async () => ({
|
|
142
217
|
tools: sharedRuntime.getToolsList(),
|
|
143
218
|
}));
|
|
144
|
-
mcpSdkServer.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
219
|
+
mcpSdkServer.setRequestHandler(CallToolRequestSchema, async (request, extra) => {
|
|
145
220
|
// Spread into anonymous object for MCP SDK index signature compatibility
|
|
146
221
|
return {
|
|
147
|
-
...(await sharedRuntime.routeToolCall(request.params.name, request.params.arguments ?? {})),
|
|
222
|
+
...(await sharedRuntime.routeToolCall(request.params.name, request.params.arguments ?? {}, { signal: extra.signal, interface: 'mcp' })),
|
|
148
223
|
};
|
|
149
224
|
});
|
|
150
225
|
const stdioTransport = new StdioServerTransport();
|
|
151
226
|
await mcpSdkServer.connect(stdioTransport);
|
|
152
227
|
isRunning = true;
|
|
228
|
+
// stdout carries MCP frames, so the notice goes to stderr.
|
|
229
|
+
console.error(autoDetected
|
|
230
|
+
? `[${name}] MCP transport: stdio (auto-detected because stdin is not a TTY; set transport: 'http' to serve HTTP)`
|
|
231
|
+
: `[${name}] MCP transport: stdio`);
|
|
153
232
|
if (!useHttp)
|
|
154
233
|
return;
|
|
155
234
|
}
|
|
@@ -163,6 +242,7 @@ export function createMcpServer(options) {
|
|
|
163
242
|
resolve();
|
|
164
243
|
});
|
|
165
244
|
});
|
|
245
|
+
console.error(`[${name}] MCP transport: http at ${sharedRuntime.url}${autoDetected ? ' (auto-detected because stdin is a TTY)' : ''}`);
|
|
166
246
|
}
|
|
167
247
|
},
|
|
168
248
|
async stop() {
|
|
@@ -173,6 +253,8 @@ export function createMcpServer(options) {
|
|
|
173
253
|
mcpSdkServer = null;
|
|
174
254
|
}
|
|
175
255
|
if (httpServer) {
|
|
256
|
+
sharedRuntime.dispose();
|
|
257
|
+
httpServer.closeAllConnections();
|
|
176
258
|
await new Promise((resolve, reject) => {
|
|
177
259
|
httpServer?.close((err) => {
|
|
178
260
|
if (err)
|
package/dist/server.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAA6B,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"server.js","sourceRoot":"","sources":["../src/server.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,EAAE,YAAY,EAA6B,MAAM,WAAW,CAAC;AAEpE,OAAO,EAAE,YAAY,EAAE,MAAM,sBAAsB,CAAC;AACpD,OAAO,EAAE,MAAM,IAAI,YAAY,EAAE,MAAM,2CAA2C,CAAC;AACnF,OAAO,EAAE,oBAAoB,EAAE,MAAM,2CAA2C,CAAC;AACjF,OAAO,EAAE,qBAAqB,EAAE,sBAAsB,EAAE,MAAM,oCAAoC,CAAC;AACnG,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EACN,4BAA4B,EAC5B,2BAA2B,EAC3B,2BAA2B,EAC3B,kBAAkB,GAClB,MAAM,4BAA4B,CAAC;AACpC,OAAO,EAAE,oBAAoB,EAAE,MAAM,yBAAyB,CAAC;AAC/D,OAAO,EAAE,uBAAuB,EAAE,MAAM,oBAAoB,CAAC;AAC7D,OAAO,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,qBAAqB,EAAE,MAAM,gBAAgB,CAAC;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,UAAU,GAAG,IAAI,CAAC;YACnB,CAAC;YAED,SAAS,GAAG,KAAK,CAAC;QACnB,CAAC;QAED,MAAM;YACL,OAAO,OAAO,CAAC,CAAC,CAAC,aAAa,CAAC,GAAG,CAAC,CAAC,CAAC,UAAU,CAAC;QACjD,CAAC;QAED,WAAW;YACV,OAAO,QAAQ,CAAC;QACjB,CAAC;QAED,YAAY;YACX,OAAO,iBAAiB,CAAC;QAC1B,CAAC;QAED,OAAO,EAAE,aAAa,CAAC,MAAM,CAAC,cAAc;QAC5C,eAAe,EAAE,aAAa,CAAC,MAAM,CAAC,eAAe;KACrD,CAAC;AACH,CAAC"}
|
package/dist/tool-router.d.ts
CHANGED
|
@@ -5,6 +5,8 @@
|
|
|
5
5
|
* Used by both stdio and HTTP transports to eliminate routing duplication.
|
|
6
6
|
*/
|
|
7
7
|
import type { BatchRequest, BatchResult, CommandContext, CommandResult, PipelineRequest, PipelineResult } from '@lushly-dev/afd-core';
|
|
8
|
+
import type { ContextState } from './bootstrap/afd-context.js';
|
|
9
|
+
import { type GroupByFn } from './command-routing.js';
|
|
8
10
|
import type { ZodCommandDefinition } from './schema.js';
|
|
9
11
|
export interface ToolCallResult {
|
|
10
12
|
content: Array<{
|
|
@@ -19,18 +21,17 @@ export interface ToolRouterDeps {
|
|
|
19
21
|
executePipeline: (request: PipelineRequest, context?: CommandContext) => Promise<PipelineResult>;
|
|
20
22
|
commands: ZodCommandDefinition[];
|
|
21
23
|
toolStrategy: 'individual' | 'grouped' | 'lazy';
|
|
22
|
-
groupByFn?:
|
|
24
|
+
groupByFn?: GroupByFn;
|
|
23
25
|
devMode: boolean;
|
|
24
26
|
/** All registered commands, including those outside the commands array */
|
|
25
27
|
allCommands?: ZodCommandDefinition[];
|
|
26
28
|
/** Set of command names exposed via the server's commands array */
|
|
27
29
|
exposedCommandNames?: Set<string>;
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
};
|
|
30
|
+
/** Context state used when the call context carries none (stdio and tests). */
|
|
31
|
+
contextState?: ContextState;
|
|
31
32
|
}
|
|
32
33
|
/**
|
|
33
34
|
* Create a tool call router that dispatches to the appropriate execution function.
|
|
34
35
|
*/
|
|
35
|
-
export declare function createToolRouter(deps: ToolRouterDeps): (toolName: string, args: unknown) => Promise<ToolCallResult>;
|
|
36
|
+
export declare function createToolRouter(deps: ToolRouterDeps): (toolName: string, args: unknown, callContext?: CommandContext) => Promise<ToolCallResult>;
|
|
36
37
|
//# sourceMappingURL=tool-router.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tool-router.d.ts","sourceRoot":"","sources":["../src/tool-router.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EACX,YAAY,EACZ,WAAW,EACX,cAAc,EACd,aAAa,EACb,eAAe,EACf,cAAc,EACd,MAAM,sBAAsB,CAAC;
|
|
1
|
+
{"version":3,"file":"tool-router.d.ts","sourceRoot":"","sources":["../src/tool-router.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EACX,YAAY,EACZ,WAAW,EACX,cAAc,EACd,aAAa,EACb,eAAe,EACf,cAAc,EACd,MAAM,sBAAsB,CAAC;AAE9B,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,4BAA4B,CAAC;AAC/D,OAAO,EAIN,KAAK,SAAS,EAId,MAAM,sBAAsB,CAAC;AAY9B,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,aAAa,CAAC;AAMxD,MAAM,WAAW,cAAc;IAC9B,OAAO,EAAE,KAAK,CAAC;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC/C,OAAO,EAAE,OAAO,CAAC;CACjB;AAED,MAAM,WAAW,cAAc;IAC9B,cAAc,EAAE,CACf,IAAI,EAAE,MAAM,EACZ,KAAK,EAAE,OAAO,EACd,OAAO,CAAC,EAAE,cAAc,KACpB,OAAO,CAAC,aAAa,CAAC,CAAC;IAC5B,YAAY,EAAE,CAAC,OAAO,EAAE,YAAY,EAAE,OAAO,CAAC,EAAE,cAAc,KAAK,OAAO,CAAC,WAAW,CAAC,CAAC;IACxF,eAAe,EAAE,CAAC,OAAO,EAAE,eAAe,EAAE,OAAO,CAAC,EAAE,cAAc,KAAK,OAAO,CAAC,cAAc,CAAC,CAAC;IACjG,QAAQ,EAAE,oBAAoB,EAAE,CAAC;IACjC,YAAY,EAAE,YAAY,GAAG,SAAS,GAAG,MAAM,CAAC;IAChD,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB,OAAO,EAAE,OAAO,CAAC;IACjB,0EAA0E;IAC1E,WAAW,CAAC,EAAE,oBAAoB,EAAE,CAAC;IACrC,mEAAmE;IACnE,mBAAmB,CAAC,EAAE,GAAG,CAAC,MAAM,CAAC,CAAC;IAClC,+EAA+E;IAC/E,YAAY,CAAC,EAAE,YAAY,CAAC;CAC5B;AAsDD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,cAAc,IAoBnD,UAAU,MAAM,EAChB,MAAM,OAAO,EACb,cAAa,cAAmB,KAC9B,OAAO,CAAC,cAAc,CAAC,CAoO1B"}
|
package/dist/tool-router.js
CHANGED
|
@@ -4,8 +4,11 @@
|
|
|
4
4
|
*
|
|
5
5
|
* Used by both stdio and HTTP transports to eliminate routing duplication.
|
|
6
6
|
*/
|
|
7
|
-
import {
|
|
7
|
+
import { failure, isBatchRequest, isPipelineRequest, truncateName } from '@lushly-dev/afd-core';
|
|
8
|
+
import { commandAction, commandGroup, filterByContext, isAccessibleInContext, notFoundSuggestion, notInContextError, } from './command-routing.js';
|
|
9
|
+
import { resolveContextState } from './context-scope.js';
|
|
8
10
|
import { executeDetail, executeDiscover } from './lazy-tools.js';
|
|
11
|
+
import { batchArgsSchema, callArgsSchema, checkMetaArgs, detailArgsSchema, discoverArgsSchema, parseMetaArgs, pipeArgsSchema, } from './meta-tools.js';
|
|
9
12
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
10
13
|
// EMPTY PIPELINE RESULT (for invalid pipeline requests)
|
|
11
14
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
@@ -27,48 +30,49 @@ const emptyPipelineResult = {
|
|
|
27
30
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
28
31
|
// ROUTER
|
|
29
32
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
33
|
+
/**
|
|
34
|
+
* Wrap a result as MCP tool content. The JSON is compact: the text is read by an
|
|
35
|
+
* agent, and indentation only adds tokens.
|
|
36
|
+
*/
|
|
30
37
|
function resultContent(data, isError) {
|
|
31
38
|
return {
|
|
32
|
-
content: [{ type: 'text', text: JSON.stringify(data
|
|
39
|
+
content: [{ type: 'text', text: JSON.stringify(data) }],
|
|
33
40
|
isError,
|
|
34
41
|
};
|
|
35
42
|
}
|
|
36
43
|
/**
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
* - No active context (everything visible)
|
|
40
|
-
* - Command has no contexts array (universal / backward compat)
|
|
41
|
-
* - Command's contexts include the active context
|
|
44
|
+
* The `COMMAND_NOT_IN_CONTEXT` tool result when `cmd` exists but is outside the
|
|
45
|
+
* active context; undefined otherwise (a missing command is left to execution).
|
|
42
46
|
*/
|
|
43
|
-
function
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
if (!cmd.contexts?.length)
|
|
49
|
-
return true;
|
|
50
|
-
return cmd.contexts.includes(activeContext);
|
|
47
|
+
function contextDenial(cmd, commandName, contextState) {
|
|
48
|
+
const activeContext = contextState?.getActive();
|
|
49
|
+
if (!cmd || !activeContext || isAccessibleInContext(cmd, activeContext))
|
|
50
|
+
return undefined;
|
|
51
|
+
return resultContent({ success: false, error: notInContextError(commandName, activeContext) }, true);
|
|
51
52
|
}
|
|
52
53
|
/**
|
|
53
54
|
* Create a tool call router that dispatches to the appropriate execution function.
|
|
54
55
|
*/
|
|
55
56
|
export function createToolRouter(deps) {
|
|
56
|
-
const { executeCommand, executeBatch, executePipeline, commands, toolStrategy, groupByFn, devMode, allCommands, exposedCommandNames,
|
|
57
|
-
|
|
57
|
+
const { executeCommand, executeBatch, executePipeline, commands, toolStrategy, groupByFn, devMode, allCommands, exposedCommandNames, } = deps;
|
|
58
|
+
/**
|
|
59
|
+
* Route one tool call.
|
|
60
|
+
*
|
|
61
|
+
* @param callContext - Base `CommandContext` for commands this call runs (request values,
|
|
62
|
+
* `signal`, and the caller's context state); each execution adds its own `traceId`.
|
|
63
|
+
*/
|
|
64
|
+
return async function routeToolCall(toolName, args, callContext = {}) {
|
|
65
|
+
const contextState = resolveContextState(callContext, deps.contextState);
|
|
66
|
+
const traced = (prefix) => ({
|
|
67
|
+
...callContext,
|
|
68
|
+
traceId: `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
69
|
+
});
|
|
58
70
|
// Handle afd-call (available in all strategies)
|
|
59
71
|
if (toolName === 'afd-call') {
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
success: false,
|
|
65
|
-
error: {
|
|
66
|
-
code: 'VALIDATION_ERROR',
|
|
67
|
-
message: 'Missing required field: command',
|
|
68
|
-
suggestion: 'Provide { command: "command-name", input: {...} }',
|
|
69
|
-
},
|
|
70
|
-
}, true);
|
|
71
|
-
}
|
|
72
|
+
const parsed = parseMetaArgs(toolName, callArgsSchema, args, 'Provide { command: "command-name", input: {...} }');
|
|
73
|
+
if (!parsed.success)
|
|
74
|
+
return resultContent(parsed.result, true);
|
|
75
|
+
const { command: commandName, input } = parsed.data;
|
|
72
76
|
// Check if command exists in the exposed commands
|
|
73
77
|
const cmd = commands.find((c) => c.name === commandName);
|
|
74
78
|
if (!cmd) {
|
|
@@ -84,88 +88,92 @@ export function createToolRouter(deps) {
|
|
|
84
88
|
},
|
|
85
89
|
}, true);
|
|
86
90
|
}
|
|
87
|
-
// Not found at all — suggest
|
|
88
|
-
const
|
|
89
|
-
const suggestions = findSimilarTools(commandName, allNames, 3);
|
|
90
|
-
const suggestionText = suggestions.length > 0
|
|
91
|
-
? `Did you mean '${suggestions[0]}'? Use afd-discover to list all commands.`
|
|
92
|
-
: 'Use afd-discover to list all commands.';
|
|
91
|
+
// Not found at all — suggest a few close matches the caller can use
|
|
92
|
+
const callable = filterByContext(commands, contextState?.getActive());
|
|
93
93
|
return resultContent({
|
|
94
94
|
success: false,
|
|
95
95
|
error: {
|
|
96
96
|
code: 'COMMAND_NOT_FOUND',
|
|
97
|
-
message: `Command '${commandName}' not found`,
|
|
98
|
-
suggestion:
|
|
97
|
+
message: `Command '${truncateName(commandName)}' not found`,
|
|
98
|
+
suggestion: notFoundSuggestion(commandName, callable.map((c) => c.name)),
|
|
99
99
|
},
|
|
100
100
|
}, true);
|
|
101
101
|
}
|
|
102
102
|
// Context check: validate the command is accessible in current context
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
return resultContent({
|
|
107
|
-
success: false,
|
|
108
|
-
error: {
|
|
109
|
-
code: 'COMMAND_NOT_IN_CONTEXT',
|
|
110
|
-
message: `Command '${commandName}' is not available in context '${activeContext}'`,
|
|
111
|
-
suggestion: 'Use afd-context-list to see available contexts, or afd-context-enter to switch.',
|
|
112
|
-
},
|
|
113
|
-
}, true);
|
|
114
|
-
}
|
|
115
|
-
}
|
|
103
|
+
const denied = contextDenial(cmd, commandName, contextState);
|
|
104
|
+
if (denied)
|
|
105
|
+
return denied;
|
|
116
106
|
// Execute through the execution engine (full middleware chain)
|
|
117
|
-
const result = await executeCommand(commandName,
|
|
118
|
-
traceId: `afd-call-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
119
|
-
});
|
|
107
|
+
const result = await executeCommand(commandName, input ?? {}, traced('afd-call'));
|
|
120
108
|
return resultContent(result, !result.success);
|
|
121
109
|
}
|
|
122
|
-
// Handle afd-discover (lazy strategy
|
|
110
|
+
// Handle afd-discover (listed by the lazy strategy, routable in all)
|
|
123
111
|
if (toolName === 'afd-discover') {
|
|
112
|
+
const parsed = parseMetaArgs(toolName, discoverArgsSchema, args, 'Provide optional { category, tag, tagMode, search, includeMutation, limit, offset }');
|
|
113
|
+
if (!parsed.success)
|
|
114
|
+
return resultContent(parsed.result, true);
|
|
124
115
|
// Filter by active context when context state is available
|
|
125
|
-
const
|
|
126
|
-
const
|
|
127
|
-
? commands.filter((cmd) => !cmd.contexts?.length || cmd.contexts.includes(activeContext))
|
|
128
|
-
: commands;
|
|
129
|
-
const result = executeDiscover(discoverCommands, (args ?? {}));
|
|
116
|
+
const discoverCommands = filterByContext(commands, contextState?.getActive());
|
|
117
|
+
const result = executeDiscover(discoverCommands, parsed.data);
|
|
130
118
|
return resultContent(result, false);
|
|
131
119
|
}
|
|
132
|
-
// Handle afd-detail (lazy
|
|
120
|
+
// Handle afd-detail (listed by the lazy and grouped strategies, routable in all)
|
|
133
121
|
if (toolName === 'afd-detail') {
|
|
122
|
+
const parsed = parseMetaArgs(toolName, detailArgsSchema, args, 'Provide { command: "command-name" } or { command: ["name-1", "name-2"] } (max 10)');
|
|
123
|
+
if (!parsed.success)
|
|
124
|
+
return resultContent(parsed.result, true);
|
|
134
125
|
const exposedNames = exposedCommandNames ?? new Set(commands.map((c) => c.name));
|
|
135
|
-
const allCmds = allCommands ?? commands;
|
|
136
126
|
// Filter by active context so agents cannot inspect commands outside their context
|
|
137
|
-
const
|
|
138
|
-
const
|
|
139
|
-
? allCmds.filter((cmd) => !cmd.contexts?.length || cmd.contexts.includes(activeContext))
|
|
140
|
-
: allCmds;
|
|
141
|
-
const result = executeDetail(contextFilteredCmds, exposedNames, (args ?? {}));
|
|
127
|
+
const contextFilteredCmds = filterByContext(allCommands ?? commands, contextState?.getActive());
|
|
128
|
+
const result = executeDetail(contextFilteredCmds, exposedNames, parsed.data);
|
|
142
129
|
return resultContent(result, false);
|
|
143
130
|
}
|
|
144
131
|
// Handle built-in afd-batch tool
|
|
145
132
|
if (toolName === 'afd-batch') {
|
|
146
|
-
|
|
133
|
+
// The Zod schema pinpoints shape errors; isBatchRequest is the envelope check
|
|
134
|
+
// shared with POST /batch. Both report INVALID_BATCH_REQUEST.
|
|
135
|
+
const check = checkMetaArgs(batchArgsSchema, args);
|
|
136
|
+
if (!check.success || !isBatchRequest(args)) {
|
|
137
|
+
const usage = 'Provide { commands: [...] } with command objects';
|
|
147
138
|
return resultContent({
|
|
148
139
|
success: false,
|
|
149
140
|
error: {
|
|
150
141
|
code: 'INVALID_BATCH_REQUEST',
|
|
151
142
|
message: 'Invalid batch request format',
|
|
152
|
-
suggestion:
|
|
143
|
+
suggestion: check.success ? usage : `${check.suggestion}. ${usage}`,
|
|
144
|
+
...(!check.success && { details: { errors: check.errors } }),
|
|
153
145
|
},
|
|
154
146
|
}, true);
|
|
155
147
|
}
|
|
156
|
-
const result = await executeBatch(args,
|
|
157
|
-
traceId: `batch-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
158
|
-
});
|
|
148
|
+
const result = await executeBatch(args, traced('batch'));
|
|
159
149
|
return resultContent(result, !result.success);
|
|
160
150
|
}
|
|
161
151
|
// Handle built-in afd-pipe tool
|
|
162
152
|
if (toolName === 'afd-pipe') {
|
|
163
|
-
|
|
164
|
-
|
|
153
|
+
// As for afd-batch: Zod pinpoints shape errors, and isPipelineRequest checks the
|
|
154
|
+
// whole envelope (including `when` conditions). Both report INVALID_PIPELINE_REQUEST.
|
|
155
|
+
const check = checkMetaArgs(pipeArgsSchema, args);
|
|
156
|
+
if (!check.success || !isPipelineRequest(args)) {
|
|
157
|
+
const usage = 'Provide steps with nonempty command names, object inputs, valid conditions, and correctly typed options; input must be JSON';
|
|
158
|
+
return resultContent({
|
|
159
|
+
...emptyPipelineResult,
|
|
160
|
+
steps: [
|
|
161
|
+
{
|
|
162
|
+
index: -1,
|
|
163
|
+
command: '',
|
|
164
|
+
status: 'failure',
|
|
165
|
+
executionTimeMs: 0,
|
|
166
|
+
error: {
|
|
167
|
+
code: 'INVALID_PIPELINE_REQUEST',
|
|
168
|
+
message: 'Invalid pipeline request envelope',
|
|
169
|
+
suggestion: check.success ? usage : `${check.suggestion}. ${usage}`,
|
|
170
|
+
...(!check.success && { details: { errors: check.errors } }),
|
|
171
|
+
},
|
|
172
|
+
},
|
|
173
|
+
],
|
|
174
|
+
}, true);
|
|
165
175
|
}
|
|
166
|
-
const result = await executePipeline(args,
|
|
167
|
-
traceId: `pipeline-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
168
|
-
});
|
|
176
|
+
const result = await executePipeline(args, traced('pipeline'));
|
|
169
177
|
const hasFailed = result.steps.some((s) => s.status === 'failure');
|
|
170
178
|
return resultContent(result, hasFailed);
|
|
171
179
|
}
|
|
@@ -178,38 +186,27 @@ export function createToolRouter(deps) {
|
|
|
178
186
|
console.error(`[MCP Debug] Grouped tool call: toolName=${toolName}, action=${action}, args=${JSON.stringify(args)}`);
|
|
179
187
|
}
|
|
180
188
|
if (action && typeof action === 'string') {
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
success: false,
|
|
189
|
-
error: {
|
|
190
|
-
code: 'COMMAND_NOT_IN_CONTEXT',
|
|
191
|
-
message: `Command '${actualCommandName}' is not available in context '${activeContext}'`,
|
|
192
|
-
suggestion: 'Use afd-context-list to see available contexts, or afd-context-enter to switch.',
|
|
193
|
-
},
|
|
194
|
-
}, true);
|
|
195
|
-
}
|
|
189
|
+
const candidates = commands.filter((command) => commandGroup(command, groupByFn) === toolName && commandAction(command) === action);
|
|
190
|
+
if (candidates.length !== 1) {
|
|
191
|
+
return resultContent(failure({
|
|
192
|
+
code: candidates.length ? 'AMBIGUOUS_ACTION' : 'COMMAND_NOT_FOUND',
|
|
193
|
+
message: `Action '${truncateName(action)}' does not identify one command in group '${truncateName(toolName)}'`,
|
|
194
|
+
suggestion: 'Use afd-call with the full command name, or list tools to find a valid action.',
|
|
195
|
+
}), true);
|
|
196
196
|
}
|
|
197
|
-
const
|
|
198
|
-
|
|
199
|
-
|
|
197
|
+
const actualCommandName = candidates[0]?.name;
|
|
198
|
+
// Context check for grouped strategy
|
|
199
|
+
const denied = contextDenial(candidates[0], actualCommandName, contextState);
|
|
200
|
+
if (denied)
|
|
201
|
+
return denied;
|
|
202
|
+
const result = await executeCommand(actualCommandName, commandParams, traced('trace'));
|
|
200
203
|
return resultContent(result, !result.success);
|
|
201
204
|
}
|
|
202
205
|
// In grouped mode, if tool is a known group but action is missing/invalid,
|
|
203
206
|
// return a helpful error instead of falling through
|
|
204
|
-
const
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
if (groupNames.has(toolName)) {
|
|
208
|
-
const groupCommands = commands.filter((cmd) => getGroup(cmd) === toolName);
|
|
209
|
-
const availableActions = groupCommands.map((cmd) => {
|
|
210
|
-
const parts = cmd.name.split('-');
|
|
211
|
-
return parts.length > 1 ? parts.slice(1).join('-') : cmd.name;
|
|
212
|
-
});
|
|
207
|
+
const groupCommands = commands.filter((cmd) => commandGroup(cmd, groupByFn) === toolName);
|
|
208
|
+
if (groupCommands.length > 0) {
|
|
209
|
+
const availableActions = groupCommands.map(commandAction);
|
|
213
210
|
return resultContent({
|
|
214
211
|
success: false,
|
|
215
212
|
error: {
|
|
@@ -223,23 +220,10 @@ export function createToolRouter(deps) {
|
|
|
223
220
|
}
|
|
224
221
|
// Handle user-defined commands (individual mode or direct command calls)
|
|
225
222
|
// Context check: validate the command is accessible in current context
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
return resultContent({
|
|
231
|
-
success: false,
|
|
232
|
-
error: {
|
|
233
|
-
code: 'COMMAND_NOT_IN_CONTEXT',
|
|
234
|
-
message: `Command '${toolName}' is not available in context '${activeContext}'`,
|
|
235
|
-
suggestion: 'Use afd-context-list to see available contexts, or afd-context-enter to switch.',
|
|
236
|
-
},
|
|
237
|
-
}, true);
|
|
238
|
-
}
|
|
239
|
-
}
|
|
240
|
-
const result = await executeCommand(toolName, args ?? {}, {
|
|
241
|
-
traceId: `trace-${Date.now()}-${Math.random().toString(36).slice(2)}`,
|
|
242
|
-
});
|
|
223
|
+
const denied = contextDenial(commands.find((c) => c.name === toolName), toolName, contextState);
|
|
224
|
+
if (denied)
|
|
225
|
+
return denied;
|
|
226
|
+
const result = await executeCommand(toolName, args ?? {}, traced('trace'));
|
|
243
227
|
return resultContent(result, !result.success);
|
|
244
228
|
};
|
|
245
229
|
}
|