@3ngram/server 0.7.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.
Files changed (116) hide show
  1. package/LICENSE +202 -0
  2. package/dist/app.d.ts +72 -0
  3. package/dist/app.js +273 -0
  4. package/dist/app.js.map +1 -0
  5. package/dist/boot.d.ts +37 -0
  6. package/dist/boot.js +53 -0
  7. package/dist/boot.js.map +1 -0
  8. package/dist/composition/extension.d.ts +50 -0
  9. package/dist/composition/extension.js +16 -0
  10. package/dist/composition/extension.js.map +1 -0
  11. package/dist/index.d.ts +1 -0
  12. package/dist/index.js +10 -0
  13. package/dist/index.js.map +1 -0
  14. package/dist/links.d.ts +17 -0
  15. package/dist/links.js +46 -0
  16. package/dist/links.js.map +1 -0
  17. package/dist/mailer.d.ts +58 -0
  18. package/dist/mailer.js +187 -0
  19. package/dist/mailer.js.map +1 -0
  20. package/dist/mcp/errors.d.ts +14 -0
  21. package/dist/mcp/errors.js +175 -0
  22. package/dist/mcp/errors.js.map +1 -0
  23. package/dist/mcp/prompts.d.ts +29 -0
  24. package/dist/mcp/prompts.js +180 -0
  25. package/dist/mcp/prompts.js.map +1 -0
  26. package/dist/mcp/server.d.ts +14 -0
  27. package/dist/mcp/server.js +34 -0
  28. package/dist/mcp/server.js.map +1 -0
  29. package/dist/mcp/tools-admin.d.ts +8 -0
  30. package/dist/mcp/tools-admin.js +260 -0
  31. package/dist/mcp/tools-admin.js.map +1 -0
  32. package/dist/mcp/tools-orient.d.ts +6 -0
  33. package/dist/mcp/tools-orient.js +110 -0
  34. package/dist/mcp/tools-orient.js.map +1 -0
  35. package/dist/mcp/tools.d.ts +88 -0
  36. package/dist/mcp/tools.js +375 -0
  37. package/dist/mcp/tools.js.map +1 -0
  38. package/dist/middleware/api-key.d.ts +13 -0
  39. package/dist/middleware/api-key.js +83 -0
  40. package/dist/middleware/api-key.js.map +1 -0
  41. package/dist/middleware/api-or-session.d.ts +9 -0
  42. package/dist/middleware/api-or-session.js +22 -0
  43. package/dist/middleware/api-or-session.js.map +1 -0
  44. package/dist/middleware/authenticate.d.ts +21 -0
  45. package/dist/middleware/authenticate.js +51 -0
  46. package/dist/middleware/authenticate.js.map +1 -0
  47. package/dist/middleware/index.d.ts +1 -0
  48. package/dist/middleware/index.js +9 -0
  49. package/dist/middleware/index.js.map +1 -0
  50. package/dist/middleware/oauth-bearer.d.ts +8 -0
  51. package/dist/middleware/oauth-bearer.js +117 -0
  52. package/dist/middleware/oauth-bearer.js.map +1 -0
  53. package/dist/middleware/rate-limit.d.ts +58 -0
  54. package/dist/middleware/rate-limit.js +139 -0
  55. package/dist/middleware/rate-limit.js.map +1 -0
  56. package/dist/middleware/request-context.d.ts +7 -0
  57. package/dist/middleware/request-context.js +14 -0
  58. package/dist/middleware/request-context.js.map +1 -0
  59. package/dist/output-validation.d.ts +18 -0
  60. package/dist/output-validation.js +30 -0
  61. package/dist/output-validation.js.map +1 -0
  62. package/dist/redis.d.ts +9 -0
  63. package/dist/redis.js +37 -0
  64. package/dist/redis.js.map +1 -0
  65. package/dist/rest/cursor.d.ts +14 -0
  66. package/dist/rest/cursor.js +38 -0
  67. package/dist/rest/cursor.js.map +1 -0
  68. package/dist/rest/errors.d.ts +14 -0
  69. package/dist/rest/errors.js +119 -0
  70. package/dist/rest/errors.js.map +1 -0
  71. package/dist/rest/router.d.ts +33 -0
  72. package/dist/rest/router.js +846 -0
  73. package/dist/rest/router.js.map +1 -0
  74. package/dist/rest/scope.d.ts +14 -0
  75. package/dist/rest/scope.js +45 -0
  76. package/dist/rest/scope.js.map +1 -0
  77. package/dist/routes/api-keys.d.ts +2 -0
  78. package/dist/routes/api-keys.js +77 -0
  79. package/dist/routes/api-keys.js.map +1 -0
  80. package/dist/routes/auth.d.ts +20 -0
  81. package/dist/routes/auth.js +325 -0
  82. package/dist/routes/auth.js.map +1 -0
  83. package/dist/routes/capabilities.d.ts +10 -0
  84. package/dist/routes/capabilities.js +17 -0
  85. package/dist/routes/capabilities.js.map +1 -0
  86. package/dist/routes/health.d.ts +7 -0
  87. package/dist/routes/health.js +12 -0
  88. package/dist/routes/health.js.map +1 -0
  89. package/dist/routes/mcp.d.ts +27 -0
  90. package/dist/routes/mcp.js +81 -0
  91. package/dist/routes/mcp.js.map +1 -0
  92. package/dist/routes/oauth-authorize.d.ts +8 -0
  93. package/dist/routes/oauth-authorize.js +245 -0
  94. package/dist/routes/oauth-authorize.js.map +1 -0
  95. package/dist/routes/oauth-clients.d.ts +2 -0
  96. package/dist/routes/oauth-clients.js +59 -0
  97. package/dist/routes/oauth-clients.js.map +1 -0
  98. package/dist/routes/oauth-register.d.ts +8 -0
  99. package/dist/routes/oauth-register.js +59 -0
  100. package/dist/routes/oauth-register.js.map +1 -0
  101. package/dist/routes/oauth-token.d.ts +30 -0
  102. package/dist/routes/oauth-token.js +451 -0
  103. package/dist/routes/oauth-token.js.map +1 -0
  104. package/dist/routes/onboarding.d.ts +2 -0
  105. package/dist/routes/onboarding.js +47 -0
  106. package/dist/routes/onboarding.js.map +1 -0
  107. package/dist/routes/profile.d.ts +2 -0
  108. package/dist/routes/profile.js +35 -0
  109. package/dist/routes/profile.js.map +1 -0
  110. package/dist/routes/well-known.d.ts +2 -0
  111. package/dist/routes/well-known.js +77 -0
  112. package/dist/routes/well-known.js.map +1 -0
  113. package/dist/version.d.ts +1 -0
  114. package/dist/version.js +17 -0
  115. package/dist/version.js.map +1 -0
  116. package/package.json +67 -0
@@ -0,0 +1,110 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // MCP ORIENTATION tools: `briefing` and
3
+ // `handoff`. A SEPARATE module from the core read/write tools (tools.ts) so the
4
+ // registry file stays thin (500-line cap) — tools.ts only IMPORTS
5
+ // this array and spreads it into TOOLS (append-only).
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. Both are reads -> requiredScope
10
+ // memory:read; runTool enforces the scope BEFORE the handler runs.
11
+ //
12
+ // SELECTOR DISCIPLINE (no-firehose, mcp-design.md centerpiece): both tools REQUIRE
13
+ // an explicit selector. The schema makes it required; core re-checks the semantic
14
+ // invariant and throws MissingSelectorError, mapped to a typed isError by
15
+ // errors.ts. A briefing/handoff can NEVER be the unfiltered firehose the old
16
+ // system regretted.
17
+ //
18
+ // INJECTED TIME: `now` is read HERE (the transport composition root) and passed
19
+ // into core, so core/db stay deterministic (no wall-clock read in business
20
+ // logic). The overdue split and stale window derive from this instant.
21
+ //
22
+ // CONTENT IN OUTPUT vs LOGS: `handoff`'s OUTPUT carries memory
23
+ // content BY DESIGN (its purpose is transporting context) — this is a data export
24
+ // to the authenticated caller, NOT a log. Neither handler logs the payload; rule 6
25
+ // (no content in logs/traces/metrics) is upheld. `briefing` carries no content.
26
+ import { briefing, handoff } from '@3ngram/core';
27
+ import { MEMORY_READ_SCOPE } from '@3ngram/core/auth';
28
+ import { briefingToolInputSchema, briefingToolOutputSchema, handoffToolInputSchema, handoffToolOutputSchema, } from '@3ngram/schema';
29
+ import { parseOutput } from '../output-validation.js';
30
+ /** Wrap a structured payload as a tool success result (text mirror + structured). */
31
+ function ok(structured) {
32
+ return {
33
+ content: [{ type: 'text', text: JSON.stringify(structured) }],
34
+ structuredContent: structured,
35
+ };
36
+ }
37
+ /**
38
+ * briefing — structured session orientation (mcp-design.md JTBD "start my session
39
+ * oriented"). Validates the REQUIRED selector + optional mode, calls core
40
+ * briefing() with the injected `now` (overdue split + stale window derive from
41
+ * 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
+ */
44
+ const briefingTool = {
45
+ name: 'briefing',
46
+ requiredScope: MEMORY_READ_SCOPE,
47
+ config: {
48
+ 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.shape,
51
+ outputSchema: briefingToolOutputSchema.shape,
52
+ },
53
+ async handler(args, ctx) {
54
+ const input = briefingToolInputSchema.parse(args);
55
+ // ACCESS GUARD: the briefing is memory-derived, so read access is asserted
56
+ // BEFORE the db op (self-host allowAllAccess allows all; back-compat when no
57
+ // gate is wired).
58
+ if (ctx.access)
59
+ await ctx.access.assertRead(ctx.userId);
60
+ // `now` is read at the transport edge (composition root), not in core/db.
61
+ const result = await briefing(ctx.userId, {
62
+ selector: input.selector,
63
+ mode: input.mode,
64
+ now: new Date(),
65
+ });
66
+ return ok(parseOutput('briefing', briefingToolOutputSchema, result));
67
+ },
68
+ };
69
+ /**
70
+ * handoff — export structured context for another agent/provider (mcp-design.md
71
+ * 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).
75
+ */
76
+ const handoffTool = {
77
+ name: 'handoff',
78
+ requiredScope: MEMORY_READ_SCOPE,
79
+ config: {
80
+ 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.shape,
83
+ outputSchema: handoffToolOutputSchema.shape,
84
+ },
85
+ async handler(args, ctx) {
86
+ const input = handoffToolInputSchema.parse(args);
87
+ // ACCESS GUARD: handoff EXPORTS memory content, so read access is asserted
88
+ // BEFORE the db op (self-host allowAllAccess allows all; back-compat when no
89
+ // gate is wired).
90
+ if (ctx.access)
91
+ 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`.
94
+ const result = await handoff(ctx.userId, {
95
+ selector: input.selector,
96
+ now: new Date(),
97
+ ...(input.generatedFor !== undefined ? { generatedFor: input.generatedFor } : {}),
98
+ });
99
+ // Decision/preference lines carry core's bounded content EXCERPT —
100
+ // long imported rows can exceed any write-time cap, so core bounds
101
+ // them before this output parse ever sees the payload.
102
+ return ok(parseOutput('handoff', handoffToolOutputSchema, result));
103
+ },
104
+ };
105
+ /**
106
+ * The orientation tools, appended to the {@link TOOLS} registry by tools.ts. A
107
+ * readonly array so the registry stays the single auditable surface.
108
+ */
109
+ export const ORIENT_TOOLS = [briefingTool, handoffTool];
110
+ //# sourceMappingURL=tools-orient.js.map
@@ -0,0 +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,mFAAmF;AACnF,kFAAkF;AAClF,0EAA0E;AAC1E,6EAA6E;AAC7E,oBAAoB;AACpB,EAAE;AACF,gFAAgF;AAChF,2EAA2E;AAC3E,uEAAuE;AACvE,EAAE;AACF,+DAA+D;AAC/D,kFAAkF;AAClF,mFAAmF;AACnF,gFAAgF;AAChF,OAAO,EAAE,QAAQ,EAAE,OAAO,EAAE,MAAM,cAAc,CAAA;AAChD,OAAO,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAA;AACrD,OAAO,EACL,uBAAuB,EACvB,wBAAwB,EACxB,sBAAsB,EACtB,uBAAuB,GACxB,MAAM,gBAAgB,CAAA;AAEvB,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AAGrD,qFAAqF;AACrF,SAAS,EAAE,CAAC,UAAmC;IAC7C,OAAO;QACL,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,E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EAAE,GAAgB;QAC3C,MAAM,KAAK,GAAG,sBAAsB,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QAChD,2EAA2E;QAC3E,6EAA6E;QAC7E,kBAAkB;QAClB,IAAI,GAAG,CAAC,MAAM;YAAE,MAAM,GAAG,CAAC,MAAM,CAAC,UAAU,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;QACvD,4EAA4E;QAC5E,sEAAsE;QACtE,MAAM,MAAM,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC,MAAM,EAAE;YACvC,QAAQ,EAAE,KAAK,CAAC,QAAQ;YACxB,GAAG,EAAE,IAAI,IAAI,EAAE;YACf,GAAG,CAAC,KAAK,CAAC,YAAY,KAAK,SAAS,CAAC,CAAC,CAAC,EAAE,YAAY,EAAE,KAAK,CAAC,YAAY,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;SAClF,CAAC,CAAA;QACF,mEAAmE;QACnE,mEAAmE;QACnE,uDAAuD;QACvD,OAAO,EAAE,CAAC,WAAW,CAAC,SAAS,EAAE,uBAAuB,EAAE,MAAM,CAAC,CAAC,CAAA;IACpE,CAAC;CACF,CAAA;AAED;;;GAGG;AACH,MAAM,CAAC,MAAM,YAAY,GAA8B,CAAC,YAAY,EAAE,WAAW,CAAC,CAAA"}
@@ -0,0 +1,88 @@
1
+ import { type AccessGate, type BudgetEnforcement } from '@3ngram/core';
2
+ import { type MemoryScope } from '@3ngram/core/auth';
3
+ import type { Gateway } from '@3ngram/llm';
4
+ import type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
5
+ import type { ZodObject, ZodRawShape } from 'zod';
6
+ /** The SDK result a tool returns: a text content mirror plus structured output. */
7
+ type ToolResult = CallToolResult;
8
+ /**
9
+ * A registered tool. `outputSchema` is a Zod RAW SHAPE (the SDK 1.x
10
+ * `registerTool` contract: it wraps a shape in a NON-strict z.object internally).
11
+ * `inputSchema` is either a raw shape OR a full Zod OBJECT schema: the SDK keeps a
12
+ * full schema AS-IS (mcp.js getZodSchemaObject), so a `.strict()` object is parsed
13
+ * strictly at the SDK boundary and an unknown key is REJECTED before the handler
14
+ * runs — a raw shape, by contrast, is wrapped non-strict and silently STRIPS
15
+ * unknown keys. Pass the strict object directly when the tool's contract rejects
16
+ * unknown keys end-to-end (search). The handler receives the
17
+ * SDK-validated args plus the per-request adapter context.
18
+ */
19
+ /**
20
+ * The registry-level scope floor a token must satisfy to reach a tool's handler
21
+ * (ADR-0009 §RS per-tool scope mapping). Either:
22
+ * - a SINGLE {@link MemoryScope}: the token MUST carry exactly that scope
23
+ * (single-action tools — reads → {@link MEMORY_READ_SCOPE}, writes →
24
+ * {@link MEMORY_WRITE_SCOPE});
25
+ * - `{ anyOf: MemoryScope[] }`: the token must carry AT LEAST ONE of the listed
26
+ * scopes (per-action tools whose actions span read AND write — the handler
27
+ * then asserts the action-specific scope). Read is NOT a superset of write, so
28
+ * a write-only token must be admitted by the floor before its handler can gate
29
+ * a mutation. {@link runTool} enforces this BEFORE the handler runs, fail-closed
30
+ * (an empty token-scope set satisfies no floor).
31
+ */
32
+ export type RequiredScope = MemoryScope | {
33
+ anyOf: readonly MemoryScope[];
34
+ };
35
+ export interface ToolDefinition {
36
+ name: string;
37
+ /** The scope floor {@link runTool} enforces before the handler runs. */
38
+ requiredScope: RequiredScope;
39
+ config: {
40
+ title: string;
41
+ description: string;
42
+ inputSchema: ZodRawShape | ZodObject;
43
+ outputSchema: ZodRawShape;
44
+ };
45
+ handler: (args: unknown, ctx: ToolContext) => Promise<ToolResult>;
46
+ }
47
+ /** Per-request context the transport injects: the authenticated tenant, its granted scopes, + optional gateway. */
48
+ export interface ToolContext {
49
+ userId: string;
50
+ /**
51
+ * The OAuth scopes the verified Bearer token granted (parsed from its `scope`
52
+ * claim by oauthBearerAuth). FAIL-CLOSED: an empty array (claim absent) grants
53
+ * nothing, so the per-tool scope check rejects every write — and any read whose
54
+ * scope is not present.
55
+ */
56
+ scopes: readonly string[];
57
+ /** Embedding gateway, or undefined when not configured (env-gated at boot). */
58
+ gateway: Gateway | undefined;
59
+ /** Budget enforcement — gates metered tools (remember/revise/
60
+ * search). Undefined → no budget gate (test/back-compat). */
61
+ budget?: BudgetEnforcement | undefined;
62
+ /** Access gate — asserts read/write access on every tool. Undefined → no access
63
+ * guard (test/back-compat). */
64
+ access?: AccessGate | undefined;
65
+ }
66
+ /**
67
+ * THE registered tool surface. Length === registered count; the <=12 cap (hard
68
+ * rule 8) is auditable from this one array. D0: 3; D1 adds revise + resolve -> 5;
69
+ * D3 appends configure_scope + describe_environment + review_proposals -> 8 (the
70
+ * sibling track's orient tools bring the union to the 10-tool v1 surface).
71
+ *
72
+ * The admin tools are created via a FACTORY given a thunk over {@link TOOLS}, so
73
+ * describe_environment can report the FULL surface (itself included) without a
74
+ * circular import: the thunk closes over TOOLS and is only invoked at REQUEST
75
+ * time, long after this assignment completes.
76
+ */
77
+ export declare const TOOLS: readonly ToolDefinition[];
78
+ /** Hard ceiling per mcp-design.md / hard rule 8. */
79
+ export declare const MAX_TOOLS = 12;
80
+ /**
81
+ * Run a tool handler with uniform metrics + typed-error mapping. A KNOWN typed
82
+ * core error (bad input, missing embedding source) becomes an isError result
83
+ * with a class-named message; an UNKNOWN error is logged (crash-safe, no
84
+ * content) and surfaced as a generic failure. The handler itself never logs
85
+ * content (hard rule 6).
86
+ */
87
+ export declare function runTool(tool: ToolDefinition, args: unknown, ctx: ToolContext): Promise<ToolResult>;
88
+ export {};
@@ -0,0 +1,375 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // MCP tool registry — the THIN adapter layer (AGENTS.md hard rule 5: transports
3
+ // hold zero business logic). Each tool validates at the ONE boundary
4
+ // (packages/schema Zod), calls the COMPLETE core service, and shapes the
5
+ // structured result. Tenant scoping is the authenticated `userId` threaded into
6
+ // every core call (which runs withTenant internally) — a tool can only ever
7
+ // touch the caller's own rows (hard rule 3).
8
+ //
9
+ // TOOL-COUNT DISCIPLINE (mcp-design.md, hard rule 8: <=12): the single {@link
10
+ // TOOLS} array is the auditable surface — its length IS the registered tool
11
+ // count. D0 ships exactly THREE (remember/search/get_facts); the other seven
12
+ // JTBD tools land in later slices.
13
+ //
14
+ // Observability (hard rule 6): no memory content, query text, subject/value, or
15
+ // credential enters a log. A tool error returns a typed isError result to the
16
+ // client; the message names the failure class, never the content.
17
+ import { log, mcpToolCalls, mcpToolErrors } from '@3ngram/config';
18
+ import { getFacts, remember, resolveByMemoryId, revise, search, } from '@3ngram/core';
19
+ import { MEMORY_READ_SCOPE, MEMORY_WRITE_SCOPE } from '@3ngram/core/auth';
20
+ import { factsQueryInputSchema, factsToolOutputSchema, rememberToolInputSchema, rememberToolOutputSchema, resolveToolInputSchema, resolveToolOutputSchema, reviseToolInputSchema, reviseToolOutputSchema, searchQuerySchema, searchToolOutputSchema, } from '@3ngram/schema';
21
+ import { parseOutput } from '../output-validation.js';
22
+ import { mapToolError } from './errors.js';
23
+ // Admin tools: configure_scope / describe_environment /
24
+ // review_proposals — defined in their own module (500-line discipline), appended
25
+ // to the registry below via the factory (append-only edit to TOOLS).
26
+ import { createAdminTools } from './tools-admin.js';
27
+ // --- orientation tools: briefing + handoff — appended ---
28
+ import { ORIENT_TOOLS } from './tools-orient.js';
29
+ /** Wrap a structured payload as a tool success result (text mirror + structured). */
30
+ function ok(structured) {
31
+ return {
32
+ content: [{ type: 'text', text: JSON.stringify(structured) }],
33
+ structuredContent: structured,
34
+ };
35
+ }
36
+ /** Drop keys whose value is undefined so an exactOptional core param type fits. */
37
+ function defined(obj) {
38
+ return Object.fromEntries(Object.entries(obj).filter(([, v]) => v !== undefined));
39
+ }
40
+ /** Wrap a typed failure as an isError result. The message names the class only. */
41
+ function fail(message) {
42
+ return { content: [{ type: 'text', text: message }], isError: true };
43
+ }
44
+ /** Coerce an optional ISO-8601 string to a Date for the bi-temporal core query. */
45
+ function toDate(value) {
46
+ return value === undefined ? undefined : new Date(value);
47
+ }
48
+ function toAsOf(asOf) {
49
+ if (asOf === undefined)
50
+ return undefined;
51
+ return defined({ validAt: toDate(asOf.validAt), asKnownAt: toDate(asOf.asKnownAt) });
52
+ }
53
+ /**
54
+ * remember — append a memory (mcp-design.md JTBD "persist something worth
55
+ * keeping"). Validates via the canonical write schema, calls core remember()
56
+ * (which validates once more at its own boundary and embeds-on-write via the
57
+ * injected gateway), returns the created memory + whether the embed landed.
58
+ * Registers the FULL `.strict()` object (not its raw `.shape`) so the SDK parses
59
+ * inbound args strictly at the transport boundary: a supplied `scope`/`project`
60
+ * survives to the handler instead of being silently stripped, and an unknown key
61
+ * is REJECTED (mirroring the search fix).
62
+ */
63
+ const rememberTool = {
64
+ name: 'remember',
65
+ requiredScope: MEMORY_WRITE_SCOPE,
66
+ config: {
67
+ title: 'Remember',
68
+ description: 'Append a new memory (decision, fact, preference, blocker, commitment, ...). Never merges; append-only. To surface a commitment or blocker in a PROJECT-scoped briefing, pass `project` — a memory written with a NULL project never matches a project filter (issue #244).',
69
+ inputSchema: rememberToolInputSchema,
70
+ outputSchema: rememberToolOutputSchema.shape,
71
+ },
72
+ async handler(args, ctx) {
73
+ // core remember() is THE validation boundary; pass the args straight through.
74
+ // It returns the new id only, so the structured output echoes the NORMALIZED
75
+ // write input (scope default + null project applied here) for the rest.
76
+ // Embedding is on iff a gateway is configured — best-effort, never blocks.
77
+ const input = rememberToolInputSchema.parse(args);
78
+ const gatewayOpts = ctx.gateway === undefined
79
+ ? { access: ctx.access }
80
+ : { gateway: ctx.gateway, budget: ctx.budget, access: ctx.access };
81
+ const written = await remember(ctx.userId, input, 'user_mcp', gatewayOpts);
82
+ // ACK-BEFORE-EMBED: the write is already durable here. We DO NOT await the
83
+ // background embed — a gateway round-trip is up to 30s and blocking the MCP
84
+ // response on it would re-couple the turn to the gateway and defeat core's
85
+ // ack-before-embed. The settle handle is left unawaited but defended so a
86
+ // background rejection can never surface as an unhandled rejection (core
87
+ // already .catch-resolves it to false; this is belt-and-braces).
88
+ void written.embed.settled.catch(() => false);
89
+ // The tool can only ever report the embed as not-yet-resolved: `pending`
90
+ // when a gateway is configured (background embed in flight), `off` when none.
91
+ const embedded = ctx.gateway === undefined ? 'off' : 'pending';
92
+ // A commitment-type memory auto-creates an 'open' commitment in the same
93
+ // write tx; surface its id so the caller can `resolve`
94
+ // it without a follow-up lookup. Undefined (omitted) for every other type.
95
+ const output = parseOutput('remember', rememberToolOutputSchema, defined({
96
+ memory: {
97
+ id: written.id,
98
+ memoryType: input.memoryType,
99
+ topic: input.topic,
100
+ scope: input.scope,
101
+ project: input.project ?? null,
102
+ },
103
+ embedded,
104
+ commitmentId: written.commitmentId,
105
+ }));
106
+ return ok(output);
107
+ },
108
+ };
109
+ /**
110
+ * search — unified fused retrieval (mcp-design.md 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 (ADR-0005 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.shape,
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
+ /**
173
+ * get_facts — currently-valid facts for a subject, bi-temporally (mcp-design.md
174
+ * JTBD "what is currently true about X"). Calls core getFacts() with the
175
+ * subject/predicate filters and the as_of coordinates (ISO strings coerced to
176
+ * Date at this boundary).
177
+ */
178
+ const getFactsTool = {
179
+ name: 'get_facts',
180
+ requiredScope: MEMORY_READ_SCOPE,
181
+ config: {
182
+ title: 'Get Facts',
183
+ description: 'Currently-valid facts for a subject, with optional bi-temporal time travel. List mode (no subject) returns the most recent facts, bounded by an optional limit (default 50, max 200).',
184
+ inputSchema: factsQueryInputSchema.shape,
185
+ outputSchema: factsToolOutputSchema.shape,
186
+ },
187
+ async handler(args, ctx) {
188
+ const input = factsQueryInputSchema.parse(args);
189
+ // ACCESS GUARD: get_facts is a READ, so read access is asserted BEFORE the db
190
+ // op (self-host allowAllAccess allows all; back-compat when no gate is wired).
191
+ // Mirrors search (which asserts this inside core) and the REST /api/v1/facts
192
+ // guard.
193
+ if (ctx.access)
194
+ await ctx.access.assertRead(ctx.userId);
195
+ const facts = await getFacts(ctx.userId, defined({
196
+ subject: input.subject,
197
+ predicate: input.predicate,
198
+ asOf: toAsOf(input.asOf),
199
+ // Always forward the bounded limit (schema default 50, max 200) so list
200
+ // mode never returns every fact (no-firehose, mcp-design.md).
201
+ limit: input.limit,
202
+ }));
203
+ const output = parseOutput('get_facts', factsToolOutputSchema, {
204
+ facts: facts.map((fact) => ({
205
+ id: fact.id,
206
+ subject: fact.subject,
207
+ predicate: fact.predicate,
208
+ value: fact.value,
209
+ confidence: fact.confidence,
210
+ validFrom: fact.validFrom.toISOString(),
211
+ validTo: fact.validTo?.toISOString() ?? null,
212
+ })),
213
+ count: facts.length,
214
+ });
215
+ return ok(output);
216
+ },
217
+ };
218
+ /**
219
+ * revise — supersede a memory with a corrected successor (mcp-design.md JTBD
220
+ * "correct or update what I know"). Wraps core revise(): closes the
221
+ * predecessor's validity and appends a typed-edge-linked successor in one
222
+ * transaction. The edge intent is constrained to the supersession family
223
+ * ('supersedes' | 'updates') by reviseToolInputSchema — NOT widened to the
224
+ * additive 'extends'/'derives' edges. Embedding is non-blocking, same
225
+ * ack-before-embed as remember (pending with a gateway, off without).
226
+ *
227
+ * COMMITMENT CARRY (revise -> commitment): the
228
+ * obligation follows the live memory. Revising a commitment-type memory MOVES its
229
+ * commitments FSM row to the successor; revising INTO a commitment AUTO-CREATES
230
+ * one (mirrors remember). Either way the live successor is immediately
231
+ * `resolve`-able. Only DEMOTING a commitment to a non-commitment type leaves the
232
+ * row on the superseded predecessor (preserved, not destroyed) pending a product
233
+ * decision. Full matrix in core revise() / packages/db carryCommitment.
234
+ */
235
+ const reviseTool = {
236
+ name: 'revise',
237
+ requiredScope: MEMORY_WRITE_SCOPE,
238
+ config: {
239
+ title: 'Revise',
240
+ description: 'Supersede an existing memory with a corrected successor, linked by a typed edge (supersedes or updates). Never edits in place; append-and-supersede.',
241
+ // FULL `.strict()` object (not `.shape`): the SDK parses strictly at the
242
+ // boundary so a supplied `scope`/`project` reaches the handler and an unknown
243
+ // key is rejected, never silently stripped.
244
+ inputSchema: reviseToolInputSchema,
245
+ outputSchema: reviseToolOutputSchema.shape,
246
+ },
247
+ async handler(args, ctx) {
248
+ // core revise() is THE validation boundary; pass args straight through. It
249
+ // returns the successor id only, so the output echoes the NORMALIZED revise
250
+ // input (scope default + null project applied here) for the rest. Embedding
251
+ // is best-effort and never blocks (same ack-before-embed as remember).
252
+ const input = reviseToolInputSchema.parse(args);
253
+ const gatewayOpts = ctx.gateway === undefined
254
+ ? { access: ctx.access }
255
+ : { gateway: ctx.gateway, budget: ctx.budget, access: ctx.access };
256
+ const written = await revise(ctx.userId, input, 'user_mcp', gatewayOpts);
257
+ void written.embed.settled.catch(() => false);
258
+ const embedded = ctx.gateway === undefined ? 'off' : 'pending';
259
+ const output = parseOutput('revise', reviseToolOutputSchema, {
260
+ memory: {
261
+ id: written.id,
262
+ memoryType: input.memoryType,
263
+ topic: input.topic,
264
+ scope: input.scope,
265
+ project: input.project ?? null,
266
+ },
267
+ embedded,
268
+ });
269
+ return ok(output);
270
+ },
271
+ };
272
+ /**
273
+ * resolve — settle the obligation a memory carries (mcp-design.md JTBD "resolve /
274
+ * unresolve (flag)"). Wraps core resolveByMemoryId(): keys on the MEMORY id the
275
+ * agent already holds and dispatches on what the memory IS. A COMMITMENT memory
276
+ * maps to its commitment via the unique (user_id, memory_id) index and takes an
277
+ * FSM-validated transition (the single `status` enum serves resolve AND unresolve
278
+ * — resolved -> open is legal per COMMITMENT_TRANSITIONS; an illegal pair is a
279
+ * typed invalid_transition result naming from/to only). A BLOCKER memory
280
+ * (blockers are MEMORY-ONLY, no FSM) is ARCHIVED instead — status
281
+ * active -> archived — dropping it from the briefing's active blockers; the
282
+ * passed `status` is ignored for a blocker and the result reports 'archived'.
283
+ */
284
+ const resolveTool = {
285
+ name: 'resolve',
286
+ requiredScope: MEMORY_WRITE_SCOPE,
287
+ config: {
288
+ title: 'Resolve',
289
+ description: 'Settle a memory by its id. A commitment transitions to a target status (open, waiting, resolved, expired) — serves resolve and unresolve (resolved -> open); illegal transitions are rejected. A blocker is archived (status active -> archived) and leaves the active-blocker briefing; the passed status is ignored for blockers and the result reports archived. Commitments AND blockers must be written WITH a project to be resolvable from a project-scoped briefing.',
290
+ inputSchema: resolveToolInputSchema.shape,
291
+ outputSchema: resolveToolOutputSchema.shape,
292
+ },
293
+ async handler(args, ctx) {
294
+ const input = resolveToolInputSchema.parse(args);
295
+ // ACCESS GUARD: resolve mutates a commitment/blocker, so write access is
296
+ // asserted BEFORE the db op (self-host allowAllAccess allows all; back-compat
297
+ // when no gate is wired). remember/revise assert this inside core; resolve's
298
+ // core fn takes no access gate, so the transport asserts it here.
299
+ if (ctx.access)
300
+ await ctx.access.assertWrite(ctx.userId);
301
+ const result = await resolveByMemoryId(ctx.userId, input.memoryId, input.status, 'user_mcp');
302
+ const output = parseOutput('resolve', resolveToolOutputSchema, {
303
+ commitmentId: result.id,
304
+ status: result.status,
305
+ });
306
+ return ok(output);
307
+ },
308
+ };
309
+ /**
310
+ * THE registered tool surface. Length === registered count; the <=12 cap (hard
311
+ * 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).
314
+ *
315
+ * The admin tools are created via a FACTORY given a thunk over {@link TOOLS}, so
316
+ * describe_environment can report the FULL surface (itself included) without a
317
+ * circular import: the thunk closes over TOOLS and is only invoked at REQUEST
318
+ * time, long after this assignment completes.
319
+ */
320
+ export const TOOLS = [
321
+ rememberTool,
322
+ searchTool,
323
+ getFactsTool,
324
+ reviseTool,
325
+ resolveTool,
326
+ // D2 orientation tools (briefing, handoff) — appended from tools-orient.ts so
327
+ // this registry stays the single auditable surface while the file stays thin.
328
+ ...ORIENT_TOOLS,
329
+ // D3 admin tools (configure_scope, describe_environment, review_proposals) —
330
+ // appended via the factory thunk so describe_environment can report the FULL
331
+ // surface (itself included) without a circular import.
332
+ ...createAdminTools(() => TOOLS.map((t) => t.name)),
333
+ ];
334
+ /** Hard ceiling per mcp-design.md / hard rule 8. */
335
+ export const MAX_TOOLS = 12;
336
+ /**
337
+ * Run a tool handler with uniform metrics + typed-error mapping. A KNOWN typed
338
+ * core error (bad input, missing embedding source) becomes an isError result
339
+ * with a class-named message; an UNKNOWN error is logged (crash-safe, no
340
+ * content) and surfaced as a generic failure. The handler itself never logs
341
+ * content (hard rule 6).
342
+ */
343
+ export async function runTool(tool, args, ctx) {
344
+ mcpToolCalls.add(1, { tool_name: tool.name });
345
+ // SCOPE GATE (ADR-0009 §RS, fail-closed): the token MUST satisfy the tool's
346
+ // scope floor. A single scope demands an exact match; an `anyOf` floor passes
347
+ // when the token carries ANY listed scope (per-action tools — the handler then
348
+ // gates the action-specific scope). ctx.scopes is empty when the token had no
349
+ // `scope` claim, so a scopeless token satisfies NO floor and reaches no tool.
350
+ // The transport stays a thin RFC 6750 insufficient_scope analogue: a typed
351
+ // isError naming the missing scope(s), never a 500 and never content. Counted
352
+ // distinctly from invalid_input.
353
+ const floor = tool.requiredScope;
354
+ const required = typeof floor === 'string' ? [floor] : floor.anyOf;
355
+ if (!required.some((scope) => ctx.scopes.includes(scope))) {
356
+ mcpToolErrors.add(1, { tool_name: tool.name, reason_code: 'insufficient_scope' });
357
+ log().warn({ tool_name: tool.name, required_scope: required.join(' | ') }, 'mcp: tool call rejected for insufficient scope');
358
+ return fail(`insufficient scope: ${required.join(' or ')} required`);
359
+ }
360
+ try {
361
+ return await tool.handler(args, ctx);
362
+ }
363
+ catch (err) {
364
+ // KNOWN typed core errors map to a class-named isError result (with the right
365
+ // reason_code + log level, no content) via the extracted ladder. An UNKNOWN
366
+ // error falls through to the generic internal-fault path below.
367
+ const mapped = mapToolError(tool.name, err);
368
+ if (mapped !== undefined)
369
+ return mapped;
370
+ mcpToolErrors.add(1, { tool_name: tool.name, reason_code: 'internal_error' });
371
+ log().error({ tool_name: tool.name, err: err instanceof Error ? err.name : 'unknown' }, 'mcp: tool handler failed');
372
+ return fail('internal error');
373
+ }
374
+ }
375
+ //# sourceMappingURL=tools.js.map
@@ -0,0 +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,8EAA8E;AAC9E,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,EACR,QAAQ,EACR,iBAAiB,EACjB,MAAM,EACN,MAAM,GACP,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,iBAAiB,EAAE,kBAAkB,EAAoB,MAAM,mBAAmB,CAAA;AAE3F,OAAO,EAEL,qBAAqB,EACrB,qBAAqB,EACrB,uBAAuB,EACvB,wBAAwB,EACxB,sBAAsB,EACtB,uBAAuB,EACvB,qBAAqB,EACrB,sBAAsB,EACtB,iBAAiB,EACjB,sBAAsB,GACvB,MAAM,gBAAgB,CAAA;AAGvB,OAAO,EAAE,WAAW,EAAE,MAAM,yBAAyB,CAAA;AACrD,OAAO,EAAE,YAAY,EAAE,MAAM,aAAa,CAAA;AAC1C,wDAAwD;AACxD,iFAAiF;AACjF,qEAAqE;AACrE,OAAO,EAAE,gBAAgB,EAAE,MAAM,kBAAkB,CAAA;AACnD,2DAA2D;AAC3D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AAG,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"}
@@ -0,0 +1,13 @@
1
+ import type { NextFunction, Request, Response } from 'express';
2
+ /**
3
+ * Authenticate the request via X-API-Key. On success binds req.userId + the
4
+ * hashed id into the log context, fires a best-effort last_used_at stamp (never
5
+ * blocking), and continues. A missing/garbage/unknown/revoked key is a uniform
6
+ * 401; any resolver/DB failure is a 503 emitted here (never a leaked 500).
7
+ *
8
+ * Also sets req.apiKeyId to the key prefix segment (`3ng_<PREFIX>_<secret>`)
9
+ * for use by the per-key rate-limiter bucket on /api/*. A malformed key
10
+ * format is logged (redacted — no key material) but does NOT block the request;
11
+ * req.userId is already bound and the route continues without a rate-limit key.
12
+ */
13
+ export declare function apiKeyAuth(req: Request, res: Response, next: NextFunction): void;