@lushly-dev/afd-server 0.1.0 → 0.3.1

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.
Files changed (44) hide show
  1. package/LICENSE +21 -26
  2. package/README.md +475 -381
  3. package/dist/bootstrap/afd-docs.d.ts +1 -1
  4. package/dist/bootstrap/afd-docs.d.ts.map +1 -1
  5. package/dist/bootstrap/afd-docs.js +3 -3
  6. package/dist/bootstrap/afd-docs.js.map +1 -1
  7. package/dist/bootstrap/afd-help.d.ts +2 -1
  8. package/dist/bootstrap/afd-help.d.ts.map +1 -1
  9. package/dist/bootstrap/afd-help.js +4 -3
  10. package/dist/bootstrap/afd-help.js.map +1 -1
  11. package/dist/bootstrap/afd-schema.d.ts +1 -1
  12. package/dist/bootstrap/afd-schema.d.ts.map +1 -1
  13. package/dist/bootstrap/afd-schema.js +13 -13
  14. package/dist/bootstrap/afd-schema.js.map +1 -1
  15. package/dist/bootstrap/index.d.ts +1 -1
  16. package/dist/bootstrap/index.js +1 -1
  17. package/dist/bootstrap/registry.d.ts.map +1 -1
  18. package/dist/bootstrap/registry.js +3 -1
  19. package/dist/bootstrap/registry.js.map +1 -1
  20. package/dist/handoff-schema.d.ts +245 -0
  21. package/dist/handoff-schema.d.ts.map +1 -0
  22. package/dist/handoff-schema.js +97 -0
  23. package/dist/handoff-schema.js.map +1 -0
  24. package/dist/index.d.ts +8 -6
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +9 -8
  27. package/dist/index.js.map +1 -1
  28. package/dist/middleware.d.ts +217 -3
  29. package/dist/middleware.d.ts.map +1 -1
  30. package/dist/middleware.js +266 -4
  31. package/dist/middleware.js.map +1 -1
  32. package/dist/schema.d.ts +49 -4
  33. package/dist/schema.d.ts.map +1 -1
  34. package/dist/schema.js +37 -4
  35. package/dist/schema.js.map +1 -1
  36. package/dist/server.d.ts +11 -9
  37. package/dist/server.d.ts.map +1 -1
  38. package/dist/server.js +539 -161
  39. package/dist/server.js.map +1 -1
  40. package/dist/validation.d.ts +68 -79
  41. package/dist/validation.d.ts.map +1 -1
  42. package/dist/validation.js +96 -102
  43. package/dist/validation.js.map +1 -1
  44. package/package.json +19 -4
package/README.md CHANGED
@@ -1,381 +1,475 @@
1
- # @afd/server
2
-
3
- Server-side utilities for building AFD-compliant MCP servers with Zod validation.
4
-
5
- ## Installation
6
-
7
- ```bash
8
- npm install @afd/server
9
- # or
10
- pnpm add @afd/server
11
- ```
12
-
13
- ## Features
14
-
15
- - **Zod-based Command Definition** - Define commands with Zod schemas for type-safe validation
16
- - **Auto JSON Schema Generation** - Automatic conversion to JSON Schema for MCP tool definitions
17
- - **Multiple Transport Support** - stdio for IDE/agent integration, HTTP/SSE for browser clients
18
- - **Auto Transport Detection** - Automatically selects the right transport based on environment
19
- - **Built-in Validation** - Automatic input validation before handler execution
20
- - **Middleware System** - Logging, tracing, rate limiting, and custom middleware
21
- - **Full TypeScript Support** - Complete type inference from Zod schemas
22
-
23
- ## Quick Start
24
-
25
- ```typescript
26
- import { z } from 'zod';
27
- import { defineCommand, createMcpServer, success, failure } from '@afd/server';
28
-
29
- // Define a command with Zod schema
30
- const greet = defineCommand({
31
- name: 'greet',
32
- description: 'Greet a user by name',
33
- category: 'demo',
34
- input: z.object({
35
- name: z.string().min(1, 'Name is required'),
36
- formal: z.boolean().default(false),
37
- }),
38
-
39
- async handler(input) {
40
- const greeting = input.formal
41
- ? `Good day, ${input.name}.`
42
- : `Hello, ${input.name}!`;
43
-
44
- return success({ greeting }, {
45
- reasoning: `Generated ${input.formal ? 'formal' : 'casual'} greeting`,
46
- confidence: 1.0,
47
- });
48
- },
49
- });
50
-
51
- // Create and start the server (auto-detects transport)
52
- const server = createMcpServer({
53
- name: 'my-server',
54
- version: '1.0.0',
55
- commands: [greet],
56
- port: 3100,
57
- });
58
-
59
- await server.start();
60
- console.log(`Server running at ${server.getUrl()}`);
61
- ```
62
-
63
- ## Transport Protocols
64
-
65
- The server supports multiple transport protocols for different use cases:
66
-
67
- ### Auto-Detection (Default)
68
-
69
- By default, the server auto-detects the best transport based on the environment:
70
-
71
- ```typescript
72
- const server = createMcpServer({
73
- name: 'my-server',
74
- version: '1.0.0',
75
- commands: [greet],
76
- // transport: 'auto' is the default
77
- });
78
-
79
- // When stdin is piped (IDE/agent context): uses stdio
80
- // When stdin is a TTY (interactive context): uses HTTP
81
- ```
82
-
83
- ### stdio Transport (IDE/Agent Integration)
84
-
85
- Use stdio for integration with IDE MCP clients like Cursor, Claude Code, or Antigravity:
86
-
87
- ```typescript
88
- const server = createMcpServer({
89
- name: 'my-server',
90
- version: '1.0.0',
91
- commands: [greet],
92
- transport: 'stdio', // Explicit stdio mode
93
- });
94
-
95
- await server.start();
96
- // Server reads JSON-RPC from stdin, writes to stdout
97
- ```
98
-
99
- In your IDE's MCP configuration (adjust the path to match your project):
100
- ```json
101
- {
102
- "mcpServers": {
103
- "my-server": {
104
- "command": "node",
105
- "args": ["path/to/your/server.js"]
106
- }
107
- }
108
- }
109
- ```
110
-
111
- ### HTTP Transport (Browser/Web UI)
112
-
113
- Use HTTP for browser-based clients and web UIs:
114
-
115
- ```typescript
116
- const server = createMcpServer({
117
- name: 'my-server',
118
- version: '1.0.0',
119
- commands: [greet],
120
- transport: 'http', // Explicit HTTP mode
121
- port: 3100,
122
- });
123
-
124
- await server.start();
125
- console.log(`Server running at ${server.getUrl()}`);
126
- // Exposes /sse, /message, /health endpoints
127
- ```
128
-
129
- ## Defining Commands
130
-
131
- ### Basic Command
132
-
133
- ```typescript
134
- import { z } from 'zod';
135
- import { defineCommand, success, failure } from '@afd/server';
136
-
137
- const createUser = defineCommand({
138
- name: 'user.create',
139
- description: 'Create a new user',
140
- category: 'users',
141
- mutation: true,
142
-
143
- input: z.object({
144
- email: z.string().email(),
145
- name: z.string().min(1).max(100),
146
- role: z.enum(['admin', 'user', 'guest']).default('user'),
147
- }),
148
-
149
- async handler(input) {
150
- // Your implementation
151
- const user = await db.users.create(input);
152
-
153
- return success(user, {
154
- reasoning: `Created user ${user.email} with role ${user.role}`,
155
- });
156
- },
157
- });
158
- ```
159
-
160
- ### Command with Error Handling
161
-
162
- ```typescript
163
- const getUser = defineCommand({
164
- name: 'user.get',
165
- description: 'Get a user by ID',
166
- category: 'users',
167
- errors: ['NOT_FOUND'],
168
-
169
- input: z.object({
170
- id: z.string().uuid(),
171
- }),
172
-
173
- async handler(input) {
174
- const user = await db.users.find(input.id);
175
-
176
- if (!user) {
177
- return failure({
178
- code: 'NOT_FOUND',
179
- message: `User with ID "${input.id}" not found`,
180
- suggestion: 'Check the ID or use user.list to find available users',
181
- });
182
- }
183
-
184
- return success(user);
185
- },
186
- });
187
- ```
188
-
189
- ## Server Configuration
190
-
191
- ```typescript
192
- const server = createMcpServer({
193
- // Required
194
- name: 'my-server',
195
- version: '1.0.0',
196
- commands: [cmd1, cmd2, cmd3],
197
-
198
- // Optional
199
- port: 3100, // Default: 3100
200
- host: 'localhost', // Default: localhost
201
- cors: true, // Enable CORS (default: true)
202
-
203
- // Middleware
204
- middleware: [
205
- createLoggingMiddleware(),
206
- createTimingMiddleware({ slowThreshold: 1000 }),
207
- ],
208
-
209
- // Callbacks
210
- onCommand(command, input, result) {
211
- console.log(`Executed ${command}:`, result.success);
212
- },
213
- onError(error) {
214
- console.error('Server error:', error);
215
- },
216
- });
217
- ```
218
-
219
- ## Middleware
220
-
221
- ### Logging
222
-
223
- ```typescript
224
- import { createLoggingMiddleware } from '@afd/server';
225
-
226
- const middleware = createLoggingMiddleware({
227
- log: console.log, // Custom log function
228
- logInput: false, // Don't log input (may contain sensitive data)
229
- logResult: false, // Don't log full results
230
- });
231
- ```
232
-
233
- ### Timing
234
-
235
- ```typescript
236
- import { createTimingMiddleware } from '@afd/server';
237
-
238
- const middleware = createTimingMiddleware({
239
- slowThreshold: 1000, // Warn if command takes > 1s
240
- onSlow(command, durationMs) {
241
- console.warn(`Slow command: ${command} took ${durationMs}ms`);
242
- },
243
- });
244
- ```
245
-
246
- ### OpenTelemetry Tracing
247
-
248
- ```typescript
249
- import { trace } from '@opentelemetry/api';
250
- import { createTracingMiddleware } from '@afd/server';
251
-
252
- const tracer = trace.getTracer('my-app');
253
-
254
- const middleware = createTracingMiddleware({
255
- tracer,
256
- spanPrefix: 'command', // Span names: command.user.create, etc.
257
- });
258
- ```
259
-
260
- ### Rate Limiting
261
-
262
- ```typescript
263
- import { createRateLimitMiddleware } from '@afd/server';
264
-
265
- const middleware = createRateLimitMiddleware({
266
- maxRequests: 100,
267
- windowMs: 60000, // 100 requests per minute
268
- keyFn: (context) => context.userId ?? 'anonymous',
269
- });
270
- ```
271
-
272
- ### Custom Middleware
273
-
274
- ```typescript
275
- import type { CommandMiddleware } from '@afd/server';
276
-
277
- const myMiddleware: CommandMiddleware = async (commandName, input, context, next) => {
278
- console.log(`Before: ${commandName}`);
279
- const result = await next();
280
- console.log(`After: ${commandName}, success: ${result.success}`);
281
- return result;
282
- };
283
- ```
284
-
285
- ## Validation Utilities
286
-
287
- ```typescript
288
- import { validateInput, validateOrThrow, isValid, patterns } from '@afd/server';
289
-
290
- // Validate and get result
291
- const result = validateInput(schema, data);
292
- if (!result.success) {
293
- console.log(result.errors);
294
- }
295
-
296
- // Validate or throw
297
- try {
298
- const data = validateOrThrow(schema, input);
299
- } catch (e) {
300
- if (e instanceof ValidationException) {
301
- console.log(e.errors);
302
- }
303
- }
304
-
305
- // Check validity
306
- if (isValid(schema, data)) {
307
- // data is typed
308
- }
309
-
310
- // Common patterns
311
- const schema = z.object({
312
- id: patterns.uuid,
313
- email: patterns.email,
314
- count: patterns.positiveInt,
315
- ...patterns.pagination,
316
- });
317
- ```
318
-
319
- ## API Reference
320
-
321
- ### defineCommand(options)
322
-
323
- Create a command definition with Zod schema.
324
-
325
- | Option | Type | Required | Description |
326
- |--------|------|----------|-------------|
327
- | `name` | string | Yes | Unique command name (e.g., `user.create`) |
328
- | `description` | string | Yes | Human-readable description |
329
- | `input` | ZodType | Yes | Zod schema for input validation |
330
- | `handler` | function | Yes | Command implementation |
331
- | `category` | string | No | Category for grouping |
332
- | `mutation` | boolean | No | Whether command has side effects |
333
- | `version` | string | No | Command version |
334
- | `tags` | string[] | No | Additional tags |
335
- | `errors` | string[] | No | Possible error codes |
336
-
337
- ### createMcpServer(options)
338
-
339
- Create an MCP server from commands.
340
-
341
- | Option | Type | Required | Description |
342
- |--------|------|----------|-------------|
343
- | `name` | string | Yes | Server name |
344
- | `version` | string | Yes | Server version |
345
- | `commands` | array | Yes | Command definitions |
346
- | `transport` | `'stdio' \| 'http' \| 'auto'` | No | Transport protocol (default: `'auto'`) |
347
- | `port` | number | No | Port for HTTP transport (default: 3100) |
348
- | `host` | string | No | Host for HTTP transport (default: localhost) |
349
- | `devMode` | boolean | No | Enable development mode (default: false) |
350
- | `cors` | boolean | No | Enable CORS for HTTP transport (default: follows devMode) |
351
- | `middleware` | array | No | Middleware functions |
352
- | `onCommand` | function | No | Command execution callback |
353
- | `onError` | function | No | Error callback |
354
-
355
- ### Server Methods
356
-
357
- | Method | Description |
358
- |--------|-------------|
359
- | `start()` | Start the server |
360
- | `stop()` | Stop the server |
361
- | `getUrl()` | Get server URL (`"stdio://"` for stdio transport) |
362
- | `getTransport()` | Get the resolved transport mode (`"stdio"` or `"http"`) |
363
- | `getCommands()` | Get registered commands |
364
- | `execute(name, input, context)` | Execute command directly |
365
-
366
- ## Endpoints
367
-
368
- The server exposes these endpoints:
369
-
370
- | Endpoint | Method | Description |
371
- |----------|--------|-------------|
372
- | `/sse` | GET | SSE connection for MCP clients |
373
- | `/message` | POST | JSON-RPC message endpoint |
374
- | `/health` | GET | Health check |
375
-
376
- ## Related
377
-
378
- - [@afd/core](../core) - Core types and helpers
379
- - [@afd/client](../client) - MCP client library
380
- - [@afd/cli](../cli) - Command-line interface
381
- - [Example: Todo App](../examples/todo-app) - Complete working example
1
+ # @lushly-dev/afd-server
2
+
3
+ Server-side utilities for building AFD-compliant MCP servers with Zod validation.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @lushly-dev/afd-server
9
+ # or
10
+ pnpm add @lushly-dev/afd-server
11
+ ```
12
+
13
+ ## Features
14
+
15
+ - **Zod-based Command Definition** - Define commands with Zod schemas for type-safe validation
16
+ - **Auto JSON Schema Generation** - Automatic conversion to JSON Schema for MCP tool definitions
17
+ - **Multiple Transport Support** - stdio for IDE/agent integration, HTTP/SSE for browser clients
18
+ - **Auto Transport Detection** - Automatically selects the right transport based on environment
19
+ - **Built-in Validation** - Automatic input validation before handler execution
20
+ - **Middleware System** - Logging, tracing, rate limiting, and custom middleware
21
+ - **Full TypeScript Support** - Complete type inference from Zod schemas
22
+
23
+ ## Quick Start
24
+
25
+ ```typescript
26
+ import { z } from 'zod';
27
+ import { defineCommand, createMcpServer, defaultMiddleware, success, failure } from '@lushly-dev/afd-server';
28
+
29
+ // Define a command with Zod schema
30
+ const greet = defineCommand({
31
+ name: 'greet',
32
+ description: 'Greet a user by name',
33
+ category: 'demo',
34
+ input: z.object({
35
+ name: z.string().min(1, 'Name is required'),
36
+ formal: z.boolean().default(false),
37
+ }),
38
+
39
+ async handler(input) {
40
+ const greeting = input.formal
41
+ ? `Good day, ${input.name}.`
42
+ : `Hello, ${input.name}!`;
43
+
44
+ return success({ greeting }, {
45
+ reasoning: `Generated ${input.formal ? 'formal' : 'casual'} greeting`,
46
+ confidence: 1.0,
47
+ });
48
+ },
49
+ });
50
+
51
+ // Create and start the server (auto-detects transport)
52
+ const server = createMcpServer({
53
+ name: 'my-server',
54
+ version: '1.0.0',
55
+ commands: [greet],
56
+ middleware: defaultMiddleware(), // Trace IDs, logging, slow-command warnings
57
+ port: 3100,
58
+ });
59
+
60
+ await server.start();
61
+ console.log(`Server running at ${server.getUrl()}`);
62
+ ```
63
+
64
+ ## Transport Protocols
65
+
66
+ The server supports multiple transport protocols for different use cases:
67
+
68
+ ### Auto-Detection (Default)
69
+
70
+ By default, the server auto-detects the best transport based on the environment:
71
+
72
+ ```typescript
73
+ const server = createMcpServer({
74
+ name: 'my-server',
75
+ version: '1.0.0',
76
+ commands: [greet],
77
+ // transport: 'auto' is the default
78
+ });
79
+
80
+ // When stdin is piped (IDE/agent context): uses stdio
81
+ // When stdin is a TTY (interactive context): uses HTTP
82
+ ```
83
+
84
+ ### stdio Transport (IDE/Agent Integration)
85
+
86
+ Use stdio for integration with IDE MCP clients like Cursor, Claude Code, or Antigravity:
87
+
88
+ ```typescript
89
+ const server = createMcpServer({
90
+ name: 'my-server',
91
+ version: '1.0.0',
92
+ commands: [greet],
93
+ transport: 'stdio', // Explicit stdio mode
94
+ });
95
+
96
+ await server.start();
97
+ // Server reads JSON-RPC from stdin, writes to stdout
98
+ ```
99
+
100
+ In your IDE's MCP configuration (adjust the path to match your project):
101
+ ```json
102
+ {
103
+ "mcpServers": {
104
+ "my-server": {
105
+ "command": "node",
106
+ "args": ["path/to/your/server.js"]
107
+ }
108
+ }
109
+ }
110
+ ```
111
+
112
+ ### HTTP Transport (Browser/Web UI)
113
+
114
+ Use HTTP for browser-based clients and web UIs:
115
+
116
+ ```typescript
117
+ const server = createMcpServer({
118
+ name: 'my-server',
119
+ version: '1.0.0',
120
+ commands: [greet],
121
+ transport: 'http', // Explicit HTTP mode
122
+ port: 3100,
123
+ });
124
+
125
+ await server.start();
126
+ console.log(`Server running at ${server.getUrl()}`);
127
+ // Exposes /sse, /message, /health endpoints
128
+ ```
129
+
130
+ ## Defining Commands
131
+
132
+ ### Basic Command
133
+
134
+ ```typescript
135
+ import { z } from 'zod';
136
+ import { defineCommand, success, failure } from '@lushly-dev/afd-server';
137
+
138
+ const createUser = defineCommand({
139
+ name: 'user-create',
140
+ description: 'Create a new user',
141
+ category: 'users',
142
+ mutation: true,
143
+
144
+ input: z.object({
145
+ email: z.string().email(),
146
+ name: z.string().min(1).max(100),
147
+ role: z.enum(['admin', 'user', 'guest']).default('user'),
148
+ }),
149
+
150
+ async handler(input) {
151
+ // Your implementation
152
+ const user = await db.users.create(input);
153
+
154
+ return success(user, {
155
+ reasoning: `Created user ${user.email} with role ${user.role}`,
156
+ });
157
+ },
158
+ });
159
+ ```
160
+
161
+ ### Command with Error Handling
162
+
163
+ ```typescript
164
+ const getUser = defineCommand({
165
+ name: 'user-get',
166
+ description: 'Get a user by ID',
167
+ category: 'users',
168
+ errors: ['NOT_FOUND'],
169
+
170
+ input: z.object({
171
+ id: z.string().uuid(),
172
+ }),
173
+
174
+ async handler(input) {
175
+ const user = await db.users.find(input.id);
176
+
177
+ if (!user) {
178
+ return failure({
179
+ code: 'NOT_FOUND',
180
+ message: `User with ID "${input.id}" not found`,
181
+ suggestion: 'Check the ID or use user-list to find available users',
182
+ });
183
+ }
184
+
185
+ return success(user);
186
+ },
187
+ });
188
+ ```
189
+
190
+ ## Server Configuration
191
+
192
+ ```typescript
193
+ const server = createMcpServer({
194
+ // Required
195
+ name: 'my-server',
196
+ version: '1.0.0',
197
+ commands: [cmd1, cmd2, cmd3],
198
+
199
+ // Optional
200
+ port: 3100, // Default: 3100
201
+ host: 'localhost', // Default: localhost
202
+ cors: true, // Enable CORS (default: true)
203
+
204
+ // Middleware — zero-config observability
205
+ middleware: defaultMiddleware(),
206
+
207
+ // Callbacks
208
+ onCommand(command, input, result) {
209
+ console.log(`Executed ${command}:`, result.success);
210
+ },
211
+ onError(error) {
212
+ console.error('Server error:', error);
213
+ },
214
+ });
215
+ ```
216
+
217
+ ## Middleware
218
+
219
+ ### Default Middleware (Recommended)
220
+
221
+ `defaultMiddleware()` returns a pre-configured stack of three middleware covering common observability needs:
222
+
223
+ 1. **Auto Trace ID** — generates `context.traceId` via `crypto.randomUUID()` when not present
224
+ 2. **Structured Logging** — logs command start/completion with trace ID correlation
225
+ 3. **Slow-Command Warnings** — warns when commands exceed a configurable threshold (default: 1000ms)
226
+
227
+ ```typescript
228
+ import { defaultMiddleware } from '@lushly-dev/afd-server';
229
+
230
+ // Zero-config — all three enabled
231
+ middleware: defaultMiddleware()
232
+
233
+ // Selective disable
234
+ middleware: defaultMiddleware({ timing: false })
235
+
236
+ // Custom options
237
+ middleware: defaultMiddleware({
238
+ logging: { logInput: true },
239
+ timing: { slowThreshold: 500, onSlow: (name, ms) => logger.warn(`${name}: ${ms}ms`) },
240
+ traceId: { generate: () => `custom-${Date.now()}` },
241
+ })
242
+
243
+ // Compose with custom middleware
244
+ middleware: [...defaultMiddleware(), myAuthMiddleware, myRateLimiter]
245
+ ```
246
+
247
+ ### Logging
248
+
249
+ ```typescript
250
+ import { createLoggingMiddleware } from '@lushly-dev/afd-server';
251
+
252
+ const middleware = createLoggingMiddleware({
253
+ log: console.log, // Custom log function
254
+ logInput: false, // Don't log input (may contain sensitive data)
255
+ logResult: false, // Don't log full results
256
+ });
257
+ ```
258
+
259
+ ### Timing
260
+
261
+ ```typescript
262
+ import { createTimingMiddleware } from '@lushly-dev/afd-server';
263
+
264
+ const middleware = createTimingMiddleware({
265
+ slowThreshold: 1000, // Warn if command takes > 1s
266
+ onSlow(command, durationMs) {
267
+ console.warn(`Slow command: ${command} took ${durationMs}ms`);
268
+ },
269
+ });
270
+ ```
271
+
272
+ ### OpenTelemetry Tracing
273
+
274
+ ```typescript
275
+ import { trace } from '@opentelemetry/api';
276
+ import { createTracingMiddleware } from '@lushly-dev/afd-server';
277
+
278
+ const tracer = trace.getTracer('my-app');
279
+
280
+ const middleware = createTracingMiddleware({
281
+ tracer,
282
+ spanPrefix: 'command', // Span names: command.user-create, etc.
283
+ });
284
+ ```
285
+
286
+ ### Rate Limiting
287
+
288
+ ```typescript
289
+ import { createRateLimitMiddleware } from '@lushly-dev/afd-server';
290
+
291
+ const middleware = createRateLimitMiddleware({
292
+ maxRequests: 100,
293
+ windowMs: 60000, // 100 requests per minute
294
+ keyFn: (context) => context.userId ?? 'anonymous',
295
+ });
296
+ ```
297
+
298
+ ### Custom Middleware
299
+
300
+ ```typescript
301
+ import type { CommandMiddleware } from '@lushly-dev/afd-server';
302
+
303
+ const myMiddleware: CommandMiddleware = async (commandName, input, context, next) => {
304
+ console.log(`Before: ${commandName}`);
305
+ const result = await next();
306
+ console.log(`After: ${commandName}, success: ${result.success}`);
307
+ return result;
308
+ };
309
+ ```
310
+
311
+ ## Validation Utilities
312
+
313
+ ```typescript
314
+ import { validateInput, validateOrThrow, isValid, patterns } from '@lushly-dev/afd-server';
315
+
316
+ // Validate and get result
317
+ const result = validateInput(schema, data);
318
+ if (!result.success) {
319
+ console.log(result.errors);
320
+ }
321
+
322
+ // Validate or throw
323
+ try {
324
+ const data = validateOrThrow(schema, input);
325
+ } catch (e) {
326
+ if (e instanceof ValidationException) {
327
+ console.log(e.errors);
328
+ }
329
+ }
330
+
331
+ // Check validity
332
+ if (isValid(schema, data)) {
333
+ // data is typed
334
+ }
335
+
336
+ // Common patterns
337
+ const schema = z.object({
338
+ id: patterns.uuid,
339
+ email: patterns.email,
340
+ count: patterns.positiveInt,
341
+ ...patterns.pagination,
342
+ });
343
+ ```
344
+
345
+ ## API Reference
346
+
347
+ ### defineCommand(options)
348
+
349
+ Create a command definition with Zod schema.
350
+
351
+ | Option | Type | Required | Description |
352
+ |--------|------|----------|-------------|
353
+ | `name` | string | Yes | Unique command name (e.g., `user-create`) |
354
+ | `description` | string | Yes | Human-readable description |
355
+ | `input` | ZodType | Yes | Zod schema for input validation |
356
+ | `handler` | function | Yes | Command implementation |
357
+ | `category` | string | No | Category for grouping |
358
+ | `mutation` | boolean | No | Whether command has side effects |
359
+ | `version` | string | No | Command version |
360
+ | `tags` | string[] | No | Additional tags |
361
+ | `requires` | string[] | No | Commands that should be called before this one (metadata only) |
362
+ | `errors` | string[] | No | Possible error codes |
363
+
364
+ ### createMcpServer(options)
365
+
366
+ Create an MCP server from commands.
367
+
368
+ | Option | Type | Required | Description |
369
+ |--------|------|----------|-------------|
370
+ | `name` | string | Yes | Server name |
371
+ | `version` | string | Yes | Server version |
372
+ | `commands` | array | Yes | Command definitions |
373
+ | `transport` | `'stdio' \| 'http' \| 'auto'` | No | Transport protocol (default: `'auto'`) |
374
+ | `port` | number | No | Port for HTTP transport (default: 3100) |
375
+ | `host` | string | No | Host for HTTP transport (default: localhost) |
376
+ | `devMode` | boolean | No | Enable development mode (default: false) |
377
+ | `cors` | boolean | No | Enable CORS for HTTP transport (default: follows devMode) |
378
+ | `middleware` | array | No | Middleware functions |
379
+ | `onCommand` | function | No | Command execution callback |
380
+ | `onError` | function | No | Error callback |
381
+
382
+ ### defaultMiddleware(options?)
383
+
384
+ Returns a pre-configured `CommandMiddleware[]` with trace ID generation, logging, and timing.
385
+
386
+ | Option | Type | Default | Description |
387
+ |--------|------|---------|-------------|
388
+ | `logging` | `LoggingOptions \| false` | enabled | Structured logging config, or `false` to disable |
389
+ | `timing` | `TimingOptions \| false` | enabled (1000ms) | Slow-command warning config, or `false` to disable |
390
+ | `traceId` | `TraceIdOptions \| false` | enabled (UUID) | Trace ID auto-generation config, or `false` to disable |
391
+
392
+ ### Server Methods
393
+
394
+ | Method | Description |
395
+ |--------|-------------|
396
+ | `start()` | Start the server |
397
+ | `stop()` | Stop the server |
398
+ | `getUrl()` | Get server URL (`"stdio://"` for stdio transport) |
399
+ | `getTransport()` | Get the resolved transport mode (`"stdio"` or `"http"`) |
400
+ | `getCommands()` | Get registered commands |
401
+ | `execute(name, input, context)` | Execute command directly |
402
+
403
+ ## HTTP Endpoints
404
+
405
+ The server exposes these endpoints:
406
+
407
+ | Endpoint | Method | Description |
408
+ |----------|--------|-------------|
409
+ | `/sse` | GET | SSE connection for MCP clients |
410
+ | `/message` | POST | JSON-RPC message endpoint |
411
+ | `/rpc` | POST | Simple JSON-RPC for browser clients |
412
+ | `/health` | GET | Health check |
413
+
414
+ ### Browser-Friendly `/rpc` Endpoint
415
+
416
+ The `/rpc` endpoint provides a simple JSON-RPC interface for browser clients:
417
+
418
+ ```typescript
419
+ // Request format
420
+ {
421
+ method: "command-name", // The command to execute
422
+ params: { ... }, // Input parameters
423
+ id: 1 // Optional request ID
424
+ }
425
+
426
+ // Response format
427
+ {
428
+ jsonrpc: "2.0",
429
+ id: 1,
430
+ result: CommandResult // The AFD CommandResult
431
+ }
432
+ ```
433
+
434
+ ### Browser Example (Vanilla JavaScript)
435
+
436
+ ```javascript
437
+ async function callCommand(method, params) {
438
+ const response = await fetch('http://localhost:3100/rpc', {
439
+ method: 'POST',
440
+ headers: { 'Content-Type': 'application/json' },
441
+ body: JSON.stringify({ method, params, id: Date.now() }),
442
+ });
443
+
444
+ const { result, error } = await response.json();
445
+ if (error) throw new Error(error.message);
446
+ return result;
447
+ }
448
+
449
+ // Usage
450
+ const result = await callCommand('greet', { name: 'World' });
451
+ console.log(result.data.greeting); // "Hello, World!"
452
+ ```
453
+
454
+ ### CORS Configuration
455
+
456
+ CORS is enabled by default for HTTP transport. Configure it in server options:
457
+
458
+ ```typescript
459
+ const server = createMcpServer({
460
+ name: 'my-server',
461
+ version: '1.0.0',
462
+ commands: [greet],
463
+ transport: 'http',
464
+ port: 3100,
465
+ cors: true, // Enable CORS (default: true)
466
+ devMode: true, // Development mode enables permissive CORS
467
+ });
468
+ ```
469
+
470
+ ## Related
471
+
472
+ - [@lushly-dev/afd-core](../core) - Core types and helpers
473
+ - [@lushly-dev/afd-client](../client) - MCP client library
474
+ - [@lushly-dev/afd-cli](../cli) - Command-line interface
475
+ - [Example: Todo App](../examples/todo/) - Complete working example