advisers 0.2.0-preview.71 → 0.2.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.
@@ -0,0 +1,869 @@
1
+ /**
2
+ * Advisers MCP server (JSON-RPC 2.0 over stdio, protocol '2024-11-05').
3
+ *
4
+ * This module is the testable library extracted from the MCP section of
5
+ * 'bin/advisers.js'. The binary owns process wiring (home, audit key, sqlite);
6
+ * this module owns the protocol surface and never touches the network.
7
+ *
8
+ * Surface (0.2.0):
9
+ * - 5 read-only tools: today / commit_ls / who / evidence / remind
10
+ * - 2 whitelisted writes:
11
+ * advisers_capture_candidate -> creates a PENDING memory candidate only.
12
+ * It never accepts a candidate and never writes the ledger; a human must
13
+ * run 'advisers memory accept <id>' afterwards.
14
+ * advisers_pack_verify -> read-only verification of an evidence-pack
15
+ * receipt directory (manifest.json / README.txt / SHA256SUMS [+ receipt.docx]).
16
+ * - 4 read-only resources: today / commitments / who / evidence (JSON).
17
+ *
18
+ * Invariants:
19
+ * - No absolute paths and no raw input (tool arguments, quotes, filesystem
20
+ * paths) are echoed in error messages.
21
+ * - Every 'tools/call' is audited through the injected 'audit' callback
22
+ * ({actor, action, allowed, reason}). A write that cannot be audited fails
23
+ * closed: a created candidate is rejected and the call returns an error.
24
+ * - One JSON-RPC request per line, UTF-8, hard cap 1 MiB per line.
25
+ */
26
+
27
+ import { lstatSync, readFileSync, readdirSync, statSync } from 'node:fs'
28
+ import { join, resolve } from 'node:path'
29
+ import { StringDecoder } from 'node:string_decoder'
30
+ import { evidenceForCommitment, evidenceForFact, evidenceForPreference, verifyPack } from './evidence.js'
31
+ import { buildReminders } from './remind.js'
32
+ import { inspectCaptureText } from './capture.js'
33
+ import { classify, redact, safetyErrorFrom } from './safety/index.js'
34
+
35
+ export const PROTOCOL_VERSION = '2024-11-05'
36
+ export const SERVER_NAME = 'advisers'
37
+ /** Hard cap for one stdio JSON-RPC line (bytes). */
38
+ export const MAX_LINE_BYTES = 1024 * 1024
39
+ /** Receipt directories are small; refuse to slurp anything huge. */
40
+ export const MAX_PACK_FILE_BYTES = 512 * 1024
41
+ export const MAX_PACK_SUMS_BYTES = 64 * 1024
42
+
43
+ // Content-safety wiring (docs/CONTENT-SAFETY.md section 8): tools/call argument
44
+ // text and returned text are classified with the mcp.tool surface. A block-level
45
+ // call returns a structured CONTENT_BLOCKED tool error (isError true) instead of
46
+ // crashing the JSON-RPC server; blocked writes never reach the store because the
47
+ // capture gate runs inside advisers_capture_candidate before proposeCandidate.
48
+ const MCP_SURFACE = 'mcp.tool'
49
+
50
+ export const TOOL_NAMES = Object.freeze([
51
+ 'advisers_today',
52
+ 'advisers_commit_ls',
53
+ 'advisers_who',
54
+ 'advisers_evidence',
55
+ 'advisers_remind',
56
+ 'advisers_capture_candidate',
57
+ 'advisers_pack_verify',
58
+ ])
59
+
60
+ export const RESOURCE_URIS = Object.freeze([
61
+ 'advisers://today',
62
+ 'advisers://commitments',
63
+ 'advisers://who',
64
+ 'advisers://evidence',
65
+ ])
66
+
67
+ const RESOURCE_DEFINITIONS = Object.freeze([
68
+ {
69
+ uri: 'advisers://today',
70
+ name: 'today',
71
+ description: 'Open commitments and their count (same shape as advisers_today).',
72
+ mimeType: 'application/json',
73
+ },
74
+ {
75
+ uri: 'advisers://commitments',
76
+ name: 'commitments',
77
+ description: 'All commitments (open and closed) as compact rows.',
78
+ mimeType: 'application/json',
79
+ },
80
+ {
81
+ uri: 'advisers://who',
82
+ name: 'who',
83
+ description: 'Who owes whom: mine (user/agent) vs waiting (third parties).',
84
+ mimeType: 'application/json',
85
+ },
86
+ {
87
+ uri: 'advisers://evidence',
88
+ name: 'evidence',
89
+ description: 'Evidence traceback index for commitments, facts and preferences (counts only).',
90
+ mimeType: 'application/json',
91
+ },
92
+ ])
93
+
94
+ const READ_ONLY_ANNOTATIONS = Object.freeze({
95
+ readOnlyHint: true,
96
+ destructiveHint: false,
97
+ idempotentHint: true,
98
+ openWorldHint: false,
99
+ })
100
+
101
+ const WRITE_ANNOTATIONS = Object.freeze({
102
+ readOnlyHint: false,
103
+ destructiveHint: false,
104
+ idempotentHint: false,
105
+ openWorldHint: false,
106
+ })
107
+
108
+ const CAPTURE_TOOL = Object.freeze({
109
+ name: 'advisers_capture_candidate',
110
+ description:
111
+ 'Propose a PENDING commitment candidate captured from a quote. This writes a memory candidate only: it never accepts the candidate and never changes the ledger. A human must review it with "advisers memory candidates" and run "advisers memory accept <id>".',
112
+ inputSchema: {
113
+ type: 'object',
114
+ properties: {
115
+ action: { type: 'string', minLength: 1, maxLength: 500, description: 'What must be done (verbatim or near-verbatim).' },
116
+ quote: { type: 'string', minLength: 1, maxLength: 2000, description: 'The verbatim source text this candidate was captured from.' },
117
+ debtor: { type: 'string', enum: ['user', 'agent', 'third'], description: 'Who owes the action. Defaults to user.' },
118
+ creditor: { type: 'string', maxLength: 200, description: 'Who is owed the action. Defaults to someone.' },
119
+ dueAt: { type: 'string', maxLength: 64, description: 'ISO 8601 due date-time, e.g. 2026-12-01T10:00:00+08:00.' },
120
+ matterId: { type: 'string', maxLength: 120, description: 'Existing matter id. Defaults to the first active matter.' },
121
+ },
122
+ required: ['action', 'quote'],
123
+ additionalProperties: false,
124
+ },
125
+ annotations: WRITE_ANNOTATIONS,
126
+ write: true,
127
+ })
128
+
129
+ const PACK_VERIFY_TOOL = Object.freeze({
130
+ name: 'advisers_pack_verify',
131
+ description:
132
+ 'Read-only verification of an evidence-pack receipt directory: recomputes SHA256SUMS for manifest.json and README.txt, rejects unsafe or unhashed pack files, and reports whether a receipt.docx is present. Never modifies the directory. The directory path is not echoed in errors.',
133
+ inputSchema: {
134
+ type: 'object',
135
+ properties: {
136
+ dir: { type: 'string', minLength: 1, maxLength: 4096, description: 'Directory written by "advisers deliveries --pack" (contains manifest.json, README.txt, SHA256SUMS, optionally receipt.docx).' },
137
+ },
138
+ required: ['dir'],
139
+ additionalProperties: false,
140
+ },
141
+ // Read-only in effect: it never writes to the receipt directory.
142
+ annotations: READ_ONLY_ANNOTATIONS,
143
+ write: false,
144
+ })
145
+
146
+ /* -------------------------------------------------------------------------- */
147
+ /* errors */
148
+ /* -------------------------------------------------------------------------- */
149
+
150
+ class RpcError extends Error {
151
+ constructor(code, message) {
152
+ super(message)
153
+ this.name = 'RpcError'
154
+ this.code = code
155
+ }
156
+ }
157
+
158
+ /** A controlled execution failure; its message is safe to return verbatim. */
159
+ class ToolError extends Error {
160
+ constructor(message) {
161
+ super(message)
162
+ this.name = 'ToolError'
163
+ }
164
+ }
165
+
166
+ function invalidParams(message) {
167
+ return new RpcError(-32602, message)
168
+ }
169
+
170
+ /** JSON text for classification only; never echoes raw input in errors. */
171
+ function safeJson(value) {
172
+ try {
173
+ return JSON.stringify(value ?? {})
174
+ } catch {
175
+ return ''
176
+ }
177
+ }
178
+
179
+ /** Structured CONTENT_BLOCKED tool result: isError=true, no original text. */
180
+ function toolBlocked(id, error) {
181
+ const payload = {
182
+ ok: false,
183
+ error: {
184
+ code: 'CONTENT_BLOCKED',
185
+ message: error.message,
186
+ action: error.action,
187
+ surface: error.surface,
188
+ ruleIds: Array.isArray(error.ruleIds) ? error.ruleIds : [],
189
+ rulesetVersion: error.rulesetVersion,
190
+ auditReason: error.auditReason,
191
+ },
192
+ }
193
+ return { jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }], isError: true } }
194
+ }
195
+
196
+ /* -------------------------------------------------------------------------- */
197
+ /* argument validation (messages are fixed strings; raw values are not echoed) */
198
+ /* -------------------------------------------------------------------------- */
199
+
200
+ const SAFE_TOKEN = /^[A-Za-z][A-Za-z0-9_]{0,40}$/
201
+
202
+ function sanitizeToken(value) {
203
+ return typeof value === 'string' && SAFE_TOKEN.test(value) ? value : 'argument'
204
+ }
205
+
206
+ function assertAllowedKeys(args, allowed) {
207
+ for (const key of Object.keys(args)) {
208
+ if (!allowed.includes(key)) throw invalidParams('unexpected argument')
209
+ }
210
+ }
211
+
212
+ function requireString(args, key, { min = 1, max = 500 } = {}) {
213
+ const value = args[key]
214
+ if (typeof value !== 'string') throw invalidParams(key + ' must be a string')
215
+ const text = value.trim()
216
+ if (text.length < min) throw invalidParams(key + ' must not be empty')
217
+ if (text.length > max) throw invalidParams(key + ' is too long')
218
+ return text
219
+ }
220
+
221
+ function optionalString(args, key, { max = 200 } = {}) {
222
+ const value = args[key]
223
+ if (value === undefined || value === null) return undefined
224
+ if (typeof value !== 'string') throw invalidParams(key + ' must be a string')
225
+ const text = value.trim()
226
+ if (!text) return undefined
227
+ if (text.length > max) throw invalidParams(key + ' is too long')
228
+ return text
229
+ }
230
+
231
+ function optionalEnum(args, key, allowed, fallback) {
232
+ const text = optionalString(args, key, { max: 40 })
233
+ if (text === undefined) return fallback
234
+ if (!allowed.includes(text)) throw invalidParams(key + ' must be one of ' + allowed.join(', '))
235
+ return text
236
+ }
237
+
238
+ function optionalBoolean(args, key) {
239
+ const value = args[key]
240
+ if (value === undefined) return false
241
+ if (typeof value !== 'boolean') throw invalidParams(key + ' must be a boolean')
242
+ return value
243
+ }
244
+
245
+ const ISO_DATE_TIME = /^\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d{1,3})?)?(?:Z|[+-]\d{2}:?\d{2})?)?$/
246
+
247
+ function optionalIsoDate(args, key) {
248
+ const text = optionalString(args, key, { max: 64 })
249
+ if (text === undefined) return undefined
250
+ if (!ISO_DATE_TIME.test(text) || Number.isNaN(Date.parse(text))) throw invalidParams(key + ' must be an ISO 8601 date-time')
251
+ return text
252
+ }
253
+
254
+ function paramsObject(params) {
255
+ if (params === undefined || params === null) return {}
256
+ if (typeof params !== 'object' || Array.isArray(params)) throw invalidParams('params must be an object')
257
+ return params
258
+ }
259
+
260
+ /* -------------------------------------------------------------------------- */
261
+ /* receipt-directory reader (read-only, fail-closed, no path leaks) */
262
+ /* -------------------------------------------------------------------------- */
263
+
264
+ function isSafePackName(name) {
265
+ if (typeof name !== 'string' || !name || name.length > 128) return false
266
+ if (/[\u0000-\u001f\u007f]/.test(name)) return false
267
+ if (name === '.' || name === '..') return false
268
+ if (name.includes('/') || name.includes('\\')) return false
269
+ if (/^[A-Za-z]:/.test(name)) return false
270
+ if (!/^[A-Za-z0-9._-]+$/.test(name)) return false
271
+ return true
272
+ }
273
+
274
+ function listedPackNames(sumsText) {
275
+ const names = new Set()
276
+ for (const raw of String(sumsText).split(/\r?\n/)) {
277
+ const line = raw.trim()
278
+ if (!line) continue
279
+ const match = /^([0-9a-fA-F]{64})\s+\*?(.+)$/.exec(line)
280
+ if (!match) continue
281
+ const name = match[2].trim()
282
+ if (isSafePackName(name) && name !== 'SHA256SUMS') names.add(name)
283
+ }
284
+ return names
285
+ }
286
+
287
+ function readPackFile(dir, name, maxBytes) {
288
+ if (!isSafePackName(name)) return undefined
289
+ const path = join(dir, name)
290
+ // Defense in depth: a safe basename must still resolve inside the directory.
291
+ if (resolve(path) !== resolve(dir, name)) return undefined
292
+ let stat
293
+ try {
294
+ stat = lstatSync(path)
295
+ } catch {
296
+ return undefined
297
+ }
298
+ if (stat.isSymbolicLink()) throw new ToolError('pack files must be regular files')
299
+ if (!stat.isFile()) return undefined
300
+ if (stat.size > maxBytes) throw new ToolError('pack file exceeds the size limit')
301
+ try {
302
+ return readFileSync(path, 'utf8')
303
+ } catch {
304
+ return undefined
305
+ }
306
+ }
307
+
308
+ /**
309
+ * Read the pack files of a receipt directory. Only known pack names and names
310
+ * listed inside SHA256SUMS are read; a receipt.docx is reported by presence,
311
+ * never parsed. Errors are generic (no absolute paths).
312
+ *
313
+ * @returns {{files: Record<string,string>, receiptPresent: boolean, extraFileCount: number}}
314
+ */
315
+ export function readReceiptDirectory(dir) {
316
+ let stat
317
+ try {
318
+ stat = statSync(dir)
319
+ } catch {
320
+ throw new ToolError('pack directory not found')
321
+ }
322
+ if (!stat.isDirectory()) throw new ToolError('pack directory not found')
323
+
324
+ const files = {}
325
+ const sums = readPackFile(dir, 'SHA256SUMS', MAX_PACK_SUMS_BYTES)
326
+ if (sums !== undefined) files.SHA256SUMS = sums
327
+
328
+ const wanted = new Set(['manifest.json', 'README.txt'])
329
+ if (sums !== undefined) for (const name of listedPackNames(sums)) wanted.add(name)
330
+ for (const name of wanted) {
331
+ const content = readPackFile(dir, name, MAX_PACK_FILE_BYTES)
332
+ if (content !== undefined) files[name] = content
333
+ }
334
+
335
+ let receiptPresent = false
336
+ let extraFileCount = 0
337
+ let entries = []
338
+ try {
339
+ entries = readdirSync(dir, { withFileTypes: true })
340
+ } catch {
341
+ entries = []
342
+ }
343
+ for (const entry of entries) {
344
+ if (!isSafePackName(entry.name)) continue
345
+ if (entry.name === 'receipt.docx') {
346
+ receiptPresent = true
347
+ continue
348
+ }
349
+ if (Object.prototype.hasOwnProperty.call(files, entry.name)) continue
350
+ if (entry.isFile()) extraFileCount += 1
351
+ }
352
+ return { files, receiptPresent, extraFileCount }
353
+ }
354
+
355
+ /* -------------------------------------------------------------------------- */
356
+ /* factory */
357
+ /* -------------------------------------------------------------------------- */
358
+
359
+ /**
360
+ * Create an MCP server handler.
361
+ *
362
+ * @param {object} options
363
+ * @param {object} [options.store] SqliteStore-like object (proposeCandidate, reviewCandidate, getTurn, ...).
364
+ * @param {object} [options.ledger] Core Ledger-like object (openCommitments, listCommitments, ...).
365
+ * @param {string} [options.version] Server version reported by 'initialize'.
366
+ * @param {Function} [options.audit] Audit sink: ({actor, action, allowed, reason}) => unknown.
367
+ * @param {Function} [options.readPack] Injectable receipt-directory reader returns {files, receiptPresent, extraFileCount}; defaults to readReceiptDirectory.
368
+ * @param {Function|Date} [options.now] Clock used by reminders (defaults to new Date()).
369
+ * @returns {{protocolVersion: string, handle: Function, handleLine: Function, serve: Function, tools: Function, resources: Function}}
370
+ */
371
+ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readPack, now = () => new Date() } = {}) {
372
+ const serverVersion = String(version ?? '0.0.0')
373
+
374
+ function nowDate() {
375
+ const value = typeof now === 'function' ? now() : now
376
+ const date = value instanceof Date ? value : new Date(value)
377
+ return Number.isNaN(date.getTime()) ? new Date() : date
378
+ }
379
+
380
+ function requireLedger() {
381
+ if (!ledger || typeof ledger.openCommitments !== 'function' || typeof ledger.listCommitments !== 'function') {
382
+ throw new ToolError('ledger unavailable')
383
+ }
384
+ return ledger
385
+ }
386
+
387
+ function requireStore() {
388
+ if (!store || typeof store.proposeCandidate !== 'function') throw new ToolError('candidate store unavailable')
389
+ return store
390
+ }
391
+
392
+ /* ------------------------------ read models ------------------------------ */
393
+
394
+ function todayData() {
395
+ const open = requireLedger().openCommitments()
396
+ return {
397
+ open: open.length,
398
+ commitments: open.map((c) => ({ id: c.id, debtor: c.debtor, creditor: c.creditor, action: c.action, dueAt: c.dueAt })),
399
+ }
400
+ }
401
+
402
+ function commitRows(all) {
403
+ return requireLedger()
404
+ .listCommitments()
405
+ .filter((c) => all || c.status === 'open')
406
+ .map((c) => ({ id: c.id, status: c.status, action: c.action, dueAt: c.dueAt, creditor: c.creditor }))
407
+ }
408
+
409
+ function whoData() {
410
+ const open = requireLedger().openCommitments()
411
+ return {
412
+ mine: open.filter((c) => c.debtor === 'user' || c.debtor === 'agent'),
413
+ waiting: open.filter((c) => c.debtor === 'third' || String(c.debtor).startsWith('third:')),
414
+ }
415
+ }
416
+
417
+ function remindData() {
418
+ try {
419
+ return buildReminders(requireLedger(), { now: nowDate() })
420
+ } catch {
421
+ throw new ToolError('reminder planning failed')
422
+ }
423
+ }
424
+
425
+ function evidenceData(id) {
426
+ const ledgerApi = requireLedger()
427
+ if (id.startsWith('cm_')) return evidenceForCommitment(store, ledgerApi, id)
428
+ if (id.startsWith('fact_')) return evidenceForFact(store, ledgerApi, id)
429
+ if (id.startsWith('pref_')) return evidenceForPreference(store, ledgerApi, id)
430
+ throw new ToolError('unknown evidence id prefix (want cm_/fact_/pref_)')
431
+ }
432
+
433
+ function evidenceIndex() {
434
+ const ledgerApi = requireLedger()
435
+ const limit = 50
436
+ const summarize = (kind, id, result) => ({
437
+ kind,
438
+ id,
439
+ found: Boolean(result?.[kind]),
440
+ sources: Array.isArray(result?.sources) ? result.sources.length : 0,
441
+ missing: Array.isArray(result?.missing) ? result.missing.length : 0,
442
+ })
443
+ const commitments = ledgerApi
444
+ .listCommitments()
445
+ .slice(0, limit)
446
+ .map((c) => summarize('commitment', c.id, evidenceForCommitment(store, ledgerApi, c.id)))
447
+ const facts = (typeof ledgerApi.listFacts === 'function' ? ledgerApi.listFacts() : [])
448
+ .slice(0, limit)
449
+ .map((f) => summarize('fact', f.id, evidenceForFact(store, ledgerApi, f.id)))
450
+ const preferences = (typeof ledgerApi.listPreferences === 'function' ? ledgerApi.listPreferences({ includeCandidates: false }) : [])
451
+ .slice(0, limit)
452
+ .map((p) => summarize('preference', p.id, evidenceForPreference(store, ledgerApi, p.id)))
453
+ return { limits: { perKind: limit }, commitments, facts, preferences }
454
+ }
455
+
456
+ /* ------------------------------ write tools ------------------------------ */
457
+
458
+ function captureCandidate(args) {
459
+ assertAllowedKeys(args, ['action', 'quote', 'debtor', 'creditor', 'dueAt', 'matterId'])
460
+ const action = requireString(args, 'action', { min: 1, max: 500 })
461
+ const quote = requireString(args, 'quote', { min: 1, max: 2000 })
462
+ // Reuse the capture gate (same surface/policy as lib/capture.js): a blocked
463
+ // write never creates a candidate; PII is redacted from the payload only.
464
+ // The quote stays verbatim (it is the stored evidence text).
465
+ inspectCaptureText([action, quote].join('\n'), { surface: 'capture.input' })
466
+ const debtor = optionalEnum(args, 'debtor', ['user', 'agent', 'third'], 'user')
467
+ const creditor = optionalString(args, 'creditor', { max: 200 }) ?? 'someone'
468
+ const dueAt = optionalIsoDate(args, 'dueAt')
469
+ let matterId = optionalString(args, 'matterId', { max: 120 })
470
+ if (matterId !== undefined) {
471
+ if (typeof ledger?.getMatter !== 'function' || !ledger.getMatter(matterId)) throw invalidParams('unknown matter id')
472
+ } else {
473
+ matterId = typeof ledger?.listMatters === 'function' ? ledger.listMatters()[0]?.id : undefined
474
+ }
475
+
476
+ const payload = { debtor, creditor: redact(creditor).text, action: redact(action).text, capability: 'none' }
477
+ if (matterId !== undefined) payload.matterId = matterId
478
+ if (dueAt !== undefined) payload.dueAt = dueAt
479
+
480
+ const storeApi = requireStore()
481
+ let candidate
482
+ try {
483
+ candidate = storeApi.proposeCandidate({ kind: 'commitment', payload, evidence: [{ quote }] })
484
+ } catch {
485
+ throw new ToolError('candidate store rejected the write')
486
+ }
487
+ if (!candidate || typeof candidate.id !== 'string' || !candidate.id) throw new ToolError('candidate store returned no record')
488
+ return {
489
+ ok: true,
490
+ candidate: { id: candidate.id, kind: candidate.kind ?? 'commitment', status: candidate.status ?? 'pending' },
491
+ note: 'Pending candidate only; it is not in the ledger. A human must run "advisers memory accept <id>".',
492
+ }
493
+ }
494
+
495
+ function rollbackCandidate(id) {
496
+ try {
497
+ if (store && typeof store.reviewCandidate === 'function') store.reviewCandidate(id, 'rejected', 'audit_failed')
498
+ } catch {
499
+ // best effort compensation only
500
+ }
501
+ }
502
+
503
+ async function verifyReceipt(args) {
504
+ assertAllowedKeys(args, ['dir'])
505
+ const dir = requireString(args, 'dir', { min: 1, max: 4096 })
506
+ if (/[\u0000-\u001f\u007f]/.test(dir)) throw invalidParams('dir is invalid')
507
+ const reader = typeof readPack === 'function' ? readPack : readReceiptDirectory
508
+ let pack
509
+ try {
510
+ pack = await reader(dir)
511
+ } catch (error) {
512
+ if (error instanceof ToolError) throw error
513
+ throw new ToolError('pack directory is unreadable')
514
+ }
515
+ if (!pack || typeof pack !== 'object' || Array.isArray(pack) || !pack.files || typeof pack.files !== 'object' || Array.isArray(pack.files)) {
516
+ throw new ToolError('pack directory is unreadable')
517
+ }
518
+ const files = pack.files
519
+ const names = Object.keys(files).filter(isSafePackName)
520
+ const verification = verifyPack(files)
521
+ return {
522
+ ok: verification.ok,
523
+ errors: verification.errors.slice(0, 50),
524
+ files: names.slice(0, 32),
525
+ fileCount: names.length,
526
+ receiptPresent: pack.receiptPresent === true,
527
+ extraFileCount: Number.isInteger(pack.extraFileCount) && pack.extraFileCount >= 0 ? pack.extraFileCount : 0,
528
+ verifiedAt: new Date().toISOString(),
529
+ }
530
+ }
531
+
532
+ /* -------------------------------- tools --------------------------------- */
533
+
534
+ const tools = [
535
+ {
536
+ name: 'advisers_today',
537
+ description: 'Read the open-commitment count and the open commitments (read-only).',
538
+ inputSchema: { type: 'object', properties: {} },
539
+ annotations: READ_ONLY_ANNOTATIONS,
540
+ run: () => todayData(),
541
+ },
542
+ {
543
+ name: 'advisers_commit_ls',
544
+ description: 'List commitments (open by default; pass all=true for every status). Read-only.',
545
+ inputSchema: { type: 'object', properties: { all: { type: 'boolean', description: 'Include done/snoozed/dropped commitments.' } } },
546
+ annotations: READ_ONLY_ANNOTATIONS,
547
+ run: (args) => commitRows(optionalBoolean(args, 'all')),
548
+ },
549
+ {
550
+ name: 'advisers_who',
551
+ description: 'Who owes whom: mine (user/agent) versus waiting (third parties). Read-only.',
552
+ inputSchema: { type: 'object', properties: {} },
553
+ annotations: READ_ONLY_ANNOTATIONS,
554
+ run: () => whoData(),
555
+ },
556
+ {
557
+ name: 'advisers_evidence',
558
+ description: 'Read the source turns for a commitment/fact/preference id. Read-only.',
559
+ inputSchema: {
560
+ type: 'object',
561
+ properties: { id: { type: 'string', description: 'cm_* commitment, fact_* fact, or pref_* preference id.' } },
562
+ required: ['id'],
563
+ },
564
+ annotations: READ_ONLY_ANNOTATIONS,
565
+ run: (args) => evidenceData(requireString(args, 'id', { min: 1, max: 128 })),
566
+ },
567
+ {
568
+ name: 'advisers_remind',
569
+ description: 'Read due reminders (no delivery, no network). Read-only.',
570
+ inputSchema: { type: 'object', properties: {} },
571
+ annotations: READ_ONLY_ANNOTATIONS,
572
+ run: () => remindData(),
573
+ },
574
+ { ...CAPTURE_TOOL, run: (args) => captureCandidate(args) },
575
+ { ...PACK_VERIFY_TOOL, run: (args) => verifyReceipt(args) },
576
+ ].map((tool) => ({ ...tool, write: tool.write === true }))
577
+
578
+ const toolsByName = new Map(tools.map((tool) => [tool.name, tool]))
579
+
580
+ function toolsList() {
581
+ return tools.map(({ name, description, inputSchema, annotations }) => ({ name, description, inputSchema, annotations }))
582
+ }
583
+
584
+ /* ------------------------------- auditing ------------------------------- */
585
+
586
+ function auditEntry(tool, outcome) {
587
+ if (!outcome.ok && outcome.error && outcome.error.name === 'ContentSafetyError') {
588
+ const action = tool.name === 'advisers_capture_candidate'
589
+ ? 'mcp.capture.candidate'
590
+ : tool.name === 'advisers_pack_verify'
591
+ ? 'mcp.pack.verify'
592
+ : 'mcp.call'
593
+ return { actor: 'mcp', action, allowed: false, reason: outcome.error.auditReason || 'CONTENT_BLOCKED' }
594
+ }
595
+ if (tool.name === 'advisers_capture_candidate') {
596
+ return {
597
+ actor: 'mcp',
598
+ action: 'mcp.capture.candidate',
599
+ allowed: outcome.ok,
600
+ reason: outcome.ok ? outcome.data.candidate.id : 'rejected',
601
+ }
602
+ }
603
+ if (tool.name === 'advisers_pack_verify') {
604
+ const data = outcome.ok ? outcome.data : undefined
605
+ return {
606
+ actor: 'mcp',
607
+ action: 'mcp.pack.verify',
608
+ allowed: Boolean(data?.ok),
609
+ reason: data ? data.fileCount + ' files, ' + data.errors.length + ' errors' : 'error',
610
+ }
611
+ }
612
+ return { actor: 'mcp', action: 'mcp.call', allowed: outcome.ok, reason: tool.name }
613
+ }
614
+
615
+ async function recordAudit(entry) {
616
+ if (typeof audit !== 'function') return true
617
+ try {
618
+ await audit(entry)
619
+ return true
620
+ } catch {
621
+ return false
622
+ }
623
+ }
624
+
625
+ /* ------------------------------ dispatcher ------------------------------ */
626
+
627
+ function reply(id, result) {
628
+ return { jsonrpc: '2.0', id, result }
629
+ }
630
+
631
+ function rpcError(id, code, message) {
632
+ return { jsonrpc: '2.0', id, error: { code, message } }
633
+ }
634
+
635
+ function toolResult(id, data) {
636
+ return reply(id, { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }], isError: false })
637
+ }
638
+
639
+ function toolFailure(id, message) {
640
+ return reply(id, { content: [{ type: 'text', text: message }], isError: true })
641
+ }
642
+
643
+ function initializeResult() {
644
+ return {
645
+ protocolVersion: PROTOCOL_VERSION,
646
+ capabilities: {
647
+ tools: { listChanged: false },
648
+ resources: { subscribe: false, listChanged: false },
649
+ },
650
+ serverInfo: { name: SERVER_NAME, version: serverVersion },
651
+ }
652
+ }
653
+
654
+ async function handleToolsCall(id, params) {
655
+ const p = paramsObject(params)
656
+ const name = p.name
657
+ if (typeof name !== 'string' || !name.trim()) throw invalidParams('name must be a non-empty string')
658
+ const args = p.arguments === undefined || p.arguments === null ? {} : p.arguments
659
+ if (typeof args !== 'object' || Array.isArray(args)) throw invalidParams('arguments must be an object')
660
+ const tool = toolsByName.get(name)
661
+ if (!tool) throw invalidParams('unknown tool ' + sanitizeToken(name))
662
+
663
+ // Gate 1: classify argument text before any tool logic runs.
664
+ const argumentSafety = classify(safeJson(args), { surface: MCP_SURFACE })
665
+ if (argumentSafety.action === 'block') {
666
+ const error = safetyErrorFrom(argumentSafety, { surface: MCP_SURFACE })
667
+ await recordAudit(auditEntry(tool, { ok: false, error }))
668
+ return toolBlocked(id, error)
669
+ }
670
+
671
+ let outcome
672
+ try {
673
+ outcome = { ok: true, data: await tool.run(args) }
674
+ } catch (error) {
675
+ outcome = { ok: false, error }
676
+ }
677
+
678
+ // Gate 2: a tool must not relay block-level text (ledger data, receipt
679
+ // metadata, ...). The returned payload is classified before it is sent.
680
+ let blockedData
681
+ if (outcome.ok) {
682
+ const outputSafety = classify(safeJson(outcome.data), { surface: MCP_SURFACE })
683
+ if (outputSafety.action === 'block') {
684
+ blockedData = outcome.data
685
+ outcome = { ok: false, error: safetyErrorFrom(outputSafety, { surface: MCP_SURFACE }) }
686
+ }
687
+ }
688
+ const audited = await recordAudit(auditEntry(tool, outcome))
689
+
690
+ if (!outcome.ok) {
691
+ if (outcome.error instanceof RpcError) {
692
+ throw outcome.error
693
+ }
694
+ if (outcome.error?.name === 'ContentSafetyError') {
695
+ // A write whose returned text was blocked is compensated (no orphan).
696
+ if (tool.name === 'advisers_capture_candidate' && blockedData?.candidate?.id) rollbackCandidate(blockedData.candidate.id)
697
+ return toolBlocked(id, outcome.error)
698
+ }
699
+ if (tool.write && !audited) return toolFailure(id, 'audit chain unavailable; call rejected')
700
+ return toolFailure(id, outcome.error instanceof ToolError ? outcome.error.message : 'tool execution failed')
701
+ }
702
+ if (tool.write && !audited) {
703
+ if (tool.name === 'advisers_capture_candidate' && outcome.data?.candidate?.id) rollbackCandidate(outcome.data.candidate.id)
704
+ return toolFailure(id, 'audit chain unavailable; write rolled back')
705
+ }
706
+ return toolResult(id, outcome.data)
707
+ }
708
+
709
+ async function handleResourcesRead(id, params) {
710
+ const p = paramsObject(params)
711
+ const uri = p.uri
712
+ if (typeof uri !== 'string' || !uri.trim()) throw invalidParams('uri must be a non-empty string')
713
+ if (!RESOURCE_URIS.includes(uri)) return rpcError(id, -32002, 'resource not found')
714
+ let data
715
+ if (uri === 'advisers://today') data = todayData()
716
+ else if (uri === 'advisers://commitments') data = { commitments: commitRows(true) }
717
+ else if (uri === 'advisers://who') data = whoData()
718
+ else data = evidenceIndex()
719
+ await recordAudit({ actor: 'mcp', action: 'mcp.call', allowed: true, reason: 'resource:' + uri })
720
+ return reply(id, { contents: [{ uri, mimeType: 'application/json', text: JSON.stringify(data, null, 2) }] })
721
+ }
722
+
723
+ /**
724
+ * Handle one decoded JSON-RPC message object.
725
+ * @returns {Promise<object|null>} response object, or null for notifications.
726
+ */
727
+ async function handle(message) {
728
+ if (message === null || typeof message !== 'object' || Array.isArray(message)) {
729
+ return rpcError(null, -32600, 'invalid request')
730
+ }
731
+ const hasId = Object.prototype.hasOwnProperty.call(message, 'id') && message.id !== undefined
732
+ const id = hasId ? message.id : undefined
733
+ if (hasId && id !== null && typeof id !== 'number' && typeof id !== 'string') {
734
+ return rpcError(null, -32600, 'invalid request')
735
+ }
736
+ if (message.jsonrpc !== '2.0' || typeof message.method !== 'string') {
737
+ return rpcError(hasId ? id : null, -32600, 'invalid request')
738
+ }
739
+ const method = message.method
740
+
741
+ try {
742
+ if (method === 'initialize') return hasId ? reply(id, initializeResult()) : null
743
+ if (method === 'notifications/initialized') return hasId ? reply(id, {}) : null
744
+ if (method === 'ping') return hasId ? reply(id, {}) : null
745
+ if (method === 'tools/list') {
746
+ paramsObject(message.params)
747
+ return hasId ? reply(id, { tools: toolsList() }) : null
748
+ }
749
+ if (method === 'tools/call') {
750
+ if (!hasId) return null
751
+ return await handleToolsCall(id, message.params)
752
+ }
753
+ if (method === 'resources/list') {
754
+ paramsObject(message.params)
755
+ return hasId ? reply(id, { resources: RESOURCE_DEFINITIONS.map((entry) => ({ ...entry })) }) : null
756
+ }
757
+ if (method === 'resources/read') {
758
+ if (!hasId) return null
759
+ return await handleResourcesRead(id, message.params)
760
+ }
761
+ return hasId ? rpcError(id, -32601, 'unknown method') : null
762
+ } catch (error) {
763
+ if (!hasId) return null
764
+ if (error instanceof RpcError) return rpcError(id, error.code, error.message)
765
+ return rpcError(id, -32603, 'internal error')
766
+ }
767
+ }
768
+
769
+ /**
770
+ * Handle one raw stdio line. Enforces the 1 MiB line cap and never echoes
771
+ * parse/validation failures back as raw text.
772
+ * @returns {Promise<object|null>}
773
+ */
774
+ async function handleLine(line) {
775
+ if (typeof line !== 'string') return rpcError(null, -32600, 'invalid request')
776
+ if (Buffer.byteLength(line, 'utf8') > MAX_LINE_BYTES) {
777
+ return rpcError(null, -32600, 'request exceeds the ' + MAX_LINE_BYTES + ' byte line limit')
778
+ }
779
+ const text = line.trim()
780
+ if (!text) return null
781
+ let message
782
+ try {
783
+ message = JSON.parse(text)
784
+ } catch {
785
+ return rpcError(null, -32700, 'parse error')
786
+ }
787
+ return handle(message)
788
+ }
789
+
790
+ /**
791
+ * Consume newline-delimited JSON-RPC requests from input and write responses
792
+ * to output. Both are Node streams; output is never ended.
793
+ */
794
+ async function serve(input, output) {
795
+ const decoder = new StringDecoder('utf8')
796
+ let buffer = ''
797
+ let bufferBytes = 0
798
+ let discarding = false
799
+
800
+ const writeResponse = (response) => {
801
+ try {
802
+ output.write(JSON.stringify(response) + '\n')
803
+ } catch {
804
+ // A closed stdout means the client went away; keep draining input.
805
+ }
806
+ }
807
+ const resetLine = () => {
808
+ buffer = ''
809
+ bufferBytes = 0
810
+ }
811
+ const oversized = () => {
812
+ discarding = true
813
+ resetLine()
814
+ writeResponse(rpcError(null, -32600, 'request exceeds the ' + MAX_LINE_BYTES + ' byte line limit'))
815
+ }
816
+ const append = (piece) => {
817
+ if (!piece || discarding) return
818
+ bufferBytes += Buffer.byteLength(piece, 'utf8')
819
+ if (bufferBytes > MAX_LINE_BYTES) {
820
+ oversized()
821
+ return
822
+ }
823
+ buffer += piece
824
+ }
825
+ const emitLine = async (line) => {
826
+ try {
827
+ const response = await handleLine(line)
828
+ if (response) writeResponse(response)
829
+ } catch {
830
+ writeResponse(rpcError(null, -32603, 'internal error'))
831
+ }
832
+ }
833
+ const completeLine = async () => {
834
+ if (discarding) {
835
+ discarding = false
836
+ resetLine()
837
+ return
838
+ }
839
+ const line = buffer
840
+ resetLine()
841
+ await emitLine(line)
842
+ }
843
+
844
+ for await (const chunk of input) {
845
+ const text = typeof chunk === 'string' ? chunk : decoder.write(chunk)
846
+ let start = 0
847
+ let index
848
+ while ((index = text.indexOf('\n', start)) !== -1) {
849
+ append(text.slice(start, index))
850
+ await completeLine()
851
+ start = index + 1
852
+ }
853
+ append(text.slice(start))
854
+ }
855
+ append(decoder.end())
856
+ if (!discarding && buffer.trim()) await emitLine(buffer)
857
+ resetLine()
858
+ discarding = false
859
+ }
860
+
861
+ return {
862
+ protocolVersion: PROTOCOL_VERSION,
863
+ handle,
864
+ handleLine,
865
+ serve,
866
+ tools: toolsList,
867
+ resources: () => RESOURCE_DEFINITIONS.map((entry) => ({ ...entry })),
868
+ }
869
+ }