@lushly-dev/afd-server 0.6.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 +320 -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 +5 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -2
- 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 +100 -13
- package/dist/server-types.d.ts.map +1 -1
- package/dist/server-types.js.map +1 -1
- package/dist/server.d.ts +10 -2
- package/dist/server.d.ts.map +1 -1
- package/dist/server.js +165 -48
- 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/README.md
CHANGED
|
@@ -19,6 +19,7 @@ pnpm add @lushly-dev/afd-server
|
|
|
19
19
|
- **Built-in Validation** - Automatic input validation before handler execution
|
|
20
20
|
- **Middleware System** - Logging, tracing, rate limiting, and custom middleware
|
|
21
21
|
- **Command Prerequisites** - Declare `requires` dependencies so agents can plan execution order
|
|
22
|
+
- **Agent Discovery** - Grouped, individual or lazy tool strategies, `afd-detail`, and optional `afd-help`/`afd-docs`/`afd-schema` bootstrap tools
|
|
22
23
|
- **Full TypeScript Support** - Complete type inference from Zod schemas
|
|
23
24
|
|
|
24
25
|
## Quick Start
|
|
@@ -29,6 +30,7 @@ import { defineCommand, createMcpServer, defaultMiddleware, success, failure } f
|
|
|
29
30
|
|
|
30
31
|
// Define a command with Zod schema
|
|
31
32
|
const greet = defineCommand({
|
|
33
|
+
expose: { mcp: true }, // Explicitly allow remote invocation
|
|
32
34
|
name: 'greet',
|
|
33
35
|
description: 'Greet a user by name',
|
|
34
36
|
category: 'demo',
|
|
@@ -59,9 +61,40 @@ const server = createMcpServer({
|
|
|
59
61
|
});
|
|
60
62
|
|
|
61
63
|
await server.start();
|
|
62
|
-
console.
|
|
64
|
+
console.error(`Server running at ${server.getUrl()}`);
|
|
63
65
|
```
|
|
64
66
|
|
|
67
|
+
## Remote Command Exposure
|
|
68
|
+
|
|
69
|
+
Remote invocation now enforces the core exposure contract: commands require `expose: { mcp: true }`. Omitting `expose`, omitting `expose.mcp`, or setting it to `false` keeps a command private. This applies to tool listing, discovery, direct MCP calls, `afd-call`, batch, pipelines, `/rpc`, and streaming. Existing applications should explicitly opt in their public commands. The server's in-process `execute()` and `executePipeline()` remain available for private commands.
|
|
70
|
+
|
|
71
|
+
Configured `contexts` automatically register `afd-context-list`, `afd-context-enter`, and `afd-context-exit`. Active contexts scope all remote execution paths. Context state belongs to the client, not the server: stdio has one stack, and each HTTP session has its own (see [Context Management](#context-management)).
|
|
72
|
+
|
|
73
|
+
## Embedding In A Host-Controlled HTTP Server
|
|
74
|
+
|
|
75
|
+
Use `createMcpHandler()` when your platform owns the HTTP server lifecycle and expects a request handler instead of a self-starting server object:
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
import { createServer } from 'node:http';
|
|
79
|
+
import { createMcpHandler } from '@lushly-dev/afd-server';
|
|
80
|
+
|
|
81
|
+
const handler = createMcpHandler({
|
|
82
|
+
name: 'my-server',
|
|
83
|
+
version: '1.0.0',
|
|
84
|
+
commands: [greet],
|
|
85
|
+
host: '127.0.0.1',
|
|
86
|
+
port: 3100,
|
|
87
|
+
});
|
|
88
|
+
|
|
89
|
+
createServer((req, res) => {
|
|
90
|
+
void handler(req, res);
|
|
91
|
+
}).listen(3100, '127.0.0.1');
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
Call `handler.dispose()` when the embedding host shuts down to close active SSE/stream responses and drop HTTP sessions. The host still owns its listener and other connections.
|
|
95
|
+
|
|
96
|
+
Use `createMcpServer()` for the batteries-included standalone server. Use `createMcpHandler()` when you need AFD to plug into an existing Node HTTP host.
|
|
97
|
+
|
|
65
98
|
## Transport Protocols
|
|
66
99
|
|
|
67
100
|
The server supports multiple transport protocols for different use cases:
|
|
@@ -82,6 +115,8 @@ const server = createMcpServer({
|
|
|
82
115
|
// When stdin is a TTY (interactive context): uses HTTP
|
|
83
116
|
```
|
|
84
117
|
|
|
118
|
+
> **Pitfall:** `auto` picks stdio whenever stdin is not a TTY. Under Docker without `-t`, systemd, pm2 or CI, the server therefore speaks stdio and the HTTP port never opens. Set `transport: 'http'` for any server that must listen on the network. `start()` logs the resolved transport to stderr, for example `[my-server] MCP transport: stdio (auto-detected because stdin is not a TTY; set transport: 'http' to serve HTTP)`.
|
|
119
|
+
|
|
85
120
|
### stdio Transport (IDE/Agent Integration)
|
|
86
121
|
|
|
87
122
|
Use stdio for integration with IDE MCP clients like Cursor, Claude Code, or Antigravity:
|
|
@@ -124,12 +159,38 @@ const server = createMcpServer({
|
|
|
124
159
|
});
|
|
125
160
|
|
|
126
161
|
await server.start();
|
|
127
|
-
console.
|
|
162
|
+
console.error(`Server running at ${server.getUrl()}`);
|
|
128
163
|
// Exposes /sse, /message, /health endpoints
|
|
129
164
|
```
|
|
130
165
|
|
|
131
166
|
## Defining Commands
|
|
132
167
|
|
|
168
|
+
### Browser-safe entry point: `@lushly-dev/afd-server/define`
|
|
169
|
+
|
|
170
|
+
The root entry loads the MCP SDK, `node:http` and `node:tls`, so it cannot be
|
|
171
|
+
bundled for the browser. Code that only defines commands (shared command
|
|
172
|
+
modules, UI state packages, in-app agents) can import from the `/define`
|
|
173
|
+
subpath instead. It exports `defineCommand`, the schema helpers
|
|
174
|
+
(`zodToJsonSchema`, `getRequiredFields`, `isObjectSchema`), the result helpers
|
|
175
|
+
(`success`, `failure`, `error`, `isSuccess`, `isFailure`), `defaultExpose` and
|
|
176
|
+
the matching types, with no MCP SDK or Node.js builtin in its module graph:
|
|
177
|
+
|
|
178
|
+
```typescript
|
|
179
|
+
import { z } from 'zod';
|
|
180
|
+
import { defineCommand, success } from '@lushly-dev/afd-server/define';
|
|
181
|
+
|
|
182
|
+
export const panelOpen = defineCommand({
|
|
183
|
+
name: 'panel-open',
|
|
184
|
+
description: 'Open a panel',
|
|
185
|
+
input: z.object({ id: z.string() }),
|
|
186
|
+
async handler(input) {
|
|
187
|
+
return success({ id: input.id, open: true });
|
|
188
|
+
},
|
|
189
|
+
});
|
|
190
|
+
```
|
|
191
|
+
|
|
192
|
+
The same functions are still exported from `@lushly-dev/afd-server`.
|
|
193
|
+
|
|
133
194
|
### Basic Command
|
|
134
195
|
|
|
135
196
|
```typescript
|
|
@@ -159,6 +220,8 @@ const createUser = defineCommand({
|
|
|
159
220
|
});
|
|
160
221
|
```
|
|
161
222
|
|
|
223
|
+
The advertised JSON Schema describes what a caller may **send** (Zod input mode): `role` has a default, so it is optional and only `email` and `name` are required. Input schemas may use `.transform()` and `.pipe()`; they are advertised by their input type (a `z.string().transform(Number)` field is a string), and the handler receives the transformed value. `output` schemas are generated in output mode. Integer fields (`z.number().int()`) are advertised as `type: 'integer'`. Examples are typed and validated as raw input, so they may omit defaulted fields.
|
|
224
|
+
|
|
162
225
|
### Command with Error Handling
|
|
163
226
|
|
|
164
227
|
```typescript
|
|
@@ -203,7 +266,7 @@ const secretData = defineCommand({
|
|
|
203
266
|
});
|
|
204
267
|
```
|
|
205
268
|
|
|
206
|
-
Prerequisites are metadata — they tell agents what to call first but are not enforced at runtime (middleware handles enforcement). They appear in MCP tool `_meta` and `afd-help` output
|
|
269
|
+
Prerequisites are metadata — they tell agents what to call first but are not enforced at runtime (middleware handles enforcement). They appear in MCP tool `_meta` (per action in `_meta.actions` for grouped tools), in `afd-detail`, and in `afd-help` output when the server has `bootstrap: true`.
|
|
207
270
|
|
|
208
271
|
### Command with Output Schema
|
|
209
272
|
|
|
@@ -259,7 +322,13 @@ const server = createMcpServer({
|
|
|
259
322
|
// Optional
|
|
260
323
|
port: 3100, // Default: 3100
|
|
261
324
|
host: 'localhost', // Default: localhost
|
|
262
|
-
|
|
325
|
+
transport: 'http', // Default: 'auto' (see the pitfall above)
|
|
326
|
+
cors: true, // Send CORS headers (default: follows devMode)
|
|
327
|
+
toolStrategy: 'grouped', // Default: 'grouped' (see "Tool Strategies")
|
|
328
|
+
bootstrap: true, // Add afd-help, afd-docs, afd-schema (default: false)
|
|
329
|
+
|
|
330
|
+
// Per-request context for HTTP calls (see "Request Context")
|
|
331
|
+
createContext: (req) => ({ clientIp: req.socket.remoteAddress ?? 'unknown' }),
|
|
263
332
|
|
|
264
333
|
// Middleware — zero-config observability
|
|
265
334
|
middleware: defaultMiddleware(),
|
|
@@ -345,13 +414,43 @@ const middleware = createTracingMiddleware({
|
|
|
345
414
|
|
|
346
415
|
### Rate Limiting
|
|
347
416
|
|
|
417
|
+
Key the limiter on a value that identifies the caller. Over HTTP, provide it with `createContext`; the default key (`'global'`) shares one budget between all clients, and `traceId` is unique per call, so it never limits anything.
|
|
418
|
+
|
|
348
419
|
```typescript
|
|
349
|
-
import { createRateLimitMiddleware } from '@lushly-dev/afd-server';
|
|
420
|
+
import { createMcpServer, createRateLimitMiddleware } from '@lushly-dev/afd-server';
|
|
350
421
|
|
|
351
|
-
const
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
422
|
+
const server = createMcpServer({
|
|
423
|
+
name: 'my-server',
|
|
424
|
+
version: '1.0.0',
|
|
425
|
+
commands,
|
|
426
|
+
transport: 'http',
|
|
427
|
+
// Prefer an authenticated user ID; fall back to the socket address. Do not trust
|
|
428
|
+
// X-Forwarded-For unless your own proxy sets it.
|
|
429
|
+
createContext: (req) => ({
|
|
430
|
+
clientId: authenticate(req)?.userId ?? req.socket.remoteAddress ?? 'unknown',
|
|
431
|
+
}),
|
|
432
|
+
middleware: [
|
|
433
|
+
createRateLimitMiddleware({
|
|
434
|
+
maxRequests: 100,
|
|
435
|
+
windowMs: 60000, // 100 requests per minute, per client
|
|
436
|
+
keyFn: (context) => String(context.clientId ?? 'unknown'),
|
|
437
|
+
}),
|
|
438
|
+
],
|
|
439
|
+
});
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
### Retries
|
|
443
|
+
|
|
444
|
+
`createRetryMiddleware` reruns a command whose failure code passes `shouldRetry` (default: `TRANSIENT_ERROR` and `TIMEOUT`), up to `maxRetries` times (default: 3). The backoff is exponential and capped: retry `n` backs off `min(maxDelay, retryDelay * 2 ** (n - 1))`, with `retryDelay` defaulting to 100 ms and `maxDelay` to 5000 ms. With `jitter` (the default) each wait is a random time between half and all of that backoff; `jitter: false` waits exactly the backoff. When `context.signal` aborts, for example because the client disconnected or a batch deadline passed, the wait ends and the last failure is returned without further retries. Retry only commands that are safe to repeat.
|
|
445
|
+
|
|
446
|
+
```typescript
|
|
447
|
+
import { createRetryMiddleware } from '@lushly-dev/afd-server';
|
|
448
|
+
|
|
449
|
+
const retry = createRetryMiddleware({
|
|
450
|
+
maxRetries: 4,
|
|
451
|
+
retryDelay: 200, // 200, 400, 800, 1600 ms before jitter
|
|
452
|
+
maxDelay: 1000, // ...capped at 1000 ms
|
|
453
|
+
shouldRetry: (code) => code === 'UPSTREAM_UNAVAILABLE',
|
|
355
454
|
});
|
|
356
455
|
```
|
|
357
456
|
|
|
@@ -368,6 +467,44 @@ const myMiddleware: CommandMiddleware = async (commandName, input, context, next
|
|
|
368
467
|
};
|
|
369
468
|
```
|
|
370
469
|
|
|
470
|
+
## In-Process Agents: `createDirectRegistry`
|
|
471
|
+
|
|
472
|
+
For an AI agent in the same process, `DirectClient` from `@lushly-dev/afd-client`
|
|
473
|
+
skips the transport. Give it a registry built with `createDirectRegistry`, not
|
|
474
|
+
one that calls `command.handler(input)` directly: the registry runs every call
|
|
475
|
+
through the same engine as `createMcpServer` (Zod input validation, middleware,
|
|
476
|
+
error sanitization, `onCommand`/`onError`), and only lists and runs commands
|
|
477
|
+
exposed to the chosen interface.
|
|
478
|
+
|
|
479
|
+
```typescript
|
|
480
|
+
import { createDirectClient } from '@lushly-dev/afd-client';
|
|
481
|
+
import { createDirectRegistry, createLoggingMiddleware } from '@lushly-dev/afd-server';
|
|
482
|
+
|
|
483
|
+
const registry = createDirectRegistry(commands, {
|
|
484
|
+
interface: 'agent', // default
|
|
485
|
+
middleware: [createLoggingMiddleware()],
|
|
486
|
+
});
|
|
487
|
+
const client = createDirectClient(registry);
|
|
488
|
+
|
|
489
|
+
await client.call('todo-create', { title: { nested: true } });
|
|
490
|
+
// → { success: false, error: { code: 'VALIDATION_ERROR', ... } }
|
|
491
|
+
```
|
|
492
|
+
|
|
493
|
+
| Option | Default | Description |
|
|
494
|
+
|--------|---------|-------------|
|
|
495
|
+
| `interface` | `'agent'` | Interface served: `'agent'`, `'palette'`, `'mcp'` or `'cli'` |
|
|
496
|
+
| `middleware` | `[]` | Middleware, as for `createMcpServer` |
|
|
497
|
+
| `devMode` | `false` | Include exception messages and stacks in failures |
|
|
498
|
+
| `onCommand`, `onError` | — | Hooks, as for `createMcpServer` |
|
|
499
|
+
|
|
500
|
+
A command is exposed to the interface when its `expose` flag for it is `true`.
|
|
501
|
+
Flags a command leaves out fall back to `defaultExpose` (`palette` and `agent`
|
|
502
|
+
on, `mcp` and `cli` off), so `expose: { mcp: true }` stays available to agents.
|
|
503
|
+
Set `expose: { agent: false }` to keep a command away from in-app agents.
|
|
504
|
+
Commands that are registered but not exposed are left out of
|
|
505
|
+
`listCommands()`/`hasCommand()`, and `execute()` returns `COMMAND_NOT_EXPOSED`
|
|
506
|
+
for them. Duplicate command names throw.
|
|
507
|
+
|
|
371
508
|
## Validation Utilities
|
|
372
509
|
|
|
373
510
|
```typescript
|
|
@@ -412,7 +549,7 @@ Create a command definition with Zod schema.
|
|
|
412
549
|
|--------|------|----------|-------------|
|
|
413
550
|
| `name` | string | Yes | Unique command name (e.g., `user-create`) |
|
|
414
551
|
| `description` | string | Yes | Human-readable description |
|
|
415
|
-
| `input` | ZodType | Yes | Zod schema for input validation |
|
|
552
|
+
| `input` | ZodType | Yes | Zod schema for input validation; advertised in Zod input mode (defaulted fields optional, transforms allowed) |
|
|
416
553
|
| `handler` | function | Yes | Command implementation |
|
|
417
554
|
| `category` | string | No | Category for grouping |
|
|
418
555
|
| `mutation` | boolean | No | Whether command has side effects |
|
|
@@ -422,6 +559,8 @@ Create a command definition with Zod schema.
|
|
|
422
559
|
| `contexts` | string[] | No | Restrict command to specific contexts (omit for universal) |
|
|
423
560
|
| `requires` | string[] | No | Commands that should be called before this one (metadata only) |
|
|
424
561
|
| `errors` | string[] | No | Possible error codes |
|
|
562
|
+
| `expose` | ExposeOptions | No | Surfaces the command is exposed to; `{ mcp: true }` is required for MCP tools |
|
|
563
|
+
| `examples` | `{ title, input }[]` | No | Example inputs, validated against `input` at define time |
|
|
425
564
|
|
|
426
565
|
### createMcpServer(options)
|
|
427
566
|
|
|
@@ -432,13 +571,22 @@ Create an MCP server from commands.
|
|
|
432
571
|
| `name` | string | Yes | Server name |
|
|
433
572
|
| `version` | string | Yes | Server version |
|
|
434
573
|
| `commands` | array | Yes | Command definitions |
|
|
435
|
-
| `transport` | `'stdio' \| 'http' \| 'auto'` | No | Transport protocol (default: `'auto'
|
|
574
|
+
| `transport` | `'stdio' \| 'http' \| 'auto'` | No | Transport protocol (default: `'auto'`, which picks stdio whenever stdin is not a TTY) |
|
|
436
575
|
| `port` | number | No | Port for HTTP transport (default: 3100) |
|
|
437
576
|
| `host` | string | No | Host for HTTP transport (default: localhost) |
|
|
438
577
|
| `toolStrategy` | `'individual' \| 'grouped' \| 'lazy'` | No | How commands appear as MCP tools (default: `'grouped'`) |
|
|
578
|
+
| `groupByFn` | `(command) => string \| undefined` | No | Group name for the grouped strategy (default: `category`, else the first name segment) |
|
|
439
579
|
| `contexts` | `{ name, description }[]` | No | Context scopes for dynamic tool filtering |
|
|
580
|
+
| `bootstrap` | boolean | No | Register the `afd-help`, `afd-docs` and `afd-schema` MCP tools (default: `false`) |
|
|
440
581
|
| `devMode` | boolean | No | Enable development mode (default: false) |
|
|
441
582
|
| `cors` | boolean | No | Enable CORS for HTTP transport (default: follows devMode) |
|
|
583
|
+
| `allowedOrigins` | string[] | No | Additional exact browser origins |
|
|
584
|
+
| `allowedHosts` | string[] | No | Accepted HTTP hostnames, without ports |
|
|
585
|
+
| `maxBodyBytes` | number | No | Maximum JSON body bytes (default: 1048576) |
|
|
586
|
+
| `createContext` | `(req) => object \| Promise<object>` | No | Per-request values merged into the `CommandContext` of every remotely executed HTTP command |
|
|
587
|
+
| `maxSseConnections` | number | No | Concurrent `/sse` connections before HTTP 503 (default: 100) |
|
|
588
|
+
| `maxSessions` | number | No | Live HTTP sessions when `contexts` are set; the least recently used is evicted (default: 1000) |
|
|
589
|
+
| `sessionIdleTimeoutMs` | number | No | Idle time before an HTTP session expires (default: 1800000, 30 minutes) |
|
|
442
590
|
| `middleware` | array | No | Middleware functions |
|
|
443
591
|
| `onCommand` | function | No | Command execution callback |
|
|
444
592
|
| `onError` | function | No | Error callback |
|
|
@@ -474,6 +622,40 @@ The server exposes these endpoints:
|
|
|
474
622
|
| `/message` | POST | JSON-RPC message endpoint |
|
|
475
623
|
| `/rpc` | POST | Simple JSON-RPC for browser clients |
|
|
476
624
|
| `/health` | GET | Health check |
|
|
625
|
+
| `/batch` | POST | Batch command execution |
|
|
626
|
+
| `/stream/:name` | POST | SSE chunks with command input in the JSON body |
|
|
627
|
+
| `/stream/:name?input=...` | GET | Legacy streaming with JSON input in the query; refused (HTTP 405) for `mutation: true` commands; input over `maxBodyBytes` is refused (HTTP 413) |
|
|
628
|
+
|
|
629
|
+
### JSON-RPC Behavior (`/message` and `/rpc`)
|
|
630
|
+
|
|
631
|
+
- A message with `"jsonrpc": "2.0"` and no `id` is a notification. It is answered with HTTP 202 and an empty body. On `/message` it is not executed (MCP notifications need no work here, and a request method sent without an `id` could not return its result). On `/rpc` the command runs, but its result is not sent. The simple `/rpc` format without a `jsonrpc` member is always answered, with `id: null` if omitted.
|
|
632
|
+
- Protocol errors are JSON-RPC error objects, with recovery guidance in `error.data.suggestion`:
|
|
633
|
+
|
|
634
|
+
| Code | Meaning | HTTP status |
|
|
635
|
+
|------|---------|-------------|
|
|
636
|
+
| `-32700` | Body is not valid JSON | 400 |
|
|
637
|
+
| `-32600` | Not a valid request object (including batch arrays, which are not supported) | 400 |
|
|
638
|
+
| `-32601` | Unknown MCP method | 200 |
|
|
639
|
+
| `-32602` | Invalid `tools/call` params | 200 |
|
|
640
|
+
| `-32603` | Internal error (for example a throwing `createContext`); details only in `devMode` | 200 |
|
|
641
|
+
| `-32000` | Transport rejection: Host, Origin, Content-Type or body size | 400, 403, 413 or 415 |
|
|
642
|
+
| `-32001` | Unknown or expired `Mcp-Session-Id` | 404 |
|
|
643
|
+
|
|
644
|
+
Command failures are not protocol errors: they stay AFD `CommandResult` failures inside `result`. `/batch` and `/stream` are not JSON-RPC and answer errors with `{ success: false, error: { code, message, suggestion } }`.
|
|
645
|
+
|
|
646
|
+
### Streaming (`/stream`)
|
|
647
|
+
|
|
648
|
+
`/stream/:name` answers with Server-Sent Events, one `event: chunk` per `StreamChunk`. It is not incremental streaming: the command's handler runs to completion first, and the chunks are produced from its final result afterwards. An array result becomes one `data` chunk per item, any other result a single `data` chunk, followed by a `complete` chunk; a failure becomes one `error` chunk. No `progress` chunks are emitted, and the time to the first chunk is the handler's full run time. Handlers return a single `CommandResult`; returning an async iterable is not supported, and the `StreamableCommand` marker from core is metadata only. If the client disconnects, the command's `context.signal` aborts.
|
|
649
|
+
|
|
650
|
+
Batch (`/batch`, `afd-batch`) and stream execution use the core `executeBatch()` and `executeStream()` executors with the server's command execution as the callback, so they behave like the core registry and DirectClient.
|
|
651
|
+
|
|
652
|
+
### Sessions (`Mcp-Session-Id`)
|
|
653
|
+
|
|
654
|
+
When `contexts` are configured, `initialize` on `/message` returns an `Mcp-Session-Id` response header. Repeat it on later `/message`, `/rpc`, `/batch` and `/stream` requests to use that session's context stack. Requests without the header are stateless. An unknown or expired session ID is answered with HTTP 404; start a new session with `initialize`. `@lushly-dev/afd-client` does this automatically. Without `contexts`, no session is issued and the header is ignored.
|
|
655
|
+
|
|
656
|
+
### SSE Connections
|
|
657
|
+
|
|
658
|
+
`/sse` accepts at most `maxSseConnections` concurrent connections (default: 100); more receive HTTP 503 with `Retry-After`. Open connections get a `: ping` comment every 25 seconds so proxies keep them open and dead peers are detected. Closed connections are removed immediately, and `dispose()`/`stop()` closes the rest.
|
|
477
659
|
|
|
478
660
|
### Browser-Friendly `/rpc` Endpoint
|
|
479
661
|
|
|
@@ -517,7 +699,13 @@ console.log(result.data.greeting); // "Hello, World!"
|
|
|
517
699
|
|
|
518
700
|
### CORS Configuration
|
|
519
701
|
|
|
520
|
-
|
|
702
|
+
HTTP requests validate Host and browser Origin before dispatch. The default Host allowlist contains the configured host and loopback names. Requests without an Origin (such as CLI clients) and same-origin browser requests are accepted. Cross-site browser requests are rejected unless their exact Origin is listed in `allowedOrigins`. `cors: true` adds response headers for accepted origins; it does not disable request validation. `devMode: true` intentionally permits any browser origin, while Host checks remain enabled.
|
|
703
|
+
|
|
704
|
+
All POST endpoints require `Content-Type: application/json`. Request bodies, and the `input` query parameter of `GET /stream`, are limited to 1 MiB (UTF-8 bytes) by default; set `maxBodyBytes` to change the limit. Larger input is refused with HTTP 413 whatever header size limit the host sets. Configure `allowedHosts` and `allowedOrigins` explicitly when embedding behind a proxy. Forwarded headers are not trusted automatically.
|
|
705
|
+
|
|
706
|
+
POST streaming is preferred because input stays out of URLs. Legacy GET streaming remains supported and applies the same browser-origin policy.
|
|
707
|
+
|
|
708
|
+
Configure a browser UI explicitly:
|
|
521
709
|
|
|
522
710
|
```typescript
|
|
523
711
|
const server = createMcpServer({
|
|
@@ -526,11 +714,55 @@ const server = createMcpServer({
|
|
|
526
714
|
commands: [greet],
|
|
527
715
|
transport: 'http',
|
|
528
716
|
port: 3100,
|
|
529
|
-
cors: true,
|
|
530
|
-
|
|
717
|
+
cors: true,
|
|
718
|
+
allowedOrigins: ['https://app.example.com'],
|
|
719
|
+
allowedHosts: ['localhost', 'api.example.com'],
|
|
720
|
+
maxBodyBytes: 1024 * 1024,
|
|
531
721
|
});
|
|
532
722
|
```
|
|
533
723
|
|
|
724
|
+
## Tool Strategies
|
|
725
|
+
|
|
726
|
+
`toolStrategy` controls how MCP-exposed commands appear in `tools/list`. `afd-call`, `afd-batch` and `afd-pipe` are listed in every strategy.
|
|
727
|
+
|
|
728
|
+
| Strategy | Tools listed |
|
|
729
|
+
|----------|--------------|
|
|
730
|
+
| `grouped` (default) | One tool per group plus `afd-detail`. A group is the command's `category`, else the first name segment (`todo-create` → `todo`), or `groupByFn(command)` |
|
|
731
|
+
| `individual` | One tool per command, with its full input schema and `_meta` |
|
|
732
|
+
| `lazy` | `afd-discover` and `afd-detail` only |
|
|
733
|
+
|
|
734
|
+
A grouped tool takes `{ action, params }`, where `action` is the command name without its group segment (`todo-create-batch` → `create-batch`). So that agents need not guess `params`, each grouped tool carries every action's schema and metadata in `_meta.actions`:
|
|
735
|
+
|
|
736
|
+
```json
|
|
737
|
+
{
|
|
738
|
+
"name": "todo",
|
|
739
|
+
"inputSchema": {
|
|
740
|
+
"type": "object",
|
|
741
|
+
"properties": {
|
|
742
|
+
"action": { "type": "string", "enum": ["create", "list"] },
|
|
743
|
+
"params": { "type": "object", "anyOf": [{ "title": "create", "...": "todo-create input schema" }] }
|
|
744
|
+
},
|
|
745
|
+
"required": ["action"]
|
|
746
|
+
},
|
|
747
|
+
"_meta": {
|
|
748
|
+
"actions": [
|
|
749
|
+
{
|
|
750
|
+
"action": "create",
|
|
751
|
+
"command": "todo-create",
|
|
752
|
+
"description": "Create a todo",
|
|
753
|
+
"inputSchema": { "type": "object", "properties": { "title": { "type": "string" } }, "required": ["title"] },
|
|
754
|
+
"requires": ["auth-sign-in"],
|
|
755
|
+
"mutation": true,
|
|
756
|
+
"examples": [{ "title": "Basic", "input": { "title": "Buy milk" } }],
|
|
757
|
+
"outputSchema": { "type": "object" }
|
|
758
|
+
}
|
|
759
|
+
]
|
|
760
|
+
}
|
|
761
|
+
}
|
|
762
|
+
```
|
|
763
|
+
|
|
764
|
+
When a group's per-action schemas are small (at most 8,192 characters of JSON, and no `$ref`), they are also inlined as `params.anyOf` branches titled with the action. They sit under `params` because some MCP hosts reject `oneOf`/`anyOf`/`allOf` at the top level of a tool schema, and they use `anyOf` because actions often share a params shape. For larger groups, read `_meta.actions` or call `afd-detail` with the command name.
|
|
765
|
+
|
|
534
766
|
## Lazy Strategy
|
|
535
767
|
|
|
536
768
|
For servers with many commands, the `lazy` strategy exposes 5 meta-tools instead of listing all commands:
|
|
@@ -554,6 +786,39 @@ Agents discover commands at runtime: `afd-discover` (filter/list) → `afd-detai
|
|
|
554
786
|
| `afd-batch` | Execute multiple commands in one call |
|
|
555
787
|
| `afd-pipe` | Pipeline execution with step references |
|
|
556
788
|
|
|
789
|
+
The meta-tools are routable in every strategy. Their arguments are validated against the schemas they advertise: invalid `afd-call`, `afd-discover` and `afd-detail` arguments return a `VALIDATION_ERROR` result (with `details.errors`), and invalid `afd-batch`/`afd-pipe` envelopes return `INVALID_BATCH_REQUEST`/`INVALID_PIPELINE_REQUEST`. A `null` argument to `afd-call`, `afd-discover` or `afd-detail` counts as omitted.
|
|
790
|
+
|
|
791
|
+
Output is kept small so lazy discovery stays cheap:
|
|
792
|
+
|
|
793
|
+
- Tool results are compact JSON (no indentation).
|
|
794
|
+
- An unknown command name, whether called directly, through `afd-call`, `/rpc`, a batch entry or a pipeline step, returns `COMMAND_NOT_FOUND`. Its suggestion names at most three close matches callable in the active context and points to `afd-discover`, for example `Did you mean 'todo-create'? Other close matches: 'todo-update'. Use afd-discover to list all commands.` It never lists every command.
|
|
795
|
+
- `afd-detail` entries for unknown names echo the requested name cut to 128 characters plus `…`. Found commands keep their exact name.
|
|
796
|
+
|
|
797
|
+
## Bootstrap Tools
|
|
798
|
+
|
|
799
|
+
Set `bootstrap: true` to register three onboarding tools, exposed over MCP like any other command:
|
|
800
|
+
|
|
801
|
+
```typescript
|
|
802
|
+
const server = createMcpServer({
|
|
803
|
+
name: 'my-server',
|
|
804
|
+
version: '1.0.0',
|
|
805
|
+
commands: allCommands,
|
|
806
|
+
bootstrap: true,
|
|
807
|
+
});
|
|
808
|
+
```
|
|
809
|
+
|
|
810
|
+
| Tool | Input | Returns |
|
|
811
|
+
|------|-------|---------|
|
|
812
|
+
| `afd-help` | `{ filter?, format?: 'brief' \| 'full' }` | Commands with `requires`, grouped by category (`full` adds tags, mutation and examples) |
|
|
813
|
+
| `afd-docs` | `{ command? }` | Markdown documentation with a parameter table per command |
|
|
814
|
+
| `afd-schema` | `{ format?: 'json' \| 'typescript' }` | Input JSON Schemas; `typescript` adds a module declaring one `<Command>Input` type per command |
|
|
815
|
+
|
|
816
|
+
They describe what a remote agent can see: MCP-exposed commands in the active context, including the built-in context and bootstrap commands. `server.execute('afd-help', {})` works in-process too. `getBootstrapCommands(getCommands)` returns the same tools (as `ZodCommandDefinition`s with `expose: { mcp: true }`) for custom setups; prefer the option with `createMcpServer`.
|
|
817
|
+
|
|
818
|
+
## Reserved and Duplicate Names
|
|
819
|
+
|
|
820
|
+
Server creation throws when two commands share a name, or when a command uses a name the server handles itself: `afd-call`, `afd-batch`, `afd-pipe`, `afd-discover` and `afd-detail` always; `afd-help`, `afd-docs` and `afd-schema` with `bootstrap: true`; `afd-context-list`, `afd-context-enter` and `afd-context-exit` when `contexts` is set.
|
|
821
|
+
|
|
557
822
|
## Context Management
|
|
558
823
|
|
|
559
824
|
Dynamic context scoping filters which commands are visible:
|
|
@@ -578,9 +843,50 @@ When contexts are configured, the server registers three additional bootstrap co
|
|
|
578
843
|
|
|
579
844
|
Commands without `contexts` are always visible. Context commands themselves are always visible.
|
|
580
845
|
|
|
846
|
+
Context state is per client:
|
|
847
|
+
|
|
848
|
+
- **stdio** serves one client, so it keeps one stack.
|
|
849
|
+
- **HTTP** keeps one stack per session. `initialize` returns an `Mcp-Session-Id` header, and requests that repeat it share that session's stack; one client entering a context never changes another client's `tools/list` or execution. Requests without the header see no active context, and `afd-context-enter`/`afd-context-exit` return `SESSION_REQUIRED` for them. Sessions expire after `sessionIdleTimeoutMs` of inactivity, and at most `maxSessions` are kept.
|
|
850
|
+
- A stack holds at most 16 contexts (`CONTEXT_DEPTH_EXCEEDED` beyond that), and re-entering the active context is a no-op.
|
|
851
|
+
- In-process `server.execute()` ignores contexts.
|
|
852
|
+
|
|
853
|
+
## Request Context
|
|
854
|
+
|
|
855
|
+
`createContext(req)` derives per-request values from the HTTP request, such as the authenticated user or the remote address. Its result is merged into the `CommandContext` of every command the request runs: `tools/call`, `afd-call`, `afd-batch` items, `afd-pipe` steps, `/rpc`, `/batch` and `/stream`. Middleware and handlers read the values from `context`:
|
|
856
|
+
|
|
857
|
+
```typescript
|
|
858
|
+
const server = createMcpServer({
|
|
859
|
+
name: 'my-server',
|
|
860
|
+
version: '1.0.0',
|
|
861
|
+
commands,
|
|
862
|
+
transport: 'http',
|
|
863
|
+
createContext: async (req) => ({ user: await verifyBearerToken(req.headers.authorization) }),
|
|
864
|
+
middleware: [
|
|
865
|
+
async (command, input, context, next) =>
|
|
866
|
+
context.user
|
|
867
|
+
? next()
|
|
868
|
+
: failure({ code: 'UNAUTHORIZED', message: 'Sign in first', suggestion: 'Send a bearer token' }),
|
|
869
|
+
],
|
|
870
|
+
});
|
|
871
|
+
```
|
|
872
|
+
|
|
873
|
+
- The server sets `traceId`, `signal` and `interface` (`'mcp'`) itself; `createContext` cannot override them.
|
|
874
|
+
- `context.signal` aborts when the client disconnects before the response is finished, on every route, not only streams. Long-running handlers should honor it.
|
|
875
|
+
- A throw from `createContext` is reported to `onError` and answered as an internal error (`-32603` on JSON-RPC routes, HTTP 500 elsewhere).
|
|
876
|
+
- Pipeline `$input` does not expose these values, so a pipeline cannot copy them into step inputs.
|
|
877
|
+
- stdio has no HTTP request, so `createContext` is not called there.
|
|
878
|
+
|
|
581
879
|
## Related
|
|
582
880
|
|
|
583
881
|
- [@lushly-dev/afd-core](../core) - Core types and helpers
|
|
584
882
|
- [@lushly-dev/afd-client](../client) - MCP client library
|
|
585
883
|
- [@lushly-dev/afd-cli](../cli) - Command-line interface
|
|
586
884
|
- [Example: Todo App](../examples/todo/) - Complete working example
|
|
885
|
+
|
|
886
|
+
### Pipeline execution limits
|
|
887
|
+
|
|
888
|
+
Pipelines run sequentially. `parallel: true` and a step with `stream: true` (deprecated, not implemented) return an actionable `UNSUPPORTED_OPTION` failure on the offending step before invoking any command; `onProgress` is deprecated and never called. `timeoutMs` bounds each awaited step by the remaining pipeline deadline and aborts its `context.signal`; handlers must honor that signal to stop their own work. A timed-out mutation may still finish if its handler ignores cancellation, so inspect partial results before retrying. Numeric `$steps[n]` references use original request indices, including skipped or failed steps. `$first` refers to original step zero; `$prev` keeps the last successful result.
|
|
889
|
+
|
|
890
|
+
Variable references follow [`spec/pipeline-variables.md`](../../spec/pipeline-variables.md). `afd-pipe` accepts an optional top-level `input` (any JSON value) that steps read as `$input` and `$input.<path>`; `$input` never exposes the server's execution context (trace ID, auth or other context values), which it used to. Only whole strings of the reference forms are resolved: other `$` strings such as `$9.99` are literals, and `$$` sends a literal `$`. Paths follow only own keys of plain JSON objects and in-bounds array indices, so `constructor`, `__proto__` and other `__`-prefixed segments never resolve. Unresolved references are omitted from objects, become `null` in arrays, and make `when` comparisons false. Step inputs or `input` nested deeper than 64 levels are rejected with `VALIDATION_ERROR` before any step runs. Step data is copied between steps, so a handler that mutates its input cannot change another step's data.
|
|
891
|
+
|
|
892
|
+
Default logging and console telemetry write to stderr so stdio MCP frames remain valid. In-memory rate limiting expires old client keys as requests arrive and caps active keys with `maxKeys` (default: 10000); new keys receive `RATE_LIMITED` while capacity is full.
|
|
@@ -7,16 +7,25 @@
|
|
|
7
7
|
import type { CommandDefinition } from '@lushly-dev/afd-core';
|
|
8
8
|
import { z } from 'zod';
|
|
9
9
|
import type { ContextConfig } from '../server-types.js';
|
|
10
|
+
/** Default maximum depth of a context stack. */
|
|
11
|
+
export declare const DEFAULT_CONTEXT_MAX_DEPTH = 16;
|
|
10
12
|
export interface ContextState {
|
|
11
13
|
stack: string[];
|
|
14
|
+
/** Maximum stack depth (default: 16). `afd-context-enter` fails once it is reached. */
|
|
15
|
+
maxDepth?: number;
|
|
12
16
|
getActive(): string | null;
|
|
13
17
|
enter(name: string): void;
|
|
14
18
|
exit(): string | null;
|
|
15
19
|
}
|
|
16
20
|
/**
|
|
17
|
-
* Create a
|
|
21
|
+
* Create a context state manager: one stack of entered contexts.
|
|
22
|
+
*
|
|
23
|
+
* The MCP server keeps one for stdio and one per HTTP session. Re-entering the active context
|
|
24
|
+
* is a no-op, and `enter` throws once `maxDepth` contexts are stacked.
|
|
18
25
|
*/
|
|
19
|
-
export declare function createContextState(
|
|
26
|
+
export declare function createContextState(options?: {
|
|
27
|
+
maxDepth?: number;
|
|
28
|
+
}): ContextState;
|
|
20
29
|
declare const listInputSchema: z.ZodObject<{}, z.core.$strip>;
|
|
21
30
|
interface ContextInfo {
|
|
22
31
|
name: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"afd-context.d.ts","sourceRoot":"","sources":["../../src/bootstrap/afd-context.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,iBAAiB,
|
|
1
|
+
{"version":3,"file":"afd-context.d.ts","sourceRoot":"","sources":["../../src/bootstrap/afd-context.ts"],"names":[],"mappings":"AAAA;;;;;GAKG;AAEH,OAAO,KAAK,EAAE,iBAAiB,EAAiB,MAAM,sBAAsB,CAAC;AAE7E,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAExB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAC;AAMxD,gDAAgD;AAChD,eAAO,MAAM,yBAAyB,KAAK,CAAC;AAE5C,MAAM,WAAW,YAAY;IAC5B,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,uFAAuF;IACvF,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,SAAS,IAAI,MAAM,GAAG,IAAI,CAAC;IAC3B,KAAK,CAAC,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,IAAI,IAAI,MAAM,GAAG,IAAI,CAAC;CACtB;AAED;;;;;GAKG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,GAAE;IAAE,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAO,GAAG,YAAY,CAwBpF;AAgBD,QAAA,MAAM,eAAe,gCAAe,CAAC;AAErC,UAAU,WAAW;IACpB,IAAI,EAAE,MAAM,CAAC;IACb,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,QAAQ,CAAC,EAAE,MAAM,EAAE,CAAC;IACpB,QAAQ,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,UAAU,iBAAiB;IAC1B,QAAQ,EAAE,WAAW,EAAE,CAAC;IACxB,aAAa,EAAE,MAAM,GAAG,IAAI,CAAC;CAC7B;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CAC1C,WAAW,EAAE,MAAM,aAAa,EAAE,EAClC,YAAY,EAAE,YAAY,GACxB,iBAAiB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,EAAE,iBAAiB,CAAC,CAkCvE;AAMD,QAAA,MAAM,gBAAgB;;iBAEpB,CAAC;AAEH,UAAU,kBAAkB;IAC3B,OAAO,EAAE,MAAM,CAAC;IAChB,QAAQ,EAAE,MAAM,GAAG,IAAI,CAAC;CACxB;AAED;;GAEG;AACH,wBAAgB,4BAA4B,CAC3C,WAAW,EAAE,MAAM,aAAa,EAAE,EAClC,YAAY,EAAE,YAAY,GACxB,iBAAiB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,gBAAgB,CAAC,EAAE,kBAAkB,CAAC,CAsDzE;AAMD,QAAA,MAAM,eAAe,gCAAe,CAAC;AAErC,UAAU,iBAAiB;IAC1B,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED;;GAEG;AACH,wBAAgB,2BAA2B,CAC1C,YAAY,EAAE,YAAY,GACxB,iBAAiB,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,eAAe,CAAC,EAAE,iBAAiB,CAAC,CA2BvE"}
|
|
@@ -6,17 +6,36 @@
|
|
|
6
6
|
*/
|
|
7
7
|
import { failure, success } from '@lushly-dev/afd-core';
|
|
8
8
|
import { z } from 'zod';
|
|
9
|
+
import { resolveContextState } from '../context-scope.js';
|
|
10
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
11
|
+
// CONTEXT STATE
|
|
12
|
+
// ═══════════════════════════════════════════════════════════════════════════════
|
|
13
|
+
/** Default maximum depth of a context stack. */
|
|
14
|
+
export const DEFAULT_CONTEXT_MAX_DEPTH = 16;
|
|
9
15
|
/**
|
|
10
|
-
* Create a
|
|
16
|
+
* Create a context state manager: one stack of entered contexts.
|
|
17
|
+
*
|
|
18
|
+
* The MCP server keeps one for stdio and one per HTTP session. Re-entering the active context
|
|
19
|
+
* is a no-op, and `enter` throws once `maxDepth` contexts are stacked.
|
|
11
20
|
*/
|
|
12
|
-
export function createContextState() {
|
|
21
|
+
export function createContextState(options = {}) {
|
|
22
|
+
const maxDepth = options.maxDepth ?? DEFAULT_CONTEXT_MAX_DEPTH;
|
|
23
|
+
if (!Number.isSafeInteger(maxDepth) || maxDepth <= 0) {
|
|
24
|
+
throw new Error('Context maxDepth must be a positive integer');
|
|
25
|
+
}
|
|
13
26
|
const stack = [];
|
|
14
27
|
return {
|
|
15
28
|
stack,
|
|
29
|
+
maxDepth,
|
|
16
30
|
getActive() {
|
|
17
31
|
return stack.length > 0 ? (stack[stack.length - 1] ?? null) : null;
|
|
18
32
|
},
|
|
19
33
|
enter(name) {
|
|
34
|
+
if (stack[stack.length - 1] === name)
|
|
35
|
+
return;
|
|
36
|
+
if (stack.length >= maxDepth) {
|
|
37
|
+
throw new Error(`Context stack is limited to ${maxDepth} levels`);
|
|
38
|
+
}
|
|
20
39
|
stack.push(name);
|
|
21
40
|
},
|
|
22
41
|
exit() {
|
|
@@ -24,6 +43,14 @@ export function createContextState() {
|
|
|
24
43
|
},
|
|
25
44
|
};
|
|
26
45
|
}
|
|
46
|
+
/** Failure for context changes requested by a caller that has no session to hold them. */
|
|
47
|
+
function sessionRequired() {
|
|
48
|
+
return failure({
|
|
49
|
+
code: 'SESSION_REQUIRED',
|
|
50
|
+
message: 'Entering or exiting a context needs an MCP session, and this request has none',
|
|
51
|
+
suggestion: 'Send an MCP initialize request to /message and repeat its Mcp-Session-Id response header on later requests',
|
|
52
|
+
});
|
|
53
|
+
}
|
|
27
54
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
28
55
|
// afd-context-list
|
|
29
56
|
// ═══════════════════════════════════════════════════════════════════════════════
|
|
@@ -40,7 +67,8 @@ export function createAfdContextListCommand(getContexts, contextState) {
|
|
|
40
67
|
mutation: false,
|
|
41
68
|
version: '1.0.0',
|
|
42
69
|
parameters: [],
|
|
43
|
-
async handler() {
|
|
70
|
+
async handler(_input, context) {
|
|
71
|
+
const activeContext = resolveContextState(context, contextState)?.getActive() ?? null;
|
|
44
72
|
const configs = getContexts();
|
|
45
73
|
const contexts = configs
|
|
46
74
|
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
|
|
@@ -52,9 +80,9 @@ export function createAfdContextListCommand(getContexts, contextState) {
|
|
|
52
80
|
}));
|
|
53
81
|
return success({
|
|
54
82
|
contexts,
|
|
55
|
-
activeContext
|
|
83
|
+
activeContext,
|
|
56
84
|
}, {
|
|
57
|
-
reasoning: `Found ${contexts.length} configured contexts. Active: ${
|
|
85
|
+
reasoning: `Found ${contexts.length} configured contexts. Active: ${activeContext ?? 'none'}`,
|
|
58
86
|
confidence: 1.0,
|
|
59
87
|
});
|
|
60
88
|
},
|
|
@@ -80,7 +108,10 @@ export function createAfdContextEnterCommand(getContexts, contextState) {
|
|
|
80
108
|
parameters: [
|
|
81
109
|
{ name: 'context', type: 'string', required: true, description: 'Context name to enter' },
|
|
82
110
|
],
|
|
83
|
-
async handler(input) {
|
|
111
|
+
async handler(input, context) {
|
|
112
|
+
const state = resolveContextState(context, contextState);
|
|
113
|
+
if (!state)
|
|
114
|
+
return sessionRequired();
|
|
84
115
|
const configs = getContexts();
|
|
85
116
|
const contextName = input.context;
|
|
86
117
|
const exists = configs.some((c) => c.name === contextName);
|
|
@@ -92,8 +123,19 @@ export function createAfdContextEnterCommand(getContexts, contextState) {
|
|
|
92
123
|
suggestion: `Available contexts: ${available}. Use afd-context-list to see all contexts.`,
|
|
93
124
|
});
|
|
94
125
|
}
|
|
95
|
-
const previous =
|
|
96
|
-
|
|
126
|
+
const previous = state.getActive();
|
|
127
|
+
if (previous === contextName) {
|
|
128
|
+
return success({ entered: contextName, previous }, { reasoning: `Already in context '${contextName}'; nothing changed`, confidence: 1.0 });
|
|
129
|
+
}
|
|
130
|
+
const maxDepth = state.maxDepth ?? DEFAULT_CONTEXT_MAX_DEPTH;
|
|
131
|
+
if (state.stack.length >= maxDepth) {
|
|
132
|
+
return failure({
|
|
133
|
+
code: 'CONTEXT_DEPTH_EXCEEDED',
|
|
134
|
+
message: `Context stack is limited to ${maxDepth} levels`,
|
|
135
|
+
suggestion: 'Call afd-context-exit to leave a context before entering another',
|
|
136
|
+
});
|
|
137
|
+
}
|
|
138
|
+
state.enter(contextName);
|
|
97
139
|
return success({ entered: contextName, previous }, {
|
|
98
140
|
reasoning: `Entered context '${contextName}'${previous ? ` (was '${previous}')` : ''}`,
|
|
99
141
|
confidence: 1.0,
|
|
@@ -117,9 +159,12 @@ export function createAfdContextExitCommand(contextState) {
|
|
|
117
159
|
mutation: true,
|
|
118
160
|
version: '1.0.0',
|
|
119
161
|
parameters: [],
|
|
120
|
-
async handler() {
|
|
121
|
-
const
|
|
122
|
-
|
|
162
|
+
async handler(_input, context) {
|
|
163
|
+
const state = resolveContextState(context, contextState);
|
|
164
|
+
if (!state)
|
|
165
|
+
return sessionRequired();
|
|
166
|
+
const exited = state.exit();
|
|
167
|
+
const current = state.getActive();
|
|
123
168
|
return success({ exited, current }, {
|
|
124
169
|
reasoning: exited
|
|
125
170
|
? `Exited context '${exited}'${current ? `, now in '${current}'` : ', no active context'}`
|