@3ngram/server 1.1.3 → 1.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.
@@ -25,7 +25,7 @@
25
25
  // (no content in logs/traces/metrics) is upheld. `briefing` carries no content.
26
26
  import { briefing, handoff } from '@3ngram/core';
27
27
  import { MEMORY_READ_SCOPE } from '@3ngram/core/auth';
28
- import { briefingToolInputSchema, briefingToolOutputSchema, handoffToolInputSchema, handoffToolOutputSchema, } from '@3ngram/schema';
28
+ import { briefingToolInputV3Schema, briefingToolOutputV4Schema, handoffToolInputV3Schema, handoffToolOutputV4Schema, } from '@3ngram/schema';
29
29
  import { parseOutput } from '../output-validation.js';
30
30
  /** Wrap a structured payload as a tool success result (text mirror + structured). */
31
31
  function ok(structured) {
@@ -36,70 +36,90 @@ function ok(structured) {
36
36
  }
37
37
  /**
38
38
  * briefing — structured session orientation (docs/concepts/mcp-design.mdx JTBD "start my session
39
- * oriented"). Validates the REQUIRED selector + optional mode, calls core
39
+ * oriented"). Validates the REQUIRED selector + optional mode/sections/
40
+ * sectionLimit (the bounds V2 successor input, issue #45), calls core
40
41
  * briefing() with the injected `now` (overdue split + stale window derive from
41
42
  * it), returns the size-disciplined sections. brief mode (default) = counts + a
42
- * small top slice per section; full = bounded lists. No section carries content.
43
+ * small top slice per section; full = bounded lists. `sections` restricts the
44
+ * read to a subset (skipped sections are omitted); `sectionLimit` tunes the
45
+ * per-section bound up to the server-side ceiling. Every section carries
46
+ * `hasMore` (count > items.length). No section carries content.
43
47
  */
44
48
  const briefingTool = {
45
49
  name: 'briefing',
46
50
  requiredScope: MEMORY_READ_SCOPE,
47
51
  config: {
48
52
  title: 'Briefing',
49
- description: 'Structured session orientation: open/overdue commitments, blockers, stale candidates, recent decisions, preferences. Requires an explicit selector (scope, project, or all) — no unfiltered default. A PROJECT selector only matches commitments/blockers written WITH that project; a NULL-project memory never appears in a project briefing (issue #244). Active blockers leave this set when resolved (resolve archives the blocker memory). brief mode (default) returns counts plus top items; full returns the bounded lists.',
50
- inputSchema: briefingToolInputSchema,
51
- outputSchema: briefingToolOutputSchema,
53
+ description: 'Structured session orientation: open/overdue commitments, blockers, stale candidates, recent decisions, preferences. Requires an explicit selector (all, scope, project, or scope_project) — no unfiltered default. If a retrieval-scope policy is set (configure_scope set_retrieval_default), a kind: "all" selector may be narrowed to your default scope (the result then reports appliedScope) or rejected until you pass a scope selector. A PROJECT selector only matches memories written WITH that project; a memory written without a project (project IS NULL) never appears through the project lens. The scope_project selector narrows to one scope AND one project together; its includeUnscoped: true additionally opts NULL-project memories of that scope in (default false = strict intersection; the bare project selector is never widened). Active blockers leave this set when resolved (resolve archives the blocker memory). brief mode (default) returns counts plus top items; full returns the bounded lists. Optional sections picks a subset (un-requested sections are skipped and omitted); optional sectionLimit (1-100) tunes the per-section bound. Each section reports its exact count and hasMore when more rows exist than returned.',
54
+ inputSchema: briefingToolInputV3Schema,
55
+ outputSchema: briefingToolOutputV4Schema,
52
56
  },
53
57
  async handler(args, ctx) {
54
- const input = briefingToolInputSchema.parse(args);
58
+ const input = briefingToolInputV3Schema.parse(args);
55
59
  // ACCESS GUARD: the briefing is memory-derived, so read access is asserted
56
60
  // BEFORE the db op (self-host allowAllAccess allows all; back-compat when no
57
61
  // gate is wired).
58
62
  if (ctx.access)
59
63
  await ctx.access.assertRead(ctx.userId);
64
+ // RETRIEVAL-SCOPE POLICY (issue #47): resolved at most once per request
65
+ // (memoized thunk from the route) and injected — core owns the
66
+ // enforcement and the appliedScope echo.
67
+ const retrievalPolicy = ctx.retrievalPolicy === undefined ? undefined : await ctx.retrievalPolicy();
60
68
  // `now` is read at the transport edge (composition root), not in core/db.
69
+ // Optional knobs ride only when present (exactOptionalPropertyTypes).
61
70
  const result = await briefing(ctx.userId, {
62
71
  selector: input.selector,
63
72
  mode: input.mode,
64
73
  now: new Date(),
74
+ ...(input.sections !== undefined ? { sections: input.sections } : {}),
75
+ ...(input.sectionLimit !== undefined ? { sectionLimit: input.sectionLimit } : {}),
76
+ ...(retrievalPolicy !== undefined ? { retrievalPolicy } : {}),
65
77
  });
66
- return ok(parseOutput('briefing', briefingToolOutputSchema, result));
78
+ return ok(parseOutput('briefing', briefingToolOutputV4Schema, result));
67
79
  },
68
80
  };
69
81
  /**
70
82
  * handoff — export structured context for another agent/provider (docs/concepts/mcp-design.mdx
71
83
  * JTBD "carry context to another tool/agent"). Same REQUIRED-selector discipline
72
- * as briefing. Reuses the briefing aggregation in core (no duplicated SQL); the
73
- * OUTPUT carries memory CONTENT by design (decisions/preferences) because a
74
- * handoff transports context — bounded, and never logged (module header).
84
+ * as briefing; optional `sectionLimit` (bounds V2, issue #45) tunes the
85
+ * per-section bound up to the server-side ceiling. Reuses the briefing
86
+ * aggregation in core (no duplicated SQL); the OUTPUT carries memory CONTENT by
87
+ * design (decisions/preferences) because a handoff transports context — bounded,
88
+ * and never logged (module header). The envelope reports exact per-section
89
+ * `counts` + `truncated` flags so a receiver knows when an export is incomplete.
75
90
  */
76
91
  const handoffTool = {
77
92
  name: 'handoff',
78
93
  requiredScope: MEMORY_READ_SCOPE,
79
94
  config: {
80
95
  title: 'Handoff',
81
- description: 'Export structured context (decisions, open commitments, preferences — with content) for another agent or provider to pick up the thread. Requires an explicit selector (scope, project, or all); the payload is bounded.',
82
- inputSchema: handoffToolInputSchema,
83
- outputSchema: handoffToolOutputSchema,
96
+ description: 'Export structured context (decisions, open commitments, preferences — with content) for another agent or provider to pick up the thread. Requires an explicit selector (all, scope, project, or scope_project); the payload is bounded. If a retrieval-scope policy is set (configure_scope set_retrieval_default), a kind: "all" selector may be narrowed to your default scope (the result then reports appliedScope) or rejected until you pass a scope selector. A scope_project selector narrows to one scope AND one project; its includeUnscoped: true additionally exports NULL-project memories of that scope (default false). Optional sectionLimit (1-100) tunes the per-section bound. The envelope reports exact per-section counts, and truncated flags a section whose list is incomplete. Item content is a bounded excerpt — when a line reports truncated: true, call get_memories with its id to read the full content.',
97
+ inputSchema: handoffToolInputV3Schema,
98
+ outputSchema: handoffToolOutputV4Schema,
84
99
  },
85
100
  async handler(args, ctx) {
86
- const input = handoffToolInputSchema.parse(args);
101
+ const input = handoffToolInputV3Schema.parse(args);
87
102
  // ACCESS GUARD: handoff EXPORTS memory content, so read access is asserted
88
103
  // BEFORE the db op (self-host allowAllAccess allows all; back-compat when no
89
104
  // gate is wired).
90
105
  if (ctx.access)
91
106
  await ctx.access.assertRead(ctx.userId);
92
- // `generatedFor` is optional under exactOptionalPropertyTypes: only include
93
- // the key when present so it is `string`, never `string | undefined`.
107
+ // RETRIEVAL-SCOPE POLICY (issue #47): same once-per-request resolution +
108
+ // injection as briefing — core owns enforcement and the appliedScope echo.
109
+ const retrievalPolicy = ctx.retrievalPolicy === undefined ? undefined : await ctx.retrievalPolicy();
110
+ // Optional fields ride only when present (exactOptionalPropertyTypes): only
111
+ // include the key when present so it is `string`, never `string | undefined`.
94
112
  const result = await handoff(ctx.userId, {
95
113
  selector: input.selector,
96
114
  now: new Date(),
97
115
  ...(input.generatedFor !== undefined ? { generatedFor: input.generatedFor } : {}),
116
+ ...(input.sectionLimit !== undefined ? { sectionLimit: input.sectionLimit } : {}),
117
+ ...(retrievalPolicy !== undefined ? { retrievalPolicy } : {}),
98
118
  });
99
119
  // Decision/preference lines carry core's bounded content EXCERPT —
100
120
  // long imported rows can exceed any write-time cap, so core bounds
101
121
  // them before this output parse ever sees the payload.
102
- return ok(parseOutput('handoff', handoffToolOutputSchema, result));
122
+ return ok(parseOutput('handoff', handoffToolOutputV4Schema, result));
103
123
  },
104
124
  };
105
125
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"tools-orient.js","sourceRoot":"","sources":["../../src/mcp/tools-orient.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,wCAAwC;AACxC,gFAAgF;AAChF,kEAAkE;AAClE,sDAAsD;AACtD,EAAE;AACF,yEAAyE;AACzE,+EAA+E;AAC/E,4EAA4E;AAC5E,mEAAmE;AACnE,EAAE;AACF,k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AAS,EAAE,yBAAyB,EAAE,MAAM,CAAC,CAAC,CAAA;IACtE,CAAC;CACF,CAAA;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAA8B,CAAC,YAAY,EAAE,WAAW,CAAC,CAAA"}
@@ -0,0 +1,7 @@
1
+ import type { ToolDefinition } from './tools.js';
2
+ /**
3
+ * The search tool, spliced into the {@link TOOLS} registry by tools.ts at its
4
+ * original position (after remember). A readonly array so the registry stays
5
+ * the single auditable surface.
6
+ */
7
+ export declare const SEARCH_TOOLS: readonly ToolDefinition[];
@@ -0,0 +1,188 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // MCP SEARCH tool: `search`. A SEPARATE module from the core read/write tools
3
+ // (tools.ts) so the registry file stays thin (500-line cap) — tools.ts only
4
+ // IMPORTS this array and spreads it into TOOLS (append-only), the same pattern
5
+ // as tools-orient.ts / tools-admin.ts.
6
+ //
7
+ // Same THIN-ADAPTER contract as every tool: validate at the ONE boundary
8
+ // (packages/schema Zod), call the COMPLETE core service (which runs withTenant
9
+ // internally), shape the structured result. A read -> requiredScope
10
+ // memory:read; runTool enforces the scope BEFORE the handler runs.
11
+ import { applyPolicyToScopeFilter, searchDashboardPage } from '@3ngram/core';
12
+ import { MEMORY_READ_SCOPE } from '@3ngram/core/auth';
13
+ import { searchQueryV3Schema, searchToolOutputV3Schema, } from '@3ngram/schema';
14
+ import { decodeSearchCursor, encodeCursor, searchFingerprint } from '../cursor.js';
15
+ import { parseOutput } from '../output-validation.js';
16
+ /** Wrap a structured payload as a tool success result (text mirror + structured). */
17
+ function ok(structured) {
18
+ return {
19
+ content: [{ type: 'text', text: JSON.stringify(structured) }],
20
+ structuredContent: structured,
21
+ };
22
+ }
23
+ /** Wrap a typed failure as an isError result. The message names the class only. */
24
+ function fail(message) {
25
+ return { content: [{ type: 'text', text: message }], isError: true };
26
+ }
27
+ /** Drop keys whose value is undefined so an exactOptional core param type fits. */
28
+ function defined(obj) {
29
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
30
+ }
31
+ /** Coerce an optional ISO-8601 string to a Date for the bi-temporal core query. */
32
+ function toDate(value) {
33
+ return value === undefined ? undefined : new Date(value);
34
+ }
35
+ function toAsOf(asOf) {
36
+ if (asOf === undefined)
37
+ return undefined;
38
+ return defined({ validAt: toDate(asOf.validAt), asKnownAt: toDate(asOf.asKnownAt) });
39
+ }
40
+ /**
41
+ * Candidate-narrowing filters: validated at the schema boundary, threaded
42
+ * verbatim to core. defined() strips undefined axes so an absent filter never
43
+ * narrows (exactOptional fit for SearchFilters). V2 axes ride the same object:
44
+ * memoryTypes passes through as-is (the schema already enforced non-empty +
45
+ * mutual exclusion with memoryType); the recorded_at range bounds coerce
46
+ * ISO -> Date here like asOf.
47
+ */
48
+ function toFilters(input) {
49
+ return defined({
50
+ memoryType: input.memoryType,
51
+ memoryTypes: input.memoryTypes,
52
+ scope: input.scope,
53
+ project: input.project,
54
+ status: input.status,
55
+ asOf: toAsOf(input.asOf),
56
+ recordedAfter: toDate(input.recordedAfter),
57
+ recordedBefore: toDate(input.recordedBefore),
58
+ });
59
+ }
60
+ /**
61
+ * Shape one core hit for the wire. `full` (default) keeps the shipped excerpt
62
+ * triple (`content` is core's bounded excerpt — read-path policy in
63
+ * packages/core/src/read/excerpt.ts; contentLength/truncated let the caller
64
+ * fetch the full memory by id when the excerpt was cut). `compact` omits the
65
+ * triple (~5x fewer tokens per hit) for broad scans — the caller batch-fetches
66
+ * the interesting ids with get_memories.
67
+ */
68
+ function projectHit(hit, projection) {
69
+ const compact = { id: hit.id, memoryType: hit.memoryType, topic: hit.topic, score: hit.score };
70
+ if (projection === 'compact')
71
+ return compact;
72
+ return {
73
+ ...compact,
74
+ content: hit.content,
75
+ contentLength: hit.contentLength,
76
+ truncated: hit.truncated,
77
+ };
78
+ }
79
+ /**
80
+ * search — unified fused retrieval (docs/concepts/mcp-design.mdx JTBD "find what I know").
81
+ * Requires a configured embedding gateway: core embeds the query and THROWS
82
+ * without an embedding source, so absent a gateway the tool returns a clear
83
+ * typed error rather than a 500. The input contract is the V3 composition
84
+ * ({@link searchQueryV3Schema}, hard rule 2): query + limit, the candidate-
85
+ * narrowing filters (V1 memoryType/scope/project/status/asOf + V2
86
+ * memoryTypes[]/recordedAfter/recordedBefore), and the continuation pair —
87
+ * `cursor` (opaque frozen-ordering token) + `projection` (full/compact). Each
88
+ * filter NARROWS the candidate set BEFORE fusion; none alters the fusion
89
+ * weights or the supersession ranking (docs/concepts/memory-model.mdx
90
+ * live-first stays the default). The tool registers the FULL `.strict()`
91
+ * object (not its raw shape), so the SDK parses inbound args strictly at the
92
+ * transport boundary and an UNKNOWN key is REJECTED there — never silently
93
+ * dropped.
94
+ *
95
+ * PAGINATION routes through the SAME frozen-ordering machinery the dashboard
96
+ * uses (core searchDashboardPage + the shared ../cursor.js codec): page 1 ranks
97
+ * the bounded candidate pool once and freezes the ordering into `nextCursor`;
98
+ * a continuation pages BY POSITION within it (fetchHitsByIds), immune to
99
+ * duplicate/skip under mid-walk corpus drift. Page-1 ranking is identical to
100
+ * the pre-cursor path (returnFullPool ranks the same pool), so the eval floors
101
+ * are untouched. A garbled cursor throws a ZodError -> runTool's ladder labels
102
+ * it invalid input (never a 500); a stale pre-v2 cursor decodes to undefined
103
+ * and restarts at page 1. The cursor is BOUND to the query+filters that issued
104
+ * it (the shared codec's fingerprint, verified in decodeSearchCursor): a
105
+ * continuation under a CHANGED query/filters is a typed
106
+ * CursorQueryMismatchError -> invalid_input, never a silent re-page of the old
107
+ * search's frozen ordering. Fingerprint-less cursors minted before the binding
108
+ * stay valid (verify-when-present).
109
+ */
110
+ const searchTool = {
111
+ name: 'search',
112
+ requiredScope: MEMORY_READ_SCOPE,
113
+ config: {
114
+ title: 'Search',
115
+ description: 'Unified semantic + keyword retrieval over your memories, supersession-aware. Accepts a query and an optional result limit, plus optional filters that narrow the candidate set BEFORE fusion (no change to ranking weights): memoryType OR memoryTypes (a list of types, mutually exclusive with memoryType), scope, project, status, asOf (bi-temporal time travel with validAt/asKnownAt), and recordedAfter/recordedBefore (an inclusive recorded-at range over the live view — not time travel). Omit a filter to leave that axis unconstrained. If a retrieval-scope policy is set (configure_scope set_retrieval_default), an unscoped search may be narrowed to your default scope (the result then reports appliedScope) or rejected until you pass a scope filter. Hit content is a bounded excerpt — when a hit reports truncated: true, call get_memories with its id to read the full content. To page: pass nextCursor back as cursor with the SAME query and filters; pages come from the ordering frozen on the first page, so a mid-walk write or archive can never duplicate or skip a hit. The cursor is bound to the query and filters that issued it: passing it with a changed query or filters is rejected as invalid input — omit the cursor to start a new search. The cursor token is a real context cost (~4-6 KB — it carries the frozen ids+scores of the candidate pool), so page only when you actually need more hits. Paging stops at the frozen pool: hasMore: false means the pool is exhausted — refine the query (better filters, more specific terms) instead of paging harder. For broad scans set projection: "compact" to omit content/contentLength/truncated per hit (~5x fewer tokens), then batch-fetch the interesting ids with get_memories.',
116
+ inputSchema: searchQueryV3Schema,
117
+ outputSchema: searchToolOutputV3Schema,
118
+ },
119
+ async handler(args, ctx) {
120
+ if (ctx.gateway === undefined) {
121
+ return fail('embedding gateway not configured');
122
+ }
123
+ const input = searchQueryV3Schema.parse(args);
124
+ const filters = toFilters(input);
125
+ // Assert platform read access before policy resolution performs its tenant
126
+ // lookup. The core call is therefore not given the gate a second time.
127
+ if (ctx.access)
128
+ await ctx.access.assertRead(ctx.userId);
129
+ // RETRIEVAL-SCOPE POLICY (issue #47): resolved at most once per request
130
+ // (the route's memoized thunk) and INJECTED into core, which owns the
131
+ // enforcement (default fills a missing scope filter; require throws the
132
+ // typed UnscopedRetrievalError mapped by errors.ts).
133
+ const retrievalPolicy = ctx.retrievalPolicy === undefined ? undefined : await ctx.retrievalPolicy();
134
+ const policyScope = applyPolicyToScopeFilter(retrievalPolicy, filters.scope);
135
+ // Frozen-ordering continuation: a malformed token throws here (client
136
+ // input, mapped by runTool); a legacy token restarts at page 1. The
137
+ // fingerprint binds the cursor to THIS query+filter set — a cursor
138
+ // replayed under a changed query/filters throws the typed mismatch
139
+ // (mapped to invalid_input), never silently paging the old frozen ids.
140
+ // Fingerprint-less cursors stay valid (verify-when-present).
141
+ const fingerprint = searchFingerprint(input.query, filters, policyScope.scope, policyScope.appliedScope !== null);
142
+ const decoded = input.cursor === undefined ? undefined : decodeSearchCursor(input.cursor, fingerprint);
143
+ const frozen = decoded === undefined
144
+ ? undefined
145
+ : {
146
+ ids: decoded.ids,
147
+ scores: decoded.scores,
148
+ off: decoded.off,
149
+ ...(decoded.policyScope === undefined ? {} : { policyScope: decoded.policyScope }),
150
+ };
151
+ const page = await searchDashboardPage(ctx.userId, input.query, { gateway: ctx.gateway }, defined({
152
+ limit: input.limit,
153
+ filters,
154
+ frozen,
155
+ budget: ctx.budget,
156
+ retrievalPolicy,
157
+ }));
158
+ // Emit a cursor ONLY when a further page exists (searchToolOutputV2Schema
159
+ // ENFORCES nextCursor <-> hasMore, so a drifting pair can never ship).
160
+ const nextCursor = page.hasMore
161
+ ? encodeCursor({
162
+ v: 2,
163
+ ids: page.frozen.ids,
164
+ scores: page.frozen.scores,
165
+ off: page.nextOffset,
166
+ fp: fingerprint,
167
+ policyScope: page.frozen.policyScope,
168
+ })
169
+ : undefined;
170
+ const output = parseOutput('search', searchToolOutputV3Schema, defined({
171
+ hits: page.hits.map((hit) => projectHit(hit, input.projection)),
172
+ count: page.hits.length,
173
+ hasMore: page.hasMore,
174
+ nextCursor,
175
+ // Present exactly when the policy narrowed this call (never silent);
176
+ // omitted otherwise so an off/no-policy response stays byte-identical.
177
+ appliedScope: page.appliedScope ?? undefined,
178
+ }));
179
+ return ok(output);
180
+ },
181
+ };
182
+ /**
183
+ * The search tool, spliced into the {@link TOOLS} registry by tools.ts at its
184
+ * original position (after remember). A readonly array so the registry stays
185
+ * the single auditable surface.
186
+ */
187
+ export const SEARCH_TOOLS = [searchTool];
188
+ //# sourceMappingURL=tools-search.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tools-search.js","sourceRoot":"","s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AAE,CAAC,UAAU,CAAC,GAAG,EAAE,KAAK,CAAC,UAAU,CAAC,CAAC;YAC/D,KAAK,EAAE,IAAI,CAAC,IAAI,CAAC,MAAM;YACvB,OAAO,EAAE,IAAI,CAAC,OAAO;YACrB,UAAU;YACV,qEAAqE;YACrE,uEAAuE;YACvE,YAAY,EAAE,IAAI,CAAC,YAAY,IAAI,SAAS;SAC7C,CAAC,CACH,CAAA;QACD,OAAO,EAAE,CAAC,MAAM,CAAC,CAAA;IACnB,CAAC;CACF,CAAA;AAED;;;;GAIG;AACH,MAAM,CAAC,MAAM,YAAY,GAA8B,CAAC,UAAU,CAAC,CAAA"}
@@ -1,4 +1,4 @@
1
- import { type AccessGate, type BudgetEnforcement, type LimitsResolver } from '@3ngram/core';
1
+ import { type AccessGate, type BudgetEnforcement, type LimitsResolver, type RetrievalPolicy } from '@3ngram/core';
2
2
  import { type MemoryScope } from '@3ngram/core/auth';
3
3
  import type { Gateway } from '@3ngram/llm';
4
4
  import type { CallToolResult } from '@modelcontextprotocol/server';
@@ -59,12 +59,21 @@ export interface ToolContext {
59
59
  access?: AccessGate | undefined;
60
60
  /** Billing-neutral resource-limit resolver. Omitted fields are unlimited. */
61
61
  limits?: LimitsResolver | undefined;
62
+ /**
63
+ * Request-scoped retrieval-scope policy resolver (issue #47). The route
64
+ * builds it as a MEMOIZED thunk over core resolveRetrievalPolicy, so the
65
+ * policy is resolved AT MOST ONCE per request — and only when a
66
+ * policy-enforced read tool (search/briefing/handoff) actually runs; write
67
+ * tools never pay the lookup. Undefined → no enforcement (test/back-compat),
68
+ * identical to a stored mode of 'off'.
69
+ */
70
+ retrievalPolicy?: (() => Promise<RetrievalPolicy>) | undefined;
62
71
  }
63
72
  /**
64
73
  * THE registered tool surface. Length === registered count; the <=12 cap (hard
65
74
  * rule 8) is auditable from this one array. D0: 3; D1 adds revise + resolve -> 5;
66
- * D3 appends configure_scope + describe_environment + review_proposals -> 8 (the
67
- * sibling track's orient tools bring the union to the 10-tool v1 surface).
75
+ * D2 orient (briefing, handoff) -> 7; D3 admin (configure_scope,
76
+ * describe_environment, review_proposals) -> 10; get_memories (inspect) -> 11.
68
77
  *
69
78
  * The admin tools are created via a FACTORY given a thunk over {@link TOOLS}, so
70
79
  * describe_environment can report the FULL surface (itself included) without a
@@ -72,7 +81,7 @@ export interface ToolContext {
72
81
  * time, long after this assignment completes.
73
82
  */
74
83
  export declare const TOOLS: readonly ToolDefinition[];
75
- /** Hard ceiling per docs/concepts/mcp-design.mdx / hard rule 8. */
84
+ /** Hard ceiling per docs/concepts/mcp-design.mdx / hard rule 8. LEDGER: 11/12 registered; the LAST slot is reserved for the future `manage_context` tool. */
76
85
  export declare const MAX_TOOLS = 12;
77
86
  /**
78
87
  * Run a tool handler with uniform metrics + typed-error mapping. A KNOWN typed
package/dist/mcp/tools.js CHANGED
@@ -15,17 +15,20 @@
15
15
  // credential enters a log. A tool error returns a typed isError result to the
16
16
  // client; the message names the failure class, never the content.
17
17
  import { log, mcpToolCalls, mcpToolErrors } from '@3ngram/config';
18
- import { getFacts, remember, resolveByMemoryId, revise, search, } from '@3ngram/core';
18
+ import { getFacts, remember, resolveByMemoryId, revise, } from '@3ngram/core';
19
19
  import { MEMORY_READ_SCOPE, MEMORY_WRITE_SCOPE } from '@3ngram/core/auth';
20
- import { factsQueryInputSchema, factsToolOutputSchema, MAX_CONTENT_LENGTH, rememberToolInputSchema, rememberToolOutputSchema, resolveToolInputSchema, resolveToolOutputSchema, reviseToolInputSchema, reviseToolOutputSchema, searchQuerySchema, searchToolOutputSchema, } from '@3ngram/schema';
20
+ import { factsQueryInputSchema, factsToolOutputSchema, MAX_CONTENT_LENGTH, rememberToolInputSchema, rememberToolOutputSchema, resolveToolInputSchema, resolveToolOutputSchema, reviseToolInputSchema, reviseToolOutputSchema, } from '@3ngram/schema';
21
21
  import { parseOutput } from '../output-validation.js';
22
22
  import { mapToolError } from './errors.js';
23
23
  // Admin tools: configure_scope / describe_environment /
24
24
  // review_proposals — defined in their own module (500-line discipline), appended
25
25
  // to the registry below via the factory (append-only edit to TOOLS).
26
26
  import { createAdminTools } from './tools-admin.js';
27
+ import { INSPECT_TOOLS } from './tools-inspect.js';
27
28
  // --- orientation tools: briefing + handoff — appended ---
28
29
  import { ORIENT_TOOLS } from './tools-orient.js';
30
+ // --- search tool: fused retrieval — spliced in at its original position ---
31
+ import { SEARCH_TOOLS } from './tools-search.js';
29
32
  /** Wrap a structured payload as a tool success result (text mirror + structured). */
30
33
  function ok(structured) {
31
34
  return {
@@ -106,69 +109,6 @@ const rememberTool = {
106
109
  return ok(output);
107
110
  },
108
111
  };
109
- /**
110
- * search — unified fused retrieval (docs/concepts/mcp-design.mdx JTBD "find what I know").
111
- * Requires a configured embedding gateway: core search() embeds the query and
112
- * THROWS without an embedding source, so absent a gateway the tool returns a
113
- * clear typed error rather than a 500. The input contract is query + limit plus
114
- * the five OPTIONAL candidate-narrowing filters (memoryType/scope/project/status,
115
- * asOf) — validated at the ONE boundary ({@link searchQuerySchema}, hard rule 2)
116
- * and threaded straight to core search()'s SearchOptions. Each filter NARROWS the
117
- * candidate set BEFORE fusion; none alters the fusion weights or the
118
- * supersession ranking (docs/concepts/memory-model.mdx live-first stays the default). The tool
119
- * registers the FULL `.strict()` object (not its raw shape), so the SDK parses
120
- * inbound args strictly at the transport boundary and an UNKNOWN key is REJECTED
121
- * there — a passed filter the tool exposes is applied, anything else is a clear
122
- * validation error, never silently dropped (registering `.shape`
123
- * would wrap it non-strict and strip unknown keys before the handler ran).
124
- */
125
- const searchTool = {
126
- name: 'search',
127
- requiredScope: MEMORY_READ_SCOPE,
128
- config: {
129
- title: 'Search',
130
- description: 'Unified semantic + keyword retrieval over your memories, supersession-aware. Accepts a query and an optional result limit, plus five optional filters that narrow the candidate set BEFORE fusion (no change to ranking weights): memoryType, scope, project, status, and asOf (bi-temporal time travel with validAt/asKnownAt). Omit a filter to leave that axis unconstrained.',
131
- inputSchema: searchQuerySchema,
132
- outputSchema: searchToolOutputSchema,
133
- },
134
- async handler(args, ctx) {
135
- if (ctx.gateway === undefined) {
136
- return fail('embedding gateway not configured');
137
- }
138
- const input = searchQuerySchema.parse(args);
139
- const hits = await search(ctx.userId, input.query, { gateway: ctx.gateway }, {
140
- limit: input.limit,
141
- // Candidate-narrowing filters: validated at the schema
142
- // boundary, threaded verbatim to core. defined() strips undefined axes so
143
- // an absent filter never narrows (exactOptional fit for SearchFilters).
144
- filters: defined({
145
- memoryType: input.memoryType,
146
- scope: input.scope,
147
- project: input.project,
148
- status: input.status,
149
- asOf: toAsOf(input.asOf),
150
- }),
151
- budget: ctx.budget,
152
- access: ctx.access,
153
- });
154
- // `content` is core's bounded excerpt (read-path policy in
155
- // packages/core/src/read/excerpt.ts); contentLength/truncated let the
156
- // caller fetch the full memory by id when the excerpt was cut.
157
- const output = parseOutput('search', searchToolOutputSchema, {
158
- hits: hits.map((hit) => ({
159
- id: hit.id,
160
- memoryType: hit.memoryType,
161
- topic: hit.topic,
162
- content: hit.content,
163
- contentLength: hit.contentLength,
164
- truncated: hit.truncated,
165
- score: hit.score,
166
- })),
167
- count: hits.length,
168
- });
169
- return ok(output);
170
- },
171
- };
172
112
  /**
173
113
  * get_facts — currently-valid facts for a subject, bi-temporally (docs/concepts/mcp-design.mdx
174
114
  * JTBD "what is currently true about X"). Calls core getFacts() with the
@@ -309,8 +249,8 @@ const resolveTool = {
309
249
  /**
310
250
  * THE registered tool surface. Length === registered count; the <=12 cap (hard
311
251
  * rule 8) is auditable from this one array. D0: 3; D1 adds revise + resolve -> 5;
312
- * D3 appends configure_scope + describe_environment + review_proposals -> 8 (the
313
- * sibling track's orient tools bring the union to the 10-tool v1 surface).
252
+ * D2 orient (briefing, handoff) -> 7; D3 admin (configure_scope,
253
+ * describe_environment, review_proposals) -> 10; get_memories (inspect) -> 11.
314
254
  *
315
255
  * The admin tools are created via a FACTORY given a thunk over {@link TOOLS}, so
316
256
  * describe_environment can report the FULL surface (itself included) without a
@@ -319,19 +259,22 @@ const resolveTool = {
319
259
  */
320
260
  export const TOOLS = [
321
261
  rememberTool,
322
- searchTool,
262
+ // search — defined in tools-search.ts (500-line discipline) and spliced in at
263
+ // its original position so the advertised tool order is unchanged.
264
+ ...SEARCH_TOOLS,
323
265
  getFactsTool,
324
266
  reviseTool,
325
267
  resolveTool,
326
268
  // D2 orientation tools (briefing, handoff) — appended from tools-orient.ts so
327
269
  // this registry stays the single auditable surface while the file stays thin.
328
270
  ...ORIENT_TOOLS,
271
+ ...INSPECT_TOOLS, // get_memories — appended from tools-inspect.ts (same pattern)
329
272
  // D3 admin tools (configure_scope, describe_environment, review_proposals) —
330
273
  // appended via the factory thunk so describe_environment can report the FULL
331
274
  // surface (itself included) without a circular import.
332
275
  ...createAdminTools(() => TOOLS.map((t) => t.name)),
333
276
  ];
334
- /** Hard ceiling per docs/concepts/mcp-design.mdx / hard rule 8. */
277
+ /** Hard ceiling per docs/concepts/mcp-design.mdx / hard rule 8. LEDGER: 11/12 registered; the LAST slot is reserved for the future `manage_context` tool. */
335
278
  export const MAX_TOOLS = 12;
336
279
  /**
337
280
  * Run a tool handler with uniform metrics + typed-error mapping. A KNOWN typed
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../src/mcp/tools.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,gFAAgF;AAChF,qEAAqE;AACrE,yEAAyE;AACzE,gFAAgF;AAChF,4EAA4E;AAC5E,6CAA6C;AAC7C,EAAE;AACF,6FAA6F;AAC7F,4EAA4E;AAC5E,6EAA6E;AAC7E,mCAAmC;AACnC,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,kEAAkE;AAClE,OAAO,EAAE,GAAG,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AACjE,OAAO,EAGL,QAAQ,EAER,QAAQ,EACR,iBAAiB,EACjB,MAAM,EACN,MAAM,GACP,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,iBAAiB,EAAE,kBA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EAAE,GAAG,CAAC,CAAA;IACtC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,8EAA8E;QAC9E,4EAA4E;QAC5E,gEAAgE;QAChE,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,IAAI,EAAE,GAAG,CAAC,CAAA;QAC3C,IAAI,MAAM,KAAK,SAAS;YAAE,OAAO,MAAM,CAAA;QACvC,aAAa,CAAC,GAAG,CAAC,CAAC,EAAE,EAAE,SAAS,EAAE,IAAI,CAAC,IAAI,EAAE,WAAW,EAAE,gBAAgB,EAAE,CAAC,CAAA;QAC7E,GAAG,EAAE,CAAC,KAAK,CACT,EAAE,SAAS,EAAE,IAAI,CAAC,IAAI,EAAE,GAAG,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,EAAE,EAC1E,0BAA0B,CAC3B,CAAA;QACD,OAAO,IAAI,CAAC,gBAAgB,CAAC,CAAA;IAC/B,CAAC;AACH,CAAC"}
@@ -3,6 +3,12 @@ export interface RestError {
3
3
  status: number;
4
4
  /** The reason_code (MCP taxonomy) — the stable machine-readable error tag. */
5
5
  reason: string;
6
+ /**
7
+ * Optional bounded, human-readable recovery detail — surfaced in the body
8
+ * alongside the reason_code. Only ever carries bounded enum states or user
9
+ * labels (e.g. registered scope names), NEVER memory content (hard rule 6).
10
+ */
11
+ detail?: string;
6
12
  }
7
13
  /**
8
14
  * Map a thrown error to an HTTP status + reason_code, or undefined when the error
@@ -24,8 +24,9 @@
24
24
  // bounded ids/hashes the typed error already carries (a uuid, a content hash, an
25
25
  // FSM state — never content).
26
26
  import { log } from '@3ngram/config';
27
- import { AccessDeniedError, BudgetExceededError, CommitmentExistsError, CommitmentNotFoundError, DuplicateMemoryError, EdgeConflictError, EpisodicSupersessionError, IllegalCommitmentTransitionError, InvalidCommitmentTransitionError, InvalidEmbeddingError, MemoryNotFoundError, MissingSelectorError, NotCommitmentMemoryError, PredecessorAlreadySupersededError, PredecessorNotFoundError, ProposalNotFoundError, ResourceLimitExceededError, ScopeNameConflictError, ScopeNotFoundError, SuccessorNotLiveError, } from '@3ngram/core';
27
+ import { AccessDeniedError, BudgetExceededError, CommitmentExistsError, CommitmentNotFoundError, DuplicateMemoryError, EdgeConflictError, EpisodicSupersessionError, formatUnscopedRetrievalDetail, IllegalCommitmentTransitionError, InvalidCommitmentTransitionError, InvalidEmbeddingError, MemoryNotFoundError, MissingSelectorError, NotCommitmentMemoryError, PredecessorAlreadySupersededError, PredecessorNotFoundError, ProposalNotFoundError, ResourceLimitExceededError, ScopeNameConflictError, ScopeNotFoundError, SuccessorNotLiveError, UnscopedRetrievalError, } from '@3ngram/core';
28
28
  import { ZodError } from 'zod';
29
+ import { CursorQueryMismatchError } from '../cursor.js';
29
30
  import { OutputValidationError } from '../output-validation.js';
30
31
  /**
31
32
  * Map a thrown error to an HTTP status + reason_code, or undefined when the error
@@ -44,13 +45,29 @@ export function mapRestError(route, err) {
44
45
  log().error({ route, err: err.name, issue_count: err.issueCount, paths: err.issuePaths }, 'rest: result failed output validation');
45
46
  return { status: 500, reason: 'invalid_output' };
46
47
  }
48
+ // An unscoped read rejected by the caller's own retrieval-scope policy
49
+ // (mode 'require', issue #47) — the MissingSelectorError sibling: 400,
50
+ // invalid_input, with bounded recovery DETAIL naming a prefix of the
51
+ // registered scopes (user labels, never content — hard rule 6). Mirrors MCP.
52
+ if (err instanceof UnscopedRetrievalError) {
53
+ log().warn({ route, err: err.name }, 'rest: unscoped read rejected by policy');
54
+ return {
55
+ status: 400,
56
+ reason: 'invalid_input',
57
+ detail: formatUnscopedRetrievalDetail(err.registeredScopes),
58
+ };
59
+ }
47
60
  // Malformed CLIENT input — a ZodError from a boundary INPUT .parse() or a
48
61
  // typed core validation error — is a 400, not a server fault: only the error
49
62
  // class name is logged.
50
63
  if (err instanceof ZodError ||
51
64
  err instanceof InvalidEmbeddingError ||
52
65
  err instanceof MissingSelectorError ||
53
- err instanceof NotCommitmentMemoryError) {
66
+ err instanceof NotCommitmentMemoryError ||
67
+ // A continuation cursor replayed against a different query/filter set —
68
+ // the caller's mistake, named honestly (never a silent re-page of the old
69
+ // search's frozen ordering). No query text is logged, only the class name.
70
+ err instanceof CursorQueryMismatchError) {
54
71
  log().warn({ route, err: err instanceof Error ? err.name : 'unknown' }, 'rest: input rejected');
55
72
  return { status: 400, reason: 'invalid_input' };
56
73
  }