@3ngram/server 1.2.7 → 1.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.
@@ -0,0 +1,13 @@
1
+ import type { ToolContext } from './tools.js';
2
+ /** Which facet a completer offers. */
3
+ type Facet = 'scopes' | 'projects';
4
+ /**
5
+ * Build a completer for one facet, bound to a request's tenant.
6
+ *
7
+ * Returns [] rather than throwing on a denied read: a completion is a UI
8
+ * affordance, and a client that cannot complete should degrade to a plain text
9
+ * field, not surface an error mid-keystroke. The important half is that it
10
+ * returns NOTHING — the guards still hold, they just fail quiet.
11
+ */
12
+ export declare function facetCompleter(ctx: ToolContext, facet: Facet): (value: string) => Promise<string[]>;
13
+ export {};
@@ -0,0 +1,67 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // MCP COMPLETIONS — argument autocompletion over the tenant's own facets (issue #104).
3
+ //
4
+ // WHAT IT SOLVES: prompts and tools take scope/project labels, and a client had
5
+ // no way to offer the tenant's ACTUAL values, so users typed them from memory
6
+ // and a typo silently returned nothing.
7
+ //
8
+ // THIN ADAPTER (hard rule 5): core listMemoryFacets already returns the DISTINCT
9
+ // scope + project values for a tenant, already runs withTenant, and is already
10
+ // the source the REST facets route uses. This module adds the guards and the
11
+ // prefix filter; it owns no query.
12
+ //
13
+ // SECURITY — the spec's completion section calls out information disclosure by
14
+ // name, and facet labels ARE tenant data (the REST route guards them for exactly
15
+ // that reason). Three rules, all enforced below:
16
+ // 1. the tenant comes from the closure over verified authInfo, NEVER from the
17
+ // completion request's arguments, which are attacker-controlled;
18
+ // 2. MEMORY_READ_SCOPE is required, fail-closed, like every read tool;
19
+ // 3. the access gate runs before the read, mirroring the REST facets route.
20
+ //
21
+ // RATE LIMITING: the spec expects servers to rate-limit completion specifically.
22
+ // A client may fire one request per keystroke, and each is a separate HTTP
23
+ // request, so per-request memoization buys nothing — the protection is the
24
+ // existing per-user limiter mounted ahead of the handler in routes/mcp.ts.
25
+ //
26
+ // NO CACHE HINTS: completion results are not a cacheable operation in this
27
+ // revision, and they are tenant-specific besides.
28
+ import { listMemoryFacets } from '@3ngram/core';
29
+ import { MEMORY_READ_SCOPE } from '@3ngram/core/auth';
30
+ /**
31
+ * Case-insensitive prefix match on what the user has typed so far. The spec
32
+ * passes the partial value; returning the unfiltered list would make the client
33
+ * do the filtering and waste the round trip.
34
+ *
35
+ * The SDK caps the response at 100 values and sets `total`/`hasMore` itself
36
+ * (createCompletionResult), so this returns everything that matches and lets
37
+ * that boundary do the truncation — one place owns the cap.
38
+ */
39
+ function matching(values, typed) {
40
+ if (typed === '')
41
+ return [...values];
42
+ const needle = typed.toLowerCase();
43
+ return values.filter((value) => value.toLowerCase().startsWith(needle));
44
+ }
45
+ /**
46
+ * Build a completer for one facet, bound to a request's tenant.
47
+ *
48
+ * Returns [] rather than throwing on a denied read: a completion is a UI
49
+ * affordance, and a client that cannot complete should degrade to a plain text
50
+ * field, not surface an error mid-keystroke. The important half is that it
51
+ * returns NOTHING — the guards still hold, they just fail quiet.
52
+ */
53
+ export function facetCompleter(ctx, facet) {
54
+ return async (value) => {
55
+ // SCOPE GATE (fail-closed). ctx.scopes is empty when the token carried no
56
+ // `scope` claim, so a scopeless token completes nothing.
57
+ if (!ctx.scopes.includes(MEMORY_READ_SCOPE))
58
+ return [];
59
+ // ACCESS GUARD before the read — scope/project labels are memory-derived
60
+ // tenant data, which is why the REST facets route guards them too.
61
+ if (ctx.access)
62
+ await ctx.access.assertRead(ctx.userId);
63
+ const facets = await listMemoryFacets(ctx.userId);
64
+ return matching(facets[facet], value);
65
+ };
66
+ }
67
+ //# sourceMappingURL=completions.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"completions.js","sourceRoot":"","sources":["../../src/mcp/completions.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,uFAAuF;AACvF,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,wCAAwC;AACxC,EAAE;AACF,iFAAiF;AACjF,+EA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AAC,CAAA;AACH,CAAC"}
@@ -1,4 +1,5 @@
1
- import type { McpServer } from '@modelcontextprotocol/server';
1
+ import { type McpServer } from '@modelcontextprotocol/server';
2
+ import type { ToolContext } from './tools.js';
2
3
  /**
3
4
  * A code-defined prompt, erased to a name + a server-bound registrar. The arg
4
5
  * shape is captured at the typed {@link definePrompt} call site, so the
@@ -7,7 +8,7 @@ import type { McpServer } from '@modelcontextprotocol/server';
7
8
  */
8
9
  interface RegisterablePrompt {
9
10
  name: string;
10
- register: (server: McpServer) => void;
11
+ register: (server: McpServer, ctx: ToolContext) => void;
11
12
  }
12
13
  /**
13
14
  * THE code-defined prompt surface. Length === registered count; the v1 cap
@@ -25,5 +26,5 @@ export declare const MAX_PROMPTS = 2;
25
26
  * with no transport-route change. The render callback is synchronous and reads
26
27
  * only its validated args (no tenant context needed — a prompt carries no data).
27
28
  */
28
- export declare function registerPrompts(server: McpServer): void;
29
+ export declare function registerPrompts(server: McpServer, ctx: ToolContext): void;
29
30
  export {};
@@ -33,7 +33,9 @@
33
33
  // {@link briefingSelectorSchema} discriminator and validate the debrief `scope`
34
34
  // against the canonical {@link scopeSchema} before rendering.
35
35
  import { briefingModeSchema, briefingSelectorSchema, scopeSchema } from '@3ngram/schema';
36
+ import { completable } from '@modelcontextprotocol/server';
36
37
  import { z } from 'zod';
38
+ import { facetCompleter } from './completions.js';
37
39
  /**
38
40
  * Define a code-defined prompt. The local raw shape is wrapped once into a full
39
41
  * Zod object because SDK v2 registers Standard Schema objects directly.
@@ -44,15 +46,18 @@ import { z } from 'zod';
44
46
  * registerPrompt auto-enables the `prompts` capability.
45
47
  */
46
48
  function definePrompt(prompt) {
47
- // The SDK already validates inbound args against `argsObject` before invoking
48
- // the callback; re-parsing through the same z.object is a zero-risk TYPE BRIDGE
49
- // that yields the exact `z.infer<z.ZodObject<Args>>` `render` declares (the
50
- // SDK's structurally-equal arg type does not generically unify with zod's).
51
- const argsObject = z.object(prompt.config.argsSchema);
52
- const config = { ...prompt.config, argsSchema: argsObject };
53
49
  return {
54
50
  name: prompt.name,
55
- register: (server) => server.registerPrompt(prompt.name, config, (args) => prompt.render(argsObject.parse(args))),
51
+ register: (server, ctx) => {
52
+ // The SDK already validates inbound args against `argsObject` before
53
+ // invoking the callback; re-parsing through the same z.object is a
54
+ // zero-risk TYPE BRIDGE that yields the exact `z.infer<z.ZodObject<Args>>`
55
+ // `render` declares (the SDK's structurally-equal arg type does not
56
+ // generically unify with zod's).
57
+ const argsObject = z.object(prompt.config.argsSchema(ctx));
58
+ const config = { ...prompt.config, argsSchema: argsObject };
59
+ server.registerPrompt(prompt.name, config, (args) => prompt.render(argsObject.parse(args)));
60
+ },
56
61
  };
57
62
  }
58
63
  /** Wrap orienting text as the single-user-message prompt result. */
@@ -82,10 +87,13 @@ const briefingPrompt = definePrompt({
82
87
  config: {
83
88
  title: 'Session briefing',
84
89
  description: 'Orient yourself at the start of a session: call the briefing TOOL with an explicit selector (no unfiltered default) to surface open/overdue commitments, blockers, stale candidates, recent decisions, and preferences.',
85
- argsSchema: {
90
+ // No completable argument: `selector` is a closed enum of selector KINDS,
91
+ // not a scope name, so there is nothing tenant-specific to offer. See the
92
+ // note on debrief below.
93
+ argsSchema: () => ({
86
94
  selector: selectorArgSchema,
87
95
  mode: modeArgSchema.optional(),
88
- },
96
+ }),
89
97
  },
90
98
  render({ selector, mode }) {
91
99
  const mode_ = mode ?? 'brief';
@@ -120,15 +128,25 @@ const debriefPrompt = definePrompt({
120
128
  config: {
121
129
  title: 'Session debrief',
122
130
  description: 'Close a session cleanly: review what happened, then persist what is worth keeping — decisions, commitments, and follow-ups — by calling the remember TOOL for each, and resolve any completed commitments.',
123
- argsSchema: {
131
+ argsSchema: (ctx) => ({
124
132
  // VALIDATED against the canonical {@link scopeSchema} (kebab-case), the SAME
125
133
  // constraint the `remember` TOOL enforces — so a scope the prompt accepts is
126
134
  // a scope `remember` accepts, and the rendered "tag with scope X" line can
127
135
  // never instruct a value the tool would reject (e.g. "Work Notes").
128
- scope: scopeSchema
129
- .optional()
130
- .describe('Optional scope (kebab-case, e.g. work, personal) the session belonged to.'),
131
- },
136
+ //
137
+ // COMPLETABLE (issue #104): the client can offer the tenant's ACTUAL scope
138
+ // names instead of making the user recall them, which is the difference
139
+ // between a typo returning nothing and the right slice being one keystroke
140
+ // away. registerPrompt wrapping ANY completable argument auto-enables the
141
+ // `completions` capability.
142
+ //
143
+ // `completable(...)` wraps the INNER schema and `.optional()` is applied
144
+ // after, not the other way round: the SDK unwraps an optional before
145
+ // testing for completability (handlePromptCompletion), and
146
+ // CompleteCallback infers its value type from the schema — wrapping the
147
+ // optional would demand a completer over `string | undefined`.
148
+ scope: completable(scopeSchema.describe('Optional scope (kebab-case, e.g. work, personal) the session belonged to.'), facetCompleter(ctx, 'scopes')).optional(),
149
+ }),
132
150
  },
133
151
  render({ scope }) {
134
152
  const scopeLine = scope === undefined
@@ -166,9 +184,9 @@ export const MAX_PROMPTS = 2;
166
184
  * with no transport-route change. The render callback is synchronous and reads
167
185
  * only its validated args (no tenant context needed — a prompt carries no data).
168
186
  */
169
- export function registerPrompts(server) {
187
+ export function registerPrompts(server, ctx) {
170
188
  for (const prompt of PROMPTS) {
171
- prompt.register(server);
189
+ prompt.register(server, ctx);
172
190
  }
173
191
  }
174
192
  //# sourceMappingURL=prompts.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"prompts.js","sourceRoot":"","sources":["../../src/mcp/prompts.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,0EAA0E;AAC1E,EAAE;AACF,gFAAgF;AAChF,8EAA8E;AAC9E,kFAAkF;AAClF,gFAAgF;AAChF,iFAAiF;AACjF,6DAA6D;AAC7D,EAAE;AACF,iFAAiF;AACjF,gFAAgF;AAChF,kFAAkF;AAClF,+EAA+E;AAC/E,gFAAgF;AAChF,gFAAgF;AAChF,2EAA2E;AAC3E,EAAE;AACF,8FAA8F;AAC9F,+EAA+E;AAC/E,kBAAkB;AAClB,EAAE;AACF,+EAA+E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AMG;AACH,MAAM,UAAU,eAAe,CAAC,MAAiB,EAAE,GAAgB;IACjE,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,MAAM,CAAC,QAAQ,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC9B,CAAC;AACH,CAAC"}
@@ -0,0 +1,43 @@
1
+ import { type McpServer } from '@modelcontextprotocol/server';
2
+ import type { ToolContext } from './tools.js';
3
+ /**
4
+ * The URI template clients complete. One variable, `{id}`, a memory uuid.
5
+ *
6
+ * SCHEME IS `threengram`, NOT `3ngram`. RFC 3986 requires a scheme to begin with
7
+ * a letter (`scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`), so
8
+ * `3ngram://…` is not a parseable URI at all — `new URL('3ngram://memory/x')`
9
+ * throws. The SDK hands the read callback a real `URL`, so a digit-leading
10
+ * scheme could never have worked; issue #105 and the first draft of
11
+ * docs/concepts/mcp-resources.mdx both specified one. Do not "fix" this back.
12
+ *
13
+ * The `memory` authority segment leaves room for a future
14
+ * `threengram://thread/{name}` without re-cutting the namespace.
15
+ */
16
+ export declare const MEMORY_RESOURCE_TEMPLATE = "threengram://memory/{id}";
17
+ /**
18
+ * TTL for a memory body. DELIBERATELY ITS OWN CONSTANT, not a reuse of
19
+ * MCP_CATALOG_CACHE_TTL_MS: the catalogs go stale on a deployment, a memory body
20
+ * essentially never does, and sharing one number means whoever retunes
21
+ * deployment freshness silently retunes memory caching too.
22
+ *
23
+ * 24 hours is long precisely because the projection below carries nothing that
24
+ * can change (see MEMORY_RESOURCE_FIELDS). The bound on how long it can be is
25
+ * the PII-erasure path, which rewrites content — that is closed by erasure
26
+ * revoking every OAuth token in the same transaction, so a `private` entry
27
+ * cannot be reused by a caller whose token no longer authenticates.
28
+ */
29
+ export declare const MEMORY_RESOURCE_CACHE_TTL_MS: number;
30
+ /**
31
+ * Register `threengram://memory/{id}`. registerResource AUTO-ENABLES the `resources`
32
+ * capability, so resources/templates/list + resources/read are served with no
33
+ * transport change — both stay Bearer-gated by routes/mcp.ts exactly like
34
+ * tools/*, and the per-read scope gate below is the resource analogue of
35
+ * runTool's.
36
+ *
37
+ * `list: undefined` is passed EXPLICITLY (the SDK requires the key so nobody
38
+ * forgets it): enumerating a tenant's corpus is the firehose the no-firehose
39
+ * rule exists to prevent, so `resources/list` returns nothing for this template.
40
+ */
41
+ export declare function registerResources(server: McpServer, ctx: ToolContext): void;
42
+ /** The projection's field list, exported so a test can assert it never widens. */
43
+ export declare const MEMORY_RESOURCE_PROJECTION: readonly string[];
@@ -0,0 +1,156 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // MCP RESOURCES — `threengram://memory/{id}` (issue #105).
3
+ //
4
+ // Design and the reasoning behind every decision here: docs/concepts/mcp-resources.mdx.
5
+ // Read it before changing this file; the payload rule below is load-bearing, not
6
+ // a shape someone picked.
7
+ //
8
+ // WHY A RESOURCE AT ALL: `resources/read` is CACHEABLE on 2026-07-28. A client
9
+ // that pulled a `truncated: true` search hit can cache the full body instead of
10
+ // re-calling get_memories every session. Resources also cost nothing against the
11
+ // 12-tool cap (hard rule 8).
12
+ //
13
+ // ADDRESSING — the id, not a version. `revise` does not modify a memory: it
14
+ // closes the predecessor's validity and APPENDS a successor with a NEW id
15
+ // (packages/db/src/memory-revise.ts). A successor is a different memory, so this
16
+ // URI is already version-addressed by construction; there is no version column
17
+ // for a second path segment to name.
18
+ //
19
+ // LAYERING: zero business logic (hard rule 5). The read validates the id at the
20
+ // schema boundary, asserts scope + access, calls the COMPLETE core service
21
+ // (which runs withTenant internally), and projects the result.
22
+ import { log } from '@3ngram/config';
23
+ import { getMemoryById, MemoryNotFoundError } from '@3ngram/core';
24
+ import { MEMORY_READ_SCOPE } from '@3ngram/core/auth';
25
+ import { ResourceTemplate } from '@modelcontextprotocol/server';
26
+ import { z } from 'zod';
27
+ /**
28
+ * The URI template clients complete. One variable, `{id}`, a memory uuid.
29
+ *
30
+ * SCHEME IS `threengram`, NOT `3ngram`. RFC 3986 requires a scheme to begin with
31
+ * a letter (`scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )`), so
32
+ * `3ngram://…` is not a parseable URI at all — `new URL('3ngram://memory/x')`
33
+ * throws. The SDK hands the read callback a real `URL`, so a digit-leading
34
+ * scheme could never have worked; issue #105 and the first draft of
35
+ * docs/concepts/mcp-resources.mdx both specified one. Do not "fix" this back.
36
+ *
37
+ * The `memory` authority segment leaves room for a future
38
+ * `threengram://thread/{name}` without re-cutting the namespace.
39
+ */
40
+ export const MEMORY_RESOURCE_TEMPLATE = 'threengram://memory/{id}';
41
+ /**
42
+ * TTL for a memory body. DELIBERATELY ITS OWN CONSTANT, not a reuse of
43
+ * MCP_CATALOG_CACHE_TTL_MS: the catalogs go stale on a deployment, a memory body
44
+ * essentially never does, and sharing one number means whoever retunes
45
+ * deployment freshness silently retunes memory caching too.
46
+ *
47
+ * 24 hours is long precisely because the projection below carries nothing that
48
+ * can change (see MEMORY_RESOURCE_FIELDS). The bound on how long it can be is
49
+ * the PII-erasure path, which rewrites content — that is closed by erasure
50
+ * revoking every OAuth token in the same transaction, so a `private` entry
51
+ * cannot be reused by a caller whose token no longer authenticates.
52
+ */
53
+ export const MEMORY_RESOURCE_CACHE_TTL_MS = 24 * 60 * 60_000;
54
+ /** Reject a non-uuid `{id}` before it reaches core (one validation boundary). */
55
+ const memoryIdSchema = z.uuid();
56
+ /**
57
+ * The IMMUTABLE PROJECTION — the entire reason the TTL can be long.
58
+ *
59
+ * These are the columns no ordinary write path can change. Enumerating every
60
+ * UPDATE against `memories` (revise, import, proposals-apply, embedding
61
+ * backfill, account-delete) shows the rest is lifecycle state.
62
+ *
63
+ * `status`, `validTo`, `commitmentStatus`, and `tags` are OMITTED ON PURPOSE.
64
+ * They are exactly what supersession, archiving, and `resolve` move. Adding any
65
+ * of them turns a correct cache into one that serves wrong answers for up to a
66
+ * day, and forces the TTL down to where this feature stops paying for itself.
67
+ * A client that needs "is this still current" asks `get_memories` or `search` —
68
+ * tool results are never cacheable, so they answer about right now.
69
+ *
70
+ * IF YOU ARE ABOUT TO ADD A FIELD HERE: check it against that list first, and
71
+ * read docs/concepts/mcp-resources.mdx. Widening this projection is a design
72
+ * change, not a tweak.
73
+ */
74
+ const MEMORY_RESOURCE_FIELDS = [
75
+ 'id',
76
+ 'memoryType',
77
+ 'topic',
78
+ 'content',
79
+ 'contentLength',
80
+ 'scope',
81
+ 'project',
82
+ 'recordedAt',
83
+ ];
84
+ /**
85
+ * Register `threengram://memory/{id}`. registerResource AUTO-ENABLES the `resources`
86
+ * capability, so resources/templates/list + resources/read are served with no
87
+ * transport change — both stay Bearer-gated by routes/mcp.ts exactly like
88
+ * tools/*, and the per-read scope gate below is the resource analogue of
89
+ * runTool's.
90
+ *
91
+ * `list: undefined` is passed EXPLICITLY (the SDK requires the key so nobody
92
+ * forgets it): enumerating a tenant's corpus is the firehose the no-firehose
93
+ * rule exists to prevent, so `resources/list` returns nothing for this template.
94
+ */
95
+ export function registerResources(server, ctx) {
96
+ server.registerResource('memory', new ResourceTemplate(MEMORY_RESOURCE_TEMPLATE, { list: undefined }), {
97
+ title: 'Memory',
98
+ description: 'The stored body of one memory by id, addressed as threengram://memory/{id}. Carries only the fields that never change after write (content, topic, type, scope, project, recordedAt) so it can be cached; lifecycle state (status, validity, commitment status, tags) is deliberately absent — read search or get_memories for that.',
99
+ mimeType: 'application/json',
100
+ // cacheScope MUST be private: this is tenant data, and the spec is
101
+ // explicit that a `public` result from an authenticated endpoint may be
102
+ // served across authorization contexts. `public` here would be a
103
+ // cross-tenant disclosure with a cache in front of it.
104
+ cacheHint: { ttlMs: MEMORY_RESOURCE_CACHE_TTL_MS, cacheScope: 'private' },
105
+ }, async (uri, variables) => {
106
+ // SCOPE GATE (fail-closed), the resource analogue of runTool's. ctx.scopes
107
+ // is empty when the token carried no `scope` claim, so a scopeless token
108
+ // satisfies nothing and reads no memory.
109
+ if (!ctx.scopes.includes(MEMORY_READ_SCOPE)) {
110
+ throw new Error(`insufficient scope: ${MEMORY_READ_SCOPE} required`);
111
+ }
112
+ // `variables` is the SDK's own expansion of the URI template, so the id
113
+ // never gets hand-parsed out of a path. The id is caller-supplied; the
114
+ // TENANT never is — it comes from the closure over the verified authInfo
115
+ // (routes/mcp.ts requireUserId), the same path every tool uses.
116
+ const raw = variables.id;
117
+ const id = memoryIdSchema.safeParse(Array.isArray(raw) ? raw[0] : raw);
118
+ // A malformed id is reported EXACTLY like a missing one: telling the
119
+ // caller "that is not a uuid" versus "no such memory" is a distinction
120
+ // only an oracle needs.
121
+ if (!id.success)
122
+ throw new MemoryNotFoundError(String(raw));
123
+ // ACCESS GUARD: this exports memory content, so read access is asserted
124
+ // BEFORE the db op — mirrors get_memories / handoff / get_facts.
125
+ if (ctx.access)
126
+ await ctx.access.assertRead(ctx.userId);
127
+ // core getMemoryById runs withTenant (RLS) and throws MemoryNotFoundError
128
+ // for an id that is unknown OR belongs to another tenant. That collapse is
129
+ // the point: a cross-tenant id must be INDISTINGUISHABLE from a missing
130
+ // one, or this URI becomes an existence oracle for other tenants' ids.
131
+ const memory = await getMemoryById(ctx.userId, id.data);
132
+ const body = {
133
+ id: memory.id,
134
+ memoryType: memory.memoryType,
135
+ topic: memory.topic,
136
+ content: memory.content,
137
+ contentLength: memory.content.length,
138
+ scope: memory.scope,
139
+ project: memory.project,
140
+ recordedAt: memory.recordedAt.toISOString(),
141
+ };
142
+ log().debug({ resource: 'memory' }, 'mcp: resource read');
143
+ return {
144
+ contents: [
145
+ {
146
+ uri: uri.href,
147
+ mimeType: 'application/json',
148
+ text: JSON.stringify(body),
149
+ },
150
+ ],
151
+ };
152
+ });
153
+ }
154
+ /** The projection's field list, exported so a test can assert it never widens. */
155
+ export const MEMORY_RESOURCE_PROJECTION = MEMORY_RESOURCE_FIELDS;
156
+ //# sourceMappingURL=resources.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resources.js","sourceRoot":"","sources":["../../src/mcp/resources.ts"],"names":[],"mappings":"AAAA,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M,CAAC,KAAK;YACnB,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,aAAa,EAAE,MAAM,CAAC,OAAO,CAAC,MAAM;YACpC,KAAK,EAAE,MAAM,CAAC,KAAK;YACnB,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,UAAU,EAAE,MAAM,CAAC,UAAU,CAAC,WAAW,EAAE;SAC5C,CAAA;QACD,GAAG,EAAE,CAAC,KAAK,CAAC,EAAE,QAAQ,EAAE,QAAQ,EAAE,EAAE,oBAAoB,CAAC,CAAA;QACzD,OAAO;YACL,QAAQ,EAAE;gBACR;oBACE,GAAG,EAAE,GAAG,CAAC,IAAI;oBACb,QAAQ,EAAE,kBAAkB;oBAC5B,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC;iBAC3B;aACF;SACF,CAAA;IACH,CAAC,CACF,CAAA;AACH,CAAC;AAED,kFAAkF;AAClF,MAAM,CAAC,MAAM,0BAA0B,GAAsB,sBAAsB,CAAA"}
@@ -1,10 +1,27 @@
1
1
  import { McpServer } from '@modelcontextprotocol/server';
2
2
  import { type ToolContext } from './tools.js';
3
3
  /**
4
- * Tool and prompt definitions change only with a server deployment. One hour
5
- * avoids reconnect refetches without making a rolling deployment's old catalog
6
- * sticky for long. Both lists are identical across tenants, so shared caching
7
- * is safe; tool authorization still runs on every tools/call.
4
+ * Natural-language usage policy surfaced to the model via
5
+ * `DiscoverResult.instructions`. It is the ONLY place an agent learns when to
6
+ * reach for one tool over another — the 11 tool descriptions each explain
7
+ * themselves, with no cross-tool framing.
8
+ *
9
+ * TREAT AS POLICY, NOT DOCUMENTATION. Clients that surface this prepend it to
10
+ * model context on every session, so it competes with the tool descriptions for
11
+ * attention. Every sentence here has to earn its place; the failure mode this
12
+ * targets is "the agent has the tools but never writes anything worth keeping",
13
+ * which is a usage problem, not a schema problem.
14
+ *
15
+ * This is a compression of the JTBD table in docs/concepts/mcp-design.mdx.
16
+ * Change them together — the doc links back here for exactly that reason.
17
+ */
18
+ export declare const SERVER_INSTRUCTIONS = "3ngram is the user's persistent memory across sessions and tools.\n\nStart a session with `briefing` to load what is already known. Before saying something is not known, not decided, or not recorded, `search` for it \u2014 this corpus outlives the conversation you can see.\n\nMemory is append-only. Never rewrite or delete: use `revise` to supersede a memory that has become wrong, and `resolve` to settle a commitment or blocker. Superseding keeps the old version readable as history.\n\nWrite decisions, commitments, blockers, and stated preferences \u2014 the things that would be expensive to rediscover. Do not write transcript noise, restatements of what the user just said, or anything re-derivable from the code.\n\nScope and project decide what later reads return, so set them when you `remember`: a memory written with no project will not appear in that project's briefing.";
19
+ /**
20
+ * Tool definitions, prompt definitions, and the discovery advertisement change
21
+ * only with a server deployment. One hour avoids reconnect refetches without
22
+ * making a rolling deployment's old catalog sticky for long. All three payloads
23
+ * are identical across tenants, so shared caching is safe; tool authorization
24
+ * still runs on every tools/call.
8
25
  */
9
26
  export declare const MCP_CATALOG_CACHE_TTL_MS: number;
10
27
  /**
@@ -8,15 +8,41 @@
8
8
  import { McpServer } from '@modelcontextprotocol/server';
9
9
  import { SERVER_VERSION } from '../version.js';
10
10
  import { registerPrompts } from './prompts.js';
11
+ import { registerResources } from './resources.js';
11
12
  import { runTool, TOOLS } from './tools.js';
12
13
  // `version` derives from package.json (see ../version.ts) so the `initialize`
13
14
  // result always matches the published package version and never skews.
14
15
  const SERVER_INFO = { name: '3ngram', version: SERVER_VERSION };
15
16
  /**
16
- * Tool and prompt definitions change only with a server deployment. One hour
17
- * avoids reconnect refetches without making a rolling deployment's old catalog
18
- * sticky for long. Both lists are identical across tenants, so shared caching
19
- * is safe; tool authorization still runs on every tools/call.
17
+ * Natural-language usage policy surfaced to the model via
18
+ * `DiscoverResult.instructions`. It is the ONLY place an agent learns when to
19
+ * reach for one tool over another — the 11 tool descriptions each explain
20
+ * themselves, with no cross-tool framing.
21
+ *
22
+ * TREAT AS POLICY, NOT DOCUMENTATION. Clients that surface this prepend it to
23
+ * model context on every session, so it competes with the tool descriptions for
24
+ * attention. Every sentence here has to earn its place; the failure mode this
25
+ * targets is "the agent has the tools but never writes anything worth keeping",
26
+ * which is a usage problem, not a schema problem.
27
+ *
28
+ * This is a compression of the JTBD table in docs/concepts/mcp-design.mdx.
29
+ * Change them together — the doc links back here for exactly that reason.
30
+ */
31
+ export const SERVER_INSTRUCTIONS = `3ngram is the user's persistent memory across sessions and tools.
32
+
33
+ Start a session with \`briefing\` to load what is already known. Before saying something is not known, not decided, or not recorded, \`search\` for it — this corpus outlives the conversation you can see.
34
+
35
+ Memory is append-only. Never rewrite or delete: use \`revise\` to supersede a memory that has become wrong, and \`resolve\` to settle a commitment or blocker. Superseding keeps the old version readable as history.
36
+
37
+ Write decisions, commitments, blockers, and stated preferences — the things that would be expensive to rediscover. Do not write transcript noise, restatements of what the user just said, or anything re-derivable from the code.
38
+
39
+ Scope and project decide what later reads return, so set them when you \`remember\`: a memory written with no project will not appear in that project's briefing.`;
40
+ /**
41
+ * Tool definitions, prompt definitions, and the discovery advertisement change
42
+ * only with a server deployment. One hour avoids reconnect refetches without
43
+ * making a rolling deployment's old catalog sticky for long. All three payloads
44
+ * are identical across tenants, so shared caching is safe; tool authorization
45
+ * still runs on every tools/call.
20
46
  */
21
47
  export const MCP_CATALOG_CACHE_TTL_MS = 60 * 60_000;
22
48
  /**
@@ -32,15 +58,40 @@ export const MCP_CATALOG_CACHE_TTL_MS = 60 * 60_000;
32
58
  */
33
59
  export function createMcpServer(ctx) {
34
60
  const server = new McpServer(SERVER_INFO, {
61
+ instructions: SERVER_INSTRUCTIONS,
62
+ // The 2026-07-28 spec requires cache hints on every cacheable result, and
63
+ // server/discover is on that list. Without a CONFIGURED hint the SDK does
64
+ // not leave the fields off — its 2026 codec fills them from its own
65
+ // defaults (ttlMs 0, cacheScope 'private'), so discovery advertises itself
66
+ // as immediately stale and clients re-probe on every reconnect.
67
+ // 'public' is correct for the same reason it is correct on the catalogs:
68
+ // DiscoverResult carries supportedVersions, capabilities, and serverInfo —
69
+ // no tenant data. It shares the catalog TTL because it goes stale on
70
+ // exactly the same trigger: a deployment.
35
71
  cacheHints: {
72
+ 'server/discover': { ttlMs: MCP_CATALOG_CACHE_TTL_MS, cacheScope: 'public' },
36
73
  'tools/list': { ttlMs: MCP_CATALOG_CACHE_TTL_MS, cacheScope: 'public' },
37
74
  'prompts/list': { ttlMs: MCP_CATALOG_CACHE_TTL_MS, cacheScope: 'public' },
75
+ // The TEMPLATE list is a static descriptor — one uri template and its
76
+ // human-readable metadata, identical for every tenant — so it caches
77
+ // 'public' alongside the other catalogs and changes on the same trigger.
78
+ // The RESOURCE BODIES are the opposite: resources/read carries tenant
79
+ // data and is pinned 'private' with its own long TTL at the registration
80
+ // site (see resources.ts). Per-resource hints win over this map field by
81
+ // field, so the two never collide.
82
+ 'resources/templates/list': { ttlMs: MCP_CATALOG_CACHE_TTL_MS, cacheScope: 'public' },
38
83
  },
39
84
  });
40
85
  for (const tool of TOOLS) {
41
86
  server.registerTool(tool.name, tool.config, (args) => runTool(tool, args, ctx));
42
87
  }
43
- registerPrompts(server);
88
+ // Prompts now take the request ToolContext too: their TEXT still carries no
89
+ // tenant data, but a completable argument reads the tenant's own facets.
90
+ registerPrompts(server, ctx);
91
+ // Resources need the per-request ToolContext: unlike prompts (static text, no
92
+ // tenant data), a resource read returns memory content and therefore enforces
93
+ // the same tenant + scope + access guards a read tool does.
94
+ registerResources(server, ctx);
44
95
  return server;
45
96
  }
46
97
  //# sourceMappingURL=server.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/mcp/server.ts"],"names":[],"mappings":"AAAA,sCAAsC;AACtC,6EAA6E;AAC7E,+EAA+E;AAC/E,gFAAgF;AAChF,wEAAwE;AACxE,gFAAgF;AAChF,gFAAgF;AAChF,OAAO,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAA;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,eAAe,CAAA;AAC9C,OAAO,EAAE,eAAe,EAAE,MAAM,cAAc,CAAA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CAAC,OAAO,CAAC,IAAI,EAAE,IAAI,EAAE,GAAG,CAAC,CAAC,CAAA;IAC1F,CAAC;IACD,4EAA4E;IAC5E,yEAAyE;IACzE,eAAe,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC5B,8EAA8E;IAC9E,8EAA8E;IAC9E,4DAA4D;IAC5D,iBAAiB,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IAC9B,OAAO,MAAM,CAAA;AACf,CAAC"}
@@ -0,0 +1,11 @@
1
+ import type { ToolAnnotations } from '@modelcontextprotocol/server';
2
+ /**
3
+ * Annotations for a read-only tool: it never mutates, and repeating it yields
4
+ * the same answer. `destructiveHint` is deliberately omitted — the spec only
5
+ * gives it meaning when `readOnlyHint` is false.
6
+ *
7
+ * `openWorldHint: false` holds for EVERY 3ngram tool: each one operates on the
8
+ * tenant's own corpus, not an open external world. The embedding gateway is an
9
+ * implementation detail of a write, not an open-world interaction.
10
+ */
11
+ export declare const READ_ONLY_ANNOTATIONS: ToolAnnotations;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Annotations for a read-only tool: it never mutates, and repeating it yields
3
+ * the same answer. `destructiveHint` is deliberately omitted — the spec only
4
+ * gives it meaning when `readOnlyHint` is false.
5
+ *
6
+ * `openWorldHint: false` holds for EVERY 3ngram tool: each one operates on the
7
+ * tenant's own corpus, not an open external world. The embedding gateway is an
8
+ * implementation detail of a write, not an open-world interaction.
9
+ */
10
+ export const READ_ONLY_ANNOTATIONS = {
11
+ readOnlyHint: true,
12
+ idempotentHint: true,
13
+ openWorldHint: false,
14
+ };
15
+ //# sourceMappingURL=tool-annotations.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tool-annotations.js","sourceRoot":"","sources":["../../src/mcp/tool-annotations.ts"],"names":[],"mappings":"AAeA;;;;;;;;GAQG;AACH,MAAM,CAAC,MAAM,qBAAqB,GAAoB;IACpD,YAAY,EAAE,IAAI;IAClB,cAAc,EAAE,IAAI;IACpB,aAAa,EAAE,KAAK;CACrB,CAAA"}