advisers 0.2.2 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +0 -0
- package/NOTICE +0 -0
- package/README-zh.md +11 -7
- package/README.md +16 -8
- package/THIRD-PARTY-NOTICES.md +1 -1
- package/bin/advisers.js +6347 -542
- package/index.js +1 -1
- package/lib/agent.js +529 -80
- package/lib/attachments.js +0 -0
- package/lib/audit-anchor.js +683 -0
- package/lib/backup.js +1345 -0
- package/lib/capture.js +0 -0
- package/lib/context-window.js +0 -0
- package/lib/digest.js +0 -0
- package/lib/doc-review.js +0 -0
- package/lib/egress.js +0 -0
- package/lib/error-codes.js +1373 -0
- package/lib/evidence.js +352 -43
- package/lib/fs-safe.js +347 -0
- package/lib/ical.js +0 -0
- package/lib/imap.js +6 -2
- package/lib/importers.js +0 -0
- package/lib/learning.js +0 -0
- package/lib/ledger-read.js +608 -0
- package/lib/mcp-server.js +331 -50
- package/lib/model.js +73 -1
- package/lib/node-warning-filter.js +15 -0
- package/lib/notify.js +13 -3
- package/lib/nudge.js +0 -0
- package/lib/ocr.js +29 -9
- package/lib/pdf.js +0 -0
- package/lib/pet-brief-store.js +0 -0
- package/lib/pet-brief.js +126 -64
- package/lib/receipt-verify.js +213 -15
- package/lib/relative-date.js +0 -0
- package/lib/remind.js +91 -36
- package/lib/research.js +0 -0
- package/lib/review.js +0 -0
- package/lib/routine.js +0 -0
- package/lib/safety/classifier.js +55 -2
- package/lib/safety/explain.js +0 -0
- package/lib/safety/index.js +0 -0
- package/lib/safety/redact.js +0 -0
- package/lib/safety/rules.js +28 -0
- package/lib/scheduler.js +0 -0
- package/lib/source.js +0 -0
- package/lib/sqlite.js +2302 -55
- package/lib/sync.js +398 -71
- package/lib/text-safe.js +229 -0
- package/lib/timestamp.js +29 -9
- package/lib/tos/index.js +1 -1
- package/lib/tos/manifest.json +6 -6
- package/lib/tos/privacy.zh-CN.md +12 -9
- package/lib/tos/safety.zh-CN.md +4 -3
- package/lib/tos/summary.zh-CN.md +3 -3
- package/lib/tos/terms.zh-CN.md +8 -6
- package/lib/tui/color.js +164 -0
- package/lib/tui/index.js +33 -0
- package/lib/tui/json.js +124 -0
- package/lib/tui/labels.js +50 -0
- package/lib/tui/policy.js +108 -0
- package/lib/tui/render.js +371 -0
- package/lib/tui/sanitize.js +142 -0
- package/lib/tui/text-file.js +116 -0
- package/lib/tui/width.js +577 -0
- package/lib/ui.js +0 -0
- package/lib/undo.js +0 -0
- package/lib/untrusted.js +186 -0
- package/lib/vault.js +0 -0
- package/package.json +6 -5
package/lib/mcp-server.js
CHANGED
|
@@ -27,15 +27,66 @@
|
|
|
27
27
|
import { lstatSync, readFileSync, readdirSync, statSync } from 'node:fs'
|
|
28
28
|
import { join, resolve } from 'node:path'
|
|
29
29
|
import { StringDecoder } from 'node:string_decoder'
|
|
30
|
-
import {
|
|
30
|
+
import {
|
|
31
|
+
evidenceForCommitment,
|
|
32
|
+
evidenceForFact,
|
|
33
|
+
evidenceForPreference,
|
|
34
|
+
isEvidenceRecordAboveClearance,
|
|
35
|
+
verifyPack,
|
|
36
|
+
} from './evidence.js'
|
|
31
37
|
import { buildReminders } from './remind.js'
|
|
32
38
|
import { inspectCaptureText } from './capture.js'
|
|
33
39
|
import { classify, redact, safetyErrorFrom } from './safety/index.js'
|
|
34
40
|
|
|
41
|
+
/**
|
|
42
|
+
* Default MCP protocol version. Legacy clients that send no version (or an
|
|
43
|
+
* unknown one) keep getting 2024-11-05, i.e. the pre-0.3.0 behaviour.
|
|
44
|
+
*/
|
|
35
45
|
export const PROTOCOL_VERSION = '2024-11-05'
|
|
46
|
+
/**
|
|
47
|
+
* Legacy protocol versions negotiated by `initialize` (0.3.0 P0-T3).
|
|
48
|
+
*
|
|
49
|
+
* The 2025-06-18 / 2025-11-25 revisions keep the same initialize/tools/
|
|
50
|
+
* resources lifecycle this server implements, so echoing the client's
|
|
51
|
+
* supported version is safe; anything else (including the stateless
|
|
52
|
+
* 2026-07-28 modern revision, which needs server/discover) falls back to
|
|
53
|
+
* PROTOCOL_VERSION. The modern revisions are NOT implemented here: this
|
|
54
|
+
* server deliberately does not advertise server/discover, so a modern client
|
|
55
|
+
* probes once, gets an unknown-method error, and falls back to initialize.
|
|
56
|
+
*/
|
|
57
|
+
export const SUPPORTED_PROTOCOL_VERSIONS = Object.freeze(['2024-11-05', '2025-06-18', '2025-11-25'])
|
|
36
58
|
export const SERVER_NAME = 'advisers'
|
|
37
59
|
/** Hard cap for one stdio JSON-RPC line (bytes). */
|
|
38
60
|
export const MAX_LINE_BYTES = 1024 * 1024
|
|
61
|
+
/**
|
|
62
|
+
* Output caps for every list-shaped tool result (0.3.0 P0-T3 / S2).
|
|
63
|
+
*
|
|
64
|
+
* The content-safety classifier fail-closes any mcp.tool egress surface above
|
|
65
|
+
* 100k characters (lib/safety/classifier.js MAX_SCAN_CHARS), so an unbounded
|
|
66
|
+
* ledger listing used to turn advisers_today/commit_ls/remind into
|
|
67
|
+
* CONTENT_BLOCKED errors on a large ledger. Every read model now truncates
|
|
68
|
+
* AFTER the per-item clearance filter and BEFORE the classifier runs, and
|
|
69
|
+
* reports the true post-filter count in `total`/`mineTotal`/`waitingTotal`
|
|
70
|
+
* with `truncated: true`. Small ledgers are byte-for-byte unchanged.
|
|
71
|
+
*/
|
|
72
|
+
export const MCP_OUTPUT_LIMITS = Object.freeze({
|
|
73
|
+
todayCommitments: 20,
|
|
74
|
+
commitRows: 50,
|
|
75
|
+
commitRowsMax: 200,
|
|
76
|
+
whoRows: 20,
|
|
77
|
+
reminders: 20,
|
|
78
|
+
evidenceItems: 20,
|
|
79
|
+
})
|
|
80
|
+
/**
|
|
81
|
+
* Last-resort byte budget for one tool/resource payload. The per-tool row caps
|
|
82
|
+
* keep every normal result far below this, but a single commitment with a huge
|
|
83
|
+
* evidence array could still push a list over the classifier's 100k-character
|
|
84
|
+
* fail-closed threshold. When that happens the longest list is halved (and
|
|
85
|
+
* marked truncated) until the serialized payload fits, so the egress
|
|
86
|
+
* classifier never turns a large ledger into CONTENT_BLOCKED.
|
|
87
|
+
*/
|
|
88
|
+
export const MCP_MAX_RESULT_BYTES = 64 * 1024
|
|
89
|
+
const PAYLOAD_LIST_KEYS = Object.freeze(['commitments', 'mine', 'waiting', 'reminders', 'sources', 'missing'])
|
|
39
90
|
/** Receipt directories are small; refuse to slurp anything huge. */
|
|
40
91
|
export const MAX_PACK_FILE_BYTES = 512 * 1024
|
|
41
92
|
export const MAX_PACK_SUMS_BYTES = 64 * 1024
|
|
@@ -68,7 +119,7 @@ const RESOURCE_DEFINITIONS = Object.freeze([
|
|
|
68
119
|
{
|
|
69
120
|
uri: 'advisers://today',
|
|
70
121
|
name: 'today',
|
|
71
|
-
description: 'Open commitments and their count (same shape as advisers_today).',
|
|
122
|
+
description: 'Open commitments and their count (same shape as advisers_today; protected matters excluded at the server clearance).',
|
|
72
123
|
mimeType: 'application/json',
|
|
73
124
|
},
|
|
74
125
|
{
|
|
@@ -176,6 +227,30 @@ function safeJson(value) {
|
|
|
176
227
|
}
|
|
177
228
|
}
|
|
178
229
|
|
|
230
|
+
/**
|
|
231
|
+
* Enforce MCP_MAX_RESULT_BYTES on a list-shaped payload, trimming the longest
|
|
232
|
+
* array until it fits and marking the result truncated (the total fields stay
|
|
233
|
+
* the true post-clearance counts). Non-list payloads are returned unchanged.
|
|
234
|
+
*/
|
|
235
|
+
function boundPayload(data) {
|
|
236
|
+
if (Buffer.byteLength(safeJson(data), 'utf8') <= MCP_MAX_RESULT_BYTES) return data
|
|
237
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) return data
|
|
238
|
+
const trimmed = { ...data }
|
|
239
|
+
for (;;) {
|
|
240
|
+
if (Buffer.byteLength(safeJson(trimmed), 'utf8') <= MCP_MAX_RESULT_BYTES) break
|
|
241
|
+
let target = null
|
|
242
|
+
for (const key of PAYLOAD_LIST_KEYS) {
|
|
243
|
+
const list = trimmed[key]
|
|
244
|
+
if (!Array.isArray(list) || list.length === 0) continue
|
|
245
|
+
if (target === null || list.length > trimmed[target].length) target = key
|
|
246
|
+
}
|
|
247
|
+
if (target === null) break
|
|
248
|
+
trimmed[target] = trimmed[target].slice(0, Math.floor(trimmed[target].length / 2))
|
|
249
|
+
trimmed.truncated = true
|
|
250
|
+
}
|
|
251
|
+
return trimmed
|
|
252
|
+
}
|
|
253
|
+
|
|
179
254
|
/** Structured CONTENT_BLOCKED tool result: isError=true, no original text. */
|
|
180
255
|
function toolBlocked(id, error) {
|
|
181
256
|
const payload = {
|
|
@@ -242,6 +317,16 @@ function optionalBoolean(args, key) {
|
|
|
242
317
|
return value
|
|
243
318
|
}
|
|
244
319
|
|
|
320
|
+
/** Optional 1..max integer row limit (undefined keeps the tool default). */
|
|
321
|
+
function optionalLimit(args, key, max) {
|
|
322
|
+
const value = args[key]
|
|
323
|
+
if (value === undefined || value === null) return undefined
|
|
324
|
+
if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > max) {
|
|
325
|
+
throw invalidParams(key + ' must be an integer between 1 and ' + max)
|
|
326
|
+
}
|
|
327
|
+
return value
|
|
328
|
+
}
|
|
329
|
+
|
|
245
330
|
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
331
|
|
|
247
332
|
function optionalIsoDate(args, key) {
|
|
@@ -366,10 +451,40 @@ export function readReceiptDirectory(dir) {
|
|
|
366
451
|
* @param {Function} [options.audit] Audit sink: ({actor, action, allowed, reason}) => unknown.
|
|
367
452
|
* @param {Function} [options.readPack] Injectable receipt-directory reader returns {files, receiptPresent, extraFileCount}; defaults to readReceiptDirectory.
|
|
368
453
|
* @param {Function|Date} [options.now] Clock used by reminders (defaults to new Date()).
|
|
454
|
+
* @param {number} [options.clearance=0] Read clearance of this MCP surface
|
|
455
|
+
* (0.2.5 A-2). Every read model excludes records whose matter secrecy is
|
|
456
|
+
* above it and reports `protectedExcluded`; 0 (fail closed) is the
|
|
457
|
+
* default and a client cannot raise it through a tool argument.
|
|
369
458
|
* @returns {{protocolVersion: string, handle: Function, handleLine: Function, serve: Function, tools: Function, resources: Function}}
|
|
370
459
|
*/
|
|
371
|
-
export function createMcpServer({ store, ledger, version = '0.0.0', audit, readPack, now = () => new Date() } = {}) {
|
|
460
|
+
export function createMcpServer({ store, ledger, loadLedger, loadStore, version = '0.0.0', audit, readPack, now = () => new Date(), clearance = 0 } = {}) {
|
|
372
461
|
const serverVersion = String(version ?? '0.0.0')
|
|
462
|
+
// Protocol version agreed by the last legacy `initialize` (advisory only:
|
|
463
|
+
// the legacy method surface is identical for every supported revision).
|
|
464
|
+
let negotiatedProtocolVersion = PROTOCOL_VERSION
|
|
465
|
+
// 0.2.5 A-2: clearance is process configuration, never a tool argument. An
|
|
466
|
+
// invalid/negative value falls back to the most restrictive level (0).
|
|
467
|
+
const requestedClearance = Number(clearance)
|
|
468
|
+
const clearanceLevel = Number.isFinite(requestedClearance) && requestedClearance >= 0 ? requestedClearance : 0
|
|
469
|
+
// 0.2.3 P0-2: the CLI wires lazy loaders instead of a preloaded ledger/store so
|
|
470
|
+
// `initialize` stays protocol-only (200k-row ledgers used to cost ~2s before the
|
|
471
|
+
// first response). Anything that needs data resolves it on first use; an
|
|
472
|
+
// explicit ledger/store object (tests, embedders) still wins, and the resolved
|
|
473
|
+
// value is cached per table subset. kind: 'commitments' | 'matters' | 'full'.
|
|
474
|
+
let resolvedLedger = ledger
|
|
475
|
+
let resolvedStore = store
|
|
476
|
+
const ledgerCache = new Map()
|
|
477
|
+
function ledgerFor(kind = 'full') {
|
|
478
|
+
if (resolvedLedger !== undefined) return resolvedLedger
|
|
479
|
+
if (ledgerCache.has(kind)) return ledgerCache.get(kind)
|
|
480
|
+
const loaded = typeof loadLedger === 'function' ? loadLedger(kind) : undefined
|
|
481
|
+
ledgerCache.set(kind, loaded)
|
|
482
|
+
return loaded
|
|
483
|
+
}
|
|
484
|
+
function storeFor() {
|
|
485
|
+
if (resolvedStore === undefined && typeof loadStore === 'function') resolvedStore = loadStore()
|
|
486
|
+
return resolvedStore
|
|
487
|
+
}
|
|
373
488
|
|
|
374
489
|
function nowDate() {
|
|
375
490
|
const value = typeof now === 'function' ? now() : now
|
|
@@ -377,61 +492,181 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
377
492
|
return Number.isNaN(date.getTime()) ? new Date() : date
|
|
378
493
|
}
|
|
379
494
|
|
|
380
|
-
function requireLedger() {
|
|
381
|
-
|
|
495
|
+
function requireLedger(kind = 'full') {
|
|
496
|
+
const ledgerApi = ledgerFor(kind)
|
|
497
|
+
if (!ledgerApi || typeof ledgerApi.openCommitments !== 'function' || typeof ledgerApi.listCommitments !== 'function') {
|
|
382
498
|
throw new ToolError('ledger unavailable')
|
|
383
499
|
}
|
|
384
|
-
return
|
|
500
|
+
return ledgerApi
|
|
385
501
|
}
|
|
386
502
|
|
|
387
503
|
function requireStore() {
|
|
388
|
-
|
|
389
|
-
|
|
504
|
+
const storeApi = storeFor()
|
|
505
|
+
if (!storeApi || typeof storeApi.proposeCandidate !== 'function') throw new ToolError('candidate store unavailable')
|
|
506
|
+
return storeApi
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// 0.2.5 A-2 (MCP clearance): commitments/facts/preferences are judged by the
|
|
510
|
+
// secrecy of their OWN matter. The 'commitments' read path does not need the
|
|
511
|
+
// matters table for anything else, so resolve the small matters table too; with
|
|
512
|
+
// an embedder-provided ledger that has no getMatter we fail closed instead of
|
|
513
|
+
// returning unfiltered data.
|
|
514
|
+
let matterLedger
|
|
515
|
+
function matterSource() {
|
|
516
|
+
if (matterLedger !== undefined) return matterLedger
|
|
517
|
+
const primary = ledgerFor('commitments')
|
|
518
|
+
if (primary && typeof primary.getMatter === 'function') {
|
|
519
|
+
matterLedger = primary
|
|
520
|
+
} else {
|
|
521
|
+
const matters = ledgerFor('matters')
|
|
522
|
+
matterLedger = matters && typeof matters.getMatter === 'function' ? matters : primary ?? matters ?? {}
|
|
523
|
+
}
|
|
524
|
+
return matterLedger
|
|
525
|
+
}
|
|
526
|
+
|
|
527
|
+
/** True when the record's matter secrecy is above this server's clearance. */
|
|
528
|
+
function isHidden(kind, record) {
|
|
529
|
+
if (!record || typeof record !== 'object') return false
|
|
530
|
+
return isEvidenceRecordAboveClearance(matterSource(), kind, record, clearanceLevel)
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
/** Split a list into visible rows and the withheld count (never a row). */
|
|
534
|
+
function splitByClearance(kind, rows) {
|
|
535
|
+
const visible = []
|
|
536
|
+
let protectedExcluded = 0
|
|
537
|
+
for (const row of rows) {
|
|
538
|
+
if (isHidden(kind, row)) protectedExcluded += 1
|
|
539
|
+
else visible.push(row)
|
|
540
|
+
}
|
|
541
|
+
return { visible, protectedExcluded }
|
|
390
542
|
}
|
|
391
543
|
|
|
392
544
|
/* ------------------------------ read models ------------------------------ */
|
|
393
545
|
|
|
394
546
|
function todayData() {
|
|
395
|
-
const open = requireLedger().openCommitments()
|
|
547
|
+
const open = requireLedger('commitments').openCommitments()
|
|
548
|
+
const view = splitByClearance('commitment', open)
|
|
549
|
+
// Cap AFTER clearance and BEFORE the egress classifier: `open` and `total`
|
|
550
|
+
// stay the true post-filter count, `truncated` says rows were withheld.
|
|
551
|
+
const commitments = view.visible.slice(0, MCP_OUTPUT_LIMITS.todayCommitments)
|
|
396
552
|
return {
|
|
397
|
-
open:
|
|
398
|
-
commitments:
|
|
553
|
+
open: view.visible.length,
|
|
554
|
+
commitments: commitments.map((c) => ({ id: c.id, debtor: c.debtor, creditor: c.creditor, action: c.action, dueAt: c.dueAt })),
|
|
555
|
+
clearance: clearanceLevel,
|
|
556
|
+
protectedExcluded: view.protectedExcluded,
|
|
557
|
+
total: view.visible.length,
|
|
558
|
+
truncated: view.visible.length > commitments.length,
|
|
399
559
|
}
|
|
400
560
|
}
|
|
401
561
|
|
|
402
|
-
function
|
|
403
|
-
|
|
562
|
+
function commitListData(all, requestedLimit) {
|
|
563
|
+
const rows = requireLedger('commitments')
|
|
404
564
|
.listCommitments()
|
|
405
565
|
.filter((c) => all || c.status === 'open')
|
|
406
|
-
|
|
566
|
+
const view = splitByClearance('commitment', rows)
|
|
567
|
+
const limit = Number.isInteger(requestedLimit) ? requestedLimit : MCP_OUTPUT_LIMITS.commitRows
|
|
568
|
+
const commitments = view.visible.slice(0, limit)
|
|
569
|
+
return {
|
|
570
|
+
commitments: commitments.map((c) => ({ id: c.id, status: c.status, action: c.action, dueAt: c.dueAt, creditor: c.creditor })),
|
|
571
|
+
clearance: clearanceLevel,
|
|
572
|
+
protectedExcluded: view.protectedExcluded,
|
|
573
|
+
total: view.visible.length,
|
|
574
|
+
truncated: view.visible.length > commitments.length,
|
|
575
|
+
limit,
|
|
576
|
+
}
|
|
407
577
|
}
|
|
408
578
|
|
|
409
579
|
function whoData() {
|
|
410
|
-
const open = requireLedger().openCommitments()
|
|
580
|
+
const open = requireLedger('commitments').openCommitments()
|
|
581
|
+
const view = splitByClearance('commitment', open)
|
|
582
|
+
const mine = view.visible.filter((c) => c.debtor === 'user' || c.debtor === 'agent')
|
|
583
|
+
const waiting = view.visible.filter((c) => c.debtor === 'third' || String(c.debtor).startsWith('third:'))
|
|
584
|
+
const limit = MCP_OUTPUT_LIMITS.whoRows
|
|
411
585
|
return {
|
|
412
|
-
mine:
|
|
413
|
-
waiting:
|
|
586
|
+
mine: mine.slice(0, limit),
|
|
587
|
+
waiting: waiting.slice(0, limit),
|
|
588
|
+
clearance: clearanceLevel,
|
|
589
|
+
protectedExcluded: view.protectedExcluded,
|
|
590
|
+
mineTotal: mine.length,
|
|
591
|
+
waitingTotal: waiting.length,
|
|
592
|
+
truncated: mine.length > limit || waiting.length > limit,
|
|
414
593
|
}
|
|
415
594
|
}
|
|
416
595
|
|
|
417
596
|
function remindData() {
|
|
597
|
+
const ledgerApi = requireLedger('commitments')
|
|
598
|
+
let reminders
|
|
418
599
|
try {
|
|
419
|
-
|
|
600
|
+
reminders = buildReminders(ledgerApi, { now: nowDate() })
|
|
420
601
|
} catch {
|
|
421
602
|
throw new ToolError('reminder planning failed')
|
|
422
603
|
}
|
|
604
|
+
let rows
|
|
605
|
+
try {
|
|
606
|
+
rows = ledgerApi.listCommitments()
|
|
607
|
+
} catch {
|
|
608
|
+
rows = []
|
|
609
|
+
}
|
|
610
|
+
const hiddenIds = new Set()
|
|
611
|
+
for (const row of rows) if (isHidden('commitment', row)) hiddenIds.add(row.id)
|
|
612
|
+
const visible = []
|
|
613
|
+
let protectedExcluded = 0
|
|
614
|
+
for (const reminder of reminders) {
|
|
615
|
+
if (hiddenIds.has(reminder.commitmentId)) protectedExcluded += 1
|
|
616
|
+
else visible.push(reminder)
|
|
617
|
+
}
|
|
618
|
+
const capped = visible.slice(0, MCP_OUTPUT_LIMITS.reminders)
|
|
619
|
+
return {
|
|
620
|
+
reminders: capped,
|
|
621
|
+
clearance: clearanceLevel,
|
|
622
|
+
protectedExcluded,
|
|
623
|
+
total: visible.length,
|
|
624
|
+
truncated: visible.length > capped.length,
|
|
625
|
+
}
|
|
423
626
|
}
|
|
424
627
|
|
|
425
628
|
function evidenceData(id) {
|
|
426
|
-
const ledgerApi = requireLedger()
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
if (
|
|
430
|
-
|
|
629
|
+
const ledgerApi = requireLedger('full')
|
|
630
|
+
const storeApi = storeFor()
|
|
631
|
+
const kind = id.startsWith('cm_') ? 'commitment' : id.startsWith('fact_') ? 'fact' : id.startsWith('pref_') ? 'preference' : null
|
|
632
|
+
if (!kind) throw new ToolError('unknown evidence id prefix (want cm_/fact_/pref_)')
|
|
633
|
+
const result =
|
|
634
|
+
kind === 'commitment'
|
|
635
|
+
? evidenceForCommitment(storeApi, ledgerApi, id)
|
|
636
|
+
: kind === 'fact'
|
|
637
|
+
? evidenceForFact(storeApi, ledgerApi, id)
|
|
638
|
+
: evidenceForPreference(storeApi, ledgerApi, id)
|
|
639
|
+
if (result?.[kind] && isHidden(kind, result[kind])) {
|
|
640
|
+
// Excluded, never partially returned: no creditor/action/quote/missing
|
|
641
|
+
// rows from a protected record may reach the client.
|
|
642
|
+
return {
|
|
643
|
+
schemaVersion: 2,
|
|
644
|
+
clearance: clearanceLevel,
|
|
645
|
+
protectedExcluded: 1,
|
|
646
|
+
sources: [],
|
|
647
|
+
missing: [],
|
|
648
|
+
note: 'record belongs to a protected matter (secrecy above MCP clearance); content withheld',
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
// Same cap contract as the list tools: after clearance, before the
|
|
652
|
+
// classifier; totals describe the untruncated lists.
|
|
653
|
+
const sources = Array.isArray(result.sources) ? result.sources : []
|
|
654
|
+
const missing = Array.isArray(result.missing) ? result.missing : []
|
|
655
|
+
return {
|
|
656
|
+
...result,
|
|
657
|
+
sources: sources.slice(0, MCP_OUTPUT_LIMITS.evidenceItems),
|
|
658
|
+
missing: missing.slice(0, MCP_OUTPUT_LIMITS.evidenceItems),
|
|
659
|
+
clearance: clearanceLevel,
|
|
660
|
+
protectedExcluded: 0,
|
|
661
|
+
sourcesTotal: sources.length,
|
|
662
|
+
missingTotal: missing.length,
|
|
663
|
+
truncated: sources.length > MCP_OUTPUT_LIMITS.evidenceItems || missing.length > MCP_OUTPUT_LIMITS.evidenceItems,
|
|
664
|
+
}
|
|
431
665
|
}
|
|
432
666
|
|
|
433
667
|
function evidenceIndex() {
|
|
434
|
-
const ledgerApi = requireLedger()
|
|
668
|
+
const ledgerApi = requireLedger('full')
|
|
669
|
+
const storeApi = storeFor()
|
|
435
670
|
const limit = 50
|
|
436
671
|
const summarize = (kind, id, result) => ({
|
|
437
672
|
kind,
|
|
@@ -440,17 +675,29 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
440
675
|
sources: Array.isArray(result?.sources) ? result.sources.length : 0,
|
|
441
676
|
missing: Array.isArray(result?.missing) ? result.missing.length : 0,
|
|
442
677
|
})
|
|
443
|
-
const commitments = ledgerApi
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
.
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
678
|
+
const commitments = splitByClearance('commitment', ledgerApi.listCommitments())
|
|
679
|
+
const facts = splitByClearance(
|
|
680
|
+
'fact',
|
|
681
|
+
typeof ledgerApi.listFacts === 'function' ? ledgerApi.listFacts() : [],
|
|
682
|
+
)
|
|
683
|
+
const preferences = splitByClearance(
|
|
684
|
+
'preference',
|
|
685
|
+
typeof ledgerApi.listPreferences === 'function' ? ledgerApi.listPreferences({ includeCandidates: false }) : [],
|
|
686
|
+
)
|
|
687
|
+
return {
|
|
688
|
+
limits: { perKind: limit },
|
|
689
|
+
clearance: clearanceLevel,
|
|
690
|
+
protectedExcluded: commitments.protectedExcluded + facts.protectedExcluded + preferences.protectedExcluded,
|
|
691
|
+
commitments: commitments.visible
|
|
692
|
+
.slice(0, limit)
|
|
693
|
+
.map((c) => summarize('commitment', c.id, evidenceForCommitment(storeApi, ledgerApi, c.id))),
|
|
694
|
+
facts: facts.visible
|
|
695
|
+
.slice(0, limit)
|
|
696
|
+
.map((f) => summarize('fact', f.id, evidenceForFact(storeApi, ledgerApi, f.id))),
|
|
697
|
+
preferences: preferences.visible
|
|
698
|
+
.slice(0, limit)
|
|
699
|
+
.map((p) => summarize('preference', p.id, evidenceForPreference(storeApi, ledgerApi, p.id))),
|
|
700
|
+
}
|
|
454
701
|
}
|
|
455
702
|
|
|
456
703
|
/* ------------------------------ write tools ------------------------------ */
|
|
@@ -466,11 +713,12 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
466
713
|
const debtor = optionalEnum(args, 'debtor', ['user', 'agent', 'third'], 'user')
|
|
467
714
|
const creditor = optionalString(args, 'creditor', { max: 200 }) ?? 'someone'
|
|
468
715
|
const dueAt = optionalIsoDate(args, 'dueAt')
|
|
716
|
+
const mattersLedger = ledgerFor('matters')
|
|
469
717
|
let matterId = optionalString(args, 'matterId', { max: 120 })
|
|
470
718
|
if (matterId !== undefined) {
|
|
471
|
-
if (typeof
|
|
719
|
+
if (typeof mattersLedger?.getMatter !== 'function' || !mattersLedger.getMatter(matterId)) throw invalidParams('unknown matter id')
|
|
472
720
|
} else {
|
|
473
|
-
matterId = typeof
|
|
721
|
+
matterId = typeof mattersLedger?.listMatters === 'function' ? mattersLedger.listMatters()[0]?.id : undefined
|
|
474
722
|
}
|
|
475
723
|
|
|
476
724
|
const payload = { debtor, creditor: redact(creditor).text, action: redact(action).text, capability: 'none' }
|
|
@@ -494,7 +742,8 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
494
742
|
|
|
495
743
|
function rollbackCandidate(id) {
|
|
496
744
|
try {
|
|
497
|
-
|
|
745
|
+
const storeApi = storeFor()
|
|
746
|
+
if (storeApi && typeof storeApi.reviewCandidate === 'function') storeApi.reviewCandidate(id, 'rejected', 'audit_failed')
|
|
498
747
|
} catch {
|
|
499
748
|
// best effort compensation only
|
|
500
749
|
}
|
|
@@ -531,31 +780,43 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
531
780
|
|
|
532
781
|
/* -------------------------------- tools --------------------------------- */
|
|
533
782
|
|
|
783
|
+
const CLEARANCE_NOTE =
|
|
784
|
+
'Records belonging to protected matters (matter secrecy above this server clearance, default 0) are excluded and only counted in protectedExcluded.'
|
|
534
785
|
const tools = [
|
|
535
786
|
{
|
|
536
787
|
name: 'advisers_today',
|
|
537
|
-
description: 'Read the open-commitment count and the open commitments (read-only).',
|
|
788
|
+
description: 'Read the open-commitment count and the open commitments (read-only). Returns at most ' + MCP_OUTPUT_LIMITS.todayCommitments + ' commitment rows; `open`/`total` are the true post-clearance count and `truncated` says rows were withheld. ' + CLEARANCE_NOTE,
|
|
538
789
|
inputSchema: { type: 'object', properties: {} },
|
|
539
790
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
540
791
|
run: () => todayData(),
|
|
541
792
|
},
|
|
542
793
|
{
|
|
543
794
|
name: 'advisers_commit_ls',
|
|
544
|
-
description:
|
|
545
|
-
|
|
795
|
+
description:
|
|
796
|
+
'List commitments (open by default; pass all=true for every status). Returns {commitments, total, truncated, limit, clearance, protectedExcluded}; total is the post-clearance row count, so a truncated result is never mistaken for the whole ledger. Read-only. ' +
|
|
797
|
+
CLEARANCE_NOTE,
|
|
798
|
+
inputSchema: {
|
|
799
|
+
type: 'object',
|
|
800
|
+
properties: {
|
|
801
|
+
all: { type: 'boolean', description: 'Include done/snoozed/dropped commitments.' },
|
|
802
|
+
limit: { type: 'integer', minimum: 1, maximum: MCP_OUTPUT_LIMITS.commitRowsMax, description: 'Max rows to return (default ' + MCP_OUTPUT_LIMITS.commitRows + ', max ' + MCP_OUTPUT_LIMITS.commitRowsMax + ').' },
|
|
803
|
+
},
|
|
804
|
+
},
|
|
546
805
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
547
|
-
run: (args) =>
|
|
806
|
+
run: (args) => commitListData(optionalBoolean(args, 'all'), optionalLimit(args, 'limit', MCP_OUTPUT_LIMITS.commitRowsMax)),
|
|
548
807
|
},
|
|
549
808
|
{
|
|
550
809
|
name: 'advisers_who',
|
|
551
|
-
description: 'Who owes whom: mine (user/agent) versus waiting (third parties). Read-only.',
|
|
810
|
+
description: 'Who owes whom: mine (user/agent) versus waiting (third parties). Read-only. Each array is capped at ' + MCP_OUTPUT_LIMITS.whoRows + ' rows; mineTotal/waitingTotal/truncated report the full counts. ' + CLEARANCE_NOTE,
|
|
552
811
|
inputSchema: { type: 'object', properties: {} },
|
|
553
812
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
554
813
|
run: () => whoData(),
|
|
555
814
|
},
|
|
556
815
|
{
|
|
557
816
|
name: 'advisers_evidence',
|
|
558
|
-
description:
|
|
817
|
+
description:
|
|
818
|
+
'Read the source turns for a commitment/fact/preference id. Read-only. ' +
|
|
819
|
+
'Evidence of a protected record is withheld (no id content) and reported as protectedExcluded.',
|
|
559
820
|
inputSchema: {
|
|
560
821
|
type: 'object',
|
|
561
822
|
properties: { id: { type: 'string', description: 'cm_* commitment, fact_* fact, or pref_* preference id.' } },
|
|
@@ -566,7 +827,9 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
566
827
|
},
|
|
567
828
|
{
|
|
568
829
|
name: 'advisers_remind',
|
|
569
|
-
description:
|
|
830
|
+
description:
|
|
831
|
+
'Read due reminders (no delivery, no network). Returns {reminders, total, truncated, clearance, protectedExcluded}; total is the post-clearance reminder count. Read-only. ' +
|
|
832
|
+
CLEARANCE_NOTE,
|
|
570
833
|
inputSchema: { type: 'object', properties: {} },
|
|
571
834
|
annotations: READ_ONLY_ANNOTATIONS,
|
|
572
835
|
run: () => remindData(),
|
|
@@ -640,9 +903,20 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
640
903
|
return reply(id, { content: [{ type: 'text', text: message }], isError: true })
|
|
641
904
|
}
|
|
642
905
|
|
|
643
|
-
|
|
906
|
+
/**
|
|
907
|
+
* Legacy `initialize` result. 0.3.0 P0-T3: echo the client's version when
|
|
908
|
+
* this server implements that legacy revision (2024-11-05 / 2025-06-18 /
|
|
909
|
+
* 2025-11-25); a missing or unknown version keeps the 2024-11-05 default so
|
|
910
|
+
* pre-0.3 clients observe exactly the old behaviour. 2026-07-28 modern is
|
|
911
|
+
* not advertised on purpose (it needs server/discover and stateless
|
|
912
|
+
* per-request `_meta`; see docs/MCP.md).
|
|
913
|
+
*/
|
|
914
|
+
function initializeResult(requestedVersion) {
|
|
915
|
+
const requested = typeof requestedVersion === 'string' ? requestedVersion.trim() : ''
|
|
916
|
+
const negotiated = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : PROTOCOL_VERSION
|
|
917
|
+
negotiatedProtocolVersion = negotiated
|
|
644
918
|
return {
|
|
645
|
-
protocolVersion:
|
|
919
|
+
protocolVersion: negotiated,
|
|
646
920
|
capabilities: {
|
|
647
921
|
tools: { listChanged: false },
|
|
648
922
|
resources: { subscribe: false, listChanged: false },
|
|
@@ -674,6 +948,8 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
674
948
|
} catch (error) {
|
|
675
949
|
outcome = { ok: false, error }
|
|
676
950
|
}
|
|
951
|
+
// 0.3.0 P0-T3: cap the payload BEFORE the egress classifier scans it.
|
|
952
|
+
if (outcome.ok) outcome.data = boundPayload(outcome.data)
|
|
677
953
|
|
|
678
954
|
// Gate 2: a tool must not relay block-level text (ledger data, receipt
|
|
679
955
|
// metadata, ...). The returned payload is classified before it is sent.
|
|
@@ -712,12 +988,14 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
712
988
|
if (typeof uri !== 'string' || !uri.trim()) throw invalidParams('uri must be a non-empty string')
|
|
713
989
|
if (!RESOURCE_URIS.includes(uri)) return rpcError(id, -32002, 'resource not found')
|
|
714
990
|
let data
|
|
991
|
+
// 0.2.5 A-2: resources read the same clearance-filtered models as the tools.
|
|
715
992
|
if (uri === 'advisers://today') data = todayData()
|
|
716
|
-
else if (uri === 'advisers://commitments') data =
|
|
993
|
+
else if (uri === 'advisers://commitments') data = commitListData(true)
|
|
717
994
|
else if (uri === 'advisers://who') data = whoData()
|
|
718
995
|
else data = evidenceIndex()
|
|
719
996
|
await recordAudit({ actor: 'mcp', action: 'mcp.call', allowed: true, reason: 'resource:' + uri })
|
|
720
|
-
|
|
997
|
+
const bounded = boundPayload(data)
|
|
998
|
+
return reply(id, { contents: [{ uri, mimeType: 'application/json', text: JSON.stringify(bounded, null, 2) }] })
|
|
721
999
|
}
|
|
722
1000
|
|
|
723
1001
|
/**
|
|
@@ -739,7 +1017,10 @@ export function createMcpServer({ store, ledger, version = '0.0.0', audit, readP
|
|
|
739
1017
|
const method = message.method
|
|
740
1018
|
|
|
741
1019
|
try {
|
|
742
|
-
if (method === 'initialize')
|
|
1020
|
+
if (method === 'initialize') {
|
|
1021
|
+
const params = paramsObject(message.params)
|
|
1022
|
+
return hasId ? reply(id, initializeResult(params.protocolVersion)) : null
|
|
1023
|
+
}
|
|
743
1024
|
if (method === 'notifications/initialized') return hasId ? reply(id, {}) : null
|
|
744
1025
|
if (method === 'ping') return hasId ? reply(id, {}) : null
|
|
745
1026
|
if (method === 'tools/list') {
|
package/lib/model.js
CHANGED
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
safetyErrorFrom,
|
|
11
11
|
buildAuditReason,
|
|
12
12
|
} from './safety/index.js'
|
|
13
|
+
import { redact } from './safety/redact.js'
|
|
13
14
|
|
|
14
15
|
const RETRY_STATUS = new Set([429, 500, 502, 503, 504])
|
|
15
16
|
const EFFORTS = new Set(['low', 'high', 'max'])
|
|
@@ -50,6 +51,71 @@ const TASK_EFFORT = {
|
|
|
50
51
|
// docs/CONTENT-SAFETY.md section 8.
|
|
51
52
|
// ---------------------------------------------------------------------------
|
|
52
53
|
const SAFETY_SURFACE = 'model.output'
|
|
54
|
+
/** Coarse severity for a warning aggregate (inspectMessages keeps action only). */
|
|
55
|
+
function warningSeverityForAction(action) {
|
|
56
|
+
if (action === 'block' || action === 'confirm') return 'high'
|
|
57
|
+
if (action === 'warn' || action === 'redact') return 'medium'
|
|
58
|
+
return 'none'
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Outbound secret/PII redaction (security audit SEC3-03, 2026-11-18).
|
|
63
|
+
*
|
|
64
|
+
* `redact`-classified strings (single-value PII and credentials) must never
|
|
65
|
+
* leave the machine verbatim. When the pre-flight classification found at
|
|
66
|
+
* least one redact-level hit, the request body is built from a redacted deep
|
|
67
|
+
* copy of the messages; the caller's array and the local ledger originals stay
|
|
68
|
+
* untouched. Redaction is one-way and text-only (no raw value is kept).
|
|
69
|
+
*/
|
|
70
|
+
function redactEgressMessages(messages) {
|
|
71
|
+
const state = { messages, changed: false, count: 0 }
|
|
72
|
+
const kinds = new Set()
|
|
73
|
+
const clean = (value) => {
|
|
74
|
+
const result = redact(value)
|
|
75
|
+
if (!result.redacted) return value
|
|
76
|
+
state.changed = true
|
|
77
|
+
state.count += result.count
|
|
78
|
+
for (const kind of result.kinds) kinds.add(kind)
|
|
79
|
+
return result.text
|
|
80
|
+
}
|
|
81
|
+
if (!messages.some((message) => message && typeof message === 'object' && hasRedactableText(message))) return null
|
|
82
|
+
const next = messages.map((message) => {
|
|
83
|
+
if (!message || typeof message !== 'object') return message
|
|
84
|
+
const copy = { ...message }
|
|
85
|
+
if (typeof message.content === 'string') copy.content = clean(message.content)
|
|
86
|
+
else if (Array.isArray(message.content)) {
|
|
87
|
+
copy.content = message.content.map((part) => (part && typeof part === 'object' && typeof part.text === 'string' ? { ...part, text: clean(part.text) } : part))
|
|
88
|
+
}
|
|
89
|
+
if (Array.isArray(message.tool_calls)) {
|
|
90
|
+
copy.tool_calls = message.tool_calls.map((call) => {
|
|
91
|
+
if (!call || typeof call !== 'object' || !call.function || typeof call.function.arguments !== 'string') return call
|
|
92
|
+
return { ...call, function: { ...call.function, arguments: clean(call.function.arguments) } }
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
return copy
|
|
96
|
+
})
|
|
97
|
+
if (!state.changed) return null
|
|
98
|
+
return { messages: next, count: state.count, kinds: [...kinds] }
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function hasRedactableText(message) {
|
|
102
|
+
if (typeof message.content === 'string' && message.content) return true
|
|
103
|
+
if (Array.isArray(message.content) && message.content.some((part) => part && typeof part === 'object' && typeof part.text === 'string' && part.text)) return true
|
|
104
|
+
if (Array.isArray(message.tool_calls) && message.tool_calls.some((call) => call && call.function && typeof call.function.arguments === 'string' && call.function.arguments)) return true
|
|
105
|
+
return false
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* A redact-level hit can be outranked by an unrelated warn/confirm hit in the
|
|
110
|
+
* same payload (action ordering), so never rely on the aggregate action alone:
|
|
111
|
+
* scan for redaction whenever the request is not a clean allow. Blocking
|
|
112
|
+
* requests throw before this point and never reach the network anyway.
|
|
113
|
+
*/
|
|
114
|
+
function requestNeedsEgressRedaction(requestSafety) {
|
|
115
|
+
if (!requestSafety) return false
|
|
116
|
+
return requestSafety.action !== 'allow'
|
|
117
|
+
}
|
|
118
|
+
|
|
53
119
|
/** Disable the optional DeepSeek safety_check network-side gate with '0'. */
|
|
54
120
|
const SAFETY_CLOUD_ENV = 'ADVISERS_SAFETY_CLOUD'
|
|
55
121
|
|
|
@@ -75,6 +141,9 @@ function safetyWarningOf(result, direction) {
|
|
|
75
141
|
rulesetVersion: result.rulesetVersion,
|
|
76
142
|
evidenceHash: result.evidenceHash || null,
|
|
77
143
|
crisis: Boolean(result.crisis),
|
|
144
|
+
severity: result.severity || warningSeverityForAction(result.action),
|
|
145
|
+
confidence: typeof result.confidence === 'number' ? result.confidence : 0,
|
|
146
|
+
reason: result.reason || result.code,
|
|
78
147
|
auditReason,
|
|
79
148
|
}
|
|
80
149
|
}
|
|
@@ -190,6 +259,7 @@ export async function chatCompletion({
|
|
|
190
259
|
signal,
|
|
191
260
|
safetyKey,
|
|
192
261
|
safetyCheck,
|
|
262
|
+
redactEgress = true,
|
|
193
263
|
}) {
|
|
194
264
|
if (!apiKey) throw new ModelError('missing API key', { code: 'MISSING_API_KEY' })
|
|
195
265
|
const policy = thinking === false ? { enabled: false } : { enabled: true, ...resolveThinking({ task, explicit: effort }) }
|
|
@@ -201,7 +271,8 @@ export async function chatCompletion({
|
|
|
201
271
|
throwIfBlocked(requestSafety, provider, 'input')
|
|
202
272
|
const safetyWarnings = safetyWarningsOf(requestSafety, 'input')
|
|
203
273
|
|
|
204
|
-
const
|
|
274
|
+
const egress = redactEgress === false || !requestNeedsEgressRedaction(requestSafety) ? null : redactEgressMessages(messages)
|
|
275
|
+
const body = { model, messages: egress ? egress.messages : messages, max_tokens: maxTokens }
|
|
205
276
|
if (tools?.length) body.tools = tools
|
|
206
277
|
if (provider === 'deepseek') {
|
|
207
278
|
// Optional network-side second net (DeepSeek supports safety_check on the
|
|
@@ -278,6 +349,7 @@ export async function chatCompletion({
|
|
|
278
349
|
thinking: policy,
|
|
279
350
|
model,
|
|
280
351
|
...(safetyWarnings.length ? { safetyWarnings } : {}),
|
|
352
|
+
...(egress ? { egressRedaction: { count: egress.count, kinds: egress.kinds } } : {}),
|
|
281
353
|
}
|
|
282
354
|
}
|
|
283
355
|
} catch (error) {
|