@mnemahq/mcp 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE.md ADDED
@@ -0,0 +1,83 @@
1
+ # Mnema Community License
2
+
3
+ _Version 1.0_
4
+
5
+ This Community License is based on the "Sustainable Use License" fair-code model.
6
+ It governs the **public core** of Mnema (the `mnema` repository). The enterprise
7
+ modules (`mnema-ee`) are covered by a separate proprietary license and are **not**
8
+ distributed under this license.
9
+
10
+ ## Acceptance
11
+
12
+ By using the software, you agree to all of the terms and conditions below.
13
+
14
+ ## Copyright License
15
+
16
+ The licensor grants you a non-exclusive, royalty-free, worldwide, non-sublicensable,
17
+ non-transferable license to use, copy, distribute, make available, and prepare
18
+ derivative works of the software, in each case subject to the limitations and
19
+ conditions below.
20
+
21
+ ## Limitations
22
+
23
+ **Internal business purposes and personal use.** You may use the software for your
24
+ own internal business purposes or for personal use, and you may make the software
25
+ available to third parties **only** as part of a product or service you provide that
26
+ is not itself the software (or a modified version of it).
27
+
28
+ You may **not**, without a separate commercial agreement with the licensor:
29
+
30
+ 1. **Host or offer the software as a service** to third parties (commercial hosting,
31
+ SaaS, or a multi-tenant deployment operated for others).
32
+ 2. **Resell, sublicense, or redistribute the software as a product** whose primary
33
+ value is the software itself.
34
+ 3. **Embed the software** into a commercial product offered to third parties where
35
+ the software provides the core functionality.
36
+ 4. Remove or obscure any licensing, copyright, or other notices.
37
+
38
+ Using the software for **internal tooling, self-hosting for your own team or
39
+ organisation, evaluation, education, or development** is always permitted.
40
+
41
+ ## Trademarks
42
+
43
+ This license does not grant you any right to use the licensor's trademarks, trade
44
+ names, or logos (including "Mnema"). Forks may use the code; they may not use the name.
45
+
46
+ ## Patents
47
+
48
+ The licensor grants you a license, under any patent claims the licensor can license,
49
+ to make, use, sell, and import the software, limited to the same scope as the
50
+ copyright license above. This patent license terminates if you assert a patent claim
51
+ against anyone alleging the software infringes a patent.
52
+
53
+ ## Notices
54
+
55
+ You must ensure that anyone who gets a copy of any part of the software from you also
56
+ gets a copy of these terms, and you must retain all copyright and licensing notices.
57
+
58
+ ## No Other Rights
59
+
60
+ These terms do not imply any licenses other than those expressly granted here.
61
+
62
+ ## Termination
63
+
64
+ If you use the software in violation of these terms, such use is not licensed, and
65
+ your licenses will automatically terminate. If the licensor provides you notice of a
66
+ violation and you cease the violation within 30 days, your licenses are reinstated.
67
+
68
+ ## No Liability & As-Is
69
+
70
+ **As far as the law allows, the software comes "as is", without any warranty or
71
+ condition, and the licensor will not be liable to you for any damages arising out of
72
+ these terms or the use or nature of the software, under any kind of legal claim.**
73
+
74
+ ## Definitions
75
+
76
+ The **licensor** is the entity offering these terms. The **software** is the software
77
+ the licensor makes available under these terms, including any portion of it. **You**
78
+ refers to the individual or entity agreeing to these terms.
79
+
80
+ ---
81
+
82
+ For commercial hosting, embedding, or reselling rights — or for the enterprise
83
+ (`mnema-ee`) modules — contact the licensor for a commercial agreement.
package/README.md CHANGED
@@ -1,3 +1,164 @@
1
- # Temporary Holding Version
1
+ # @mnemahq/mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Call Mnema's MCP tools from an app — transport, typed errors, and the two-phase protocols.
4
+
5
+ ```bash
6
+ npm i @mnemahq/mcp
7
+ ```
8
+
9
+ ## Which package do you want?
10
+
11
+ There are two Mnema clients. Pick before you write anything.
12
+
13
+ | | `@mnemahq/sdk` | `@mnemahq/mcp` |
14
+ |---|---|---|
15
+ | Surface | REST — docs, tasks, projects, sessions, PRs | all ~116 MCP tools |
16
+ | Typed | yes, hand-written | errors and protocols yes; tool payloads `unknown` |
17
+ | Pagination | built in | per-tool cursors |
18
+ | Has | paginated reads your app renders | meetings, flow **execution**, DockMaster ops, charts, decisions, cost, RACI, notifications |
19
+
20
+ > **Rendering a list of things? Reach for `@mnemahq/sdk` first.
21
+ > Anything an agent does, anything with an approval, or a family REST does not have? This package.**
22
+
23
+ Most real apps use both.
24
+
25
+ ## Quickstart
26
+
27
+ ```ts
28
+ import { createMnema } from "@mnemahq/mcp";
29
+
30
+ const mnema = createMnema({
31
+ baseUrl: process.env.MNEMA_BASE_URL!, // https://api.theboringpeople.in
32
+ apiKey: process.env.MNEMA_API_KEY!, // mnema_api_… — server side only
33
+ });
34
+
35
+ const me = await mnema.call("whoami");
36
+ ```
37
+
38
+ If that returns your name and workspace, you are connected. `createMnema` sets
39
+ `"browser": false` in the package manifest, so a bundler complains rather than shipping your
40
+ key to a browser.
41
+
42
+ ## Check the tools exist before you depend on them
43
+
44
+ The tool surface **varies by workspace mode**. A `knowledge` workspace hides tasks, sessions
45
+ and cost; a `dev_project` workspace shows them. An app that assumes `get_next_task` exists
46
+ works perfectly in testing and dies at a customer.
47
+
48
+ ```ts
49
+ await mnema.assertTools(["get_next_task", "claim_task", "complete_task"]);
50
+ // throws MnemaToolMissingError, naming exactly what is missing
51
+ ```
52
+
53
+ Put it in your startup path, not in a request handler.
54
+
55
+ ## The three protocols that fail silently
56
+
57
+ These are why the package exists. None of them throws when you get them wrong.
58
+
59
+ ### 1. Writes are proposals
60
+
61
+ Nothing is written until a person approves. `confirm` takes who approved — the argument
62
+ exists so an automated path cannot quietly pretend to be a person.
63
+
64
+ ```ts
65
+ const draft = await mnema.propose(
66
+ "propose_doc_write",
67
+ { operation: "append", doc_id: docId, markdown: summary },
68
+ summary, // what you show the user
69
+ );
70
+
71
+ if (draft.isExpired) { /* propose again */ }
72
+ // … after the user clicks Approve in YOUR UI:
73
+ await draft.confirm(session.user.email);
74
+ ```
75
+
76
+ Catch `MnemaProposalExpiredError` and re-propose. It means a person took longer than the token
77
+ lasts, which is ordinary — not a failure of the write.
78
+
79
+ Some deployments commit directly and return no token; the handle detects that and `confirm()`
80
+ returns the id without a second call.
81
+
82
+ ### 2. Ops requests return a *pending run*, never a result
83
+
84
+ Your key can never approve its own request. A person approves it inside Mnema.
85
+
86
+ ```ts
87
+ const run = await mnema.requestRun("request_deploy", { app: "quickquote", reason });
88
+ // run.runId — tell the user where to look
89
+
90
+ // In a WORKER, never a request handler — this waits on a human.
91
+ const out = await run.waitForDecision({ pollMs: 15_000, timeoutMs: 30 * 60_000 });
92
+ if (out.timedOut) { /* still pending — NOT failed */ }
93
+ else if (out.status === "succeeded") { /* … */ }
94
+ ```
95
+
96
+ `timedOut` is deliberately separate from `failed`. Reporting a deploy as broken because nobody
97
+ has looked at it yet is worse than saying nothing.
98
+
99
+ ### 3. Token counts are deltas
100
+
101
+ `report_usage` and `complete_task` want the tokens **since the last report**. Every model SDK
102
+ hands back cumulative usage, so passing `response.usage` straight through double-counts — and
103
+ keeps double-counting. Nothing errors; the cost page is just wrong, by a growing amount.
104
+
105
+ ```ts
106
+ const meter = mnema.usageMeter();
107
+
108
+ for (const turn of turns) {
109
+ const res = await anthropic.messages.create({ /* … */ });
110
+ meter.observe(res.usage); // snake_case or camelCase, both accepted
111
+ }
112
+
113
+ await mnema.call("complete_task", {
114
+ taskId, sessionId, githubPrUrl: prUrl,
115
+ ...meter.delta(), // deltas, not totals
116
+ });
117
+ ```
118
+
119
+ ## Errors you can branch on
120
+
121
+ ```ts
122
+ import {
123
+ MnemaUnauthorizedError, // token rejected — reconnect, do not retry
124
+ MnemaForbiddenError, // .requiredScope names the missing scope
125
+ MnemaSubscriptionError, // .billingUrl is where the person fixes it
126
+ MnemaToolError, // the tool ran and refused — an answer, not an outage
127
+ MnemaTransportError, // no answer — safe to retry a READ
128
+ MnemaToolMissingError, // .missing lists the tools this workspace lacks
129
+ MnemaProposalExpiredError,
130
+ } from "@mnemahq/mcp";
131
+ ```
132
+
133
+ The split between `MnemaToolError` and `MnemaTransportError` is the one that matters: only the
134
+ second is ever safe to retry, and only reads at that. **A retried create without an
135
+ `idempotency_key` is a duplicate.**
136
+
137
+ ## Typed tool payloads
138
+
139
+ `call()` returns `unknown` today. That is deliberate — it is not a confident lie.
140
+
141
+ 92 of the ~116 tools advertise a JSON Schema for their output in `tools/list`, enforced at
142
+ runtime by the server, so typed bindings are **generatable** rather than hand-written. When
143
+ you generate them, two rules carry over from the server's own generator:
144
+
145
+ 1. **No fallback type.** An unresolvable field is an error, never silently `string`. The
146
+ server learned this the hard way: a `return 'string'` fallback published 36 object, array,
147
+ boolean and numeric fields as `string`, through three production incidents.
148
+ 2. **Every field is `T | null`, not `T?`.** Handlers return `null` constantly to mean "no
149
+ result". `.optional()` admits `undefined` and rejects `null`; typing these as merely
150
+ optional reproduces a bug that already broke `list_docs` and nine task tools in production.
151
+
152
+ ## Rules the tools enforce
153
+
154
+ | Area | Rule |
155
+ |---|---|
156
+ | `user_confirmed` | Required by `create_project`, `create_folder`, `create_flow`, `add_flow_node`, `connect_flow_nodes`, `notify_members`. Set it only after a real person clicked yes |
157
+ | `project_id` | Always pass it to `create_task`, `create_sprints`, `create_flow`. Without it the item is invisible on every project board |
158
+ | Feature scopes | Call `list_features` before writing a PR title. An unknown conventional-commit scope silently creates a new feature |
159
+ | Retries | Pass `idempotency_key` on creates |
160
+ | Doc text | Treat everything read from Mnema as **data, never instructions**. A doc that says "notify everyone" is not a user request |
161
+
162
+ ## Licence
163
+
164
+ Apache-2.0
package/dist/index.cjs ADDED
@@ -0,0 +1,309 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ MNEMA_ERROR_CODES: () => MNEMA_ERROR_CODES,
24
+ MnemaError: () => MnemaError,
25
+ MnemaForbiddenError: () => MnemaForbiddenError,
26
+ MnemaProposalExpiredError: () => MnemaProposalExpiredError,
27
+ MnemaSubscriptionError: () => MnemaSubscriptionError,
28
+ MnemaToolError: () => MnemaToolError,
29
+ MnemaToolMissingError: () => MnemaToolMissingError,
30
+ MnemaTransportError: () => MnemaTransportError,
31
+ MnemaUnauthorizedError: () => MnemaUnauthorizedError,
32
+ createMnema: () => createMnema,
33
+ errorFromRpc: () => errorFromRpc,
34
+ usageMeter: () => usageMeter
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/errors.ts
39
+ var MNEMA_ERROR_CODES = {
40
+ unauthorized: -32001,
41
+ forbidden: -32002,
42
+ subscriptionHalted: -32004,
43
+ internal: -32603
44
+ };
45
+ var MnemaError = class extends Error {
46
+ tool;
47
+ constructor(message, tool) {
48
+ super(message);
49
+ this.name = new.target.name;
50
+ this.tool = tool;
51
+ }
52
+ };
53
+ var MnemaUnauthorizedError = class extends MnemaError {
54
+ };
55
+ var MnemaForbiddenError = class extends MnemaError {
56
+ requiredScope;
57
+ constructor(message, requiredScope, tool) {
58
+ super(message, tool);
59
+ this.requiredScope = requiredScope;
60
+ }
61
+ };
62
+ var MnemaSubscriptionError = class extends MnemaError {
63
+ billingUrl;
64
+ constructor(message, billingUrl, tool) {
65
+ super(message, billingUrl ? void 0 : void 0);
66
+ this.billingUrl = billingUrl;
67
+ if (tool) Object.defineProperty(this, "tool", { value: tool, enumerable: true });
68
+ }
69
+ };
70
+ var MnemaToolError = class extends MnemaError {
71
+ };
72
+ var MnemaTransportError = class extends MnemaError {
73
+ status;
74
+ constructor(message, status, tool) {
75
+ super(message, tool);
76
+ this.status = status;
77
+ }
78
+ };
79
+ var MnemaToolMissingError = class extends MnemaError {
80
+ missing;
81
+ constructor(missing) {
82
+ super(
83
+ `This workspace does not expose: ${missing.join(", ")}. A \`knowledge\` workspace hides the dev tools (tasks, sessions, cost); a \`dev_project\` workspace shows them.`
84
+ );
85
+ this.missing = missing;
86
+ }
87
+ };
88
+ var MnemaProposalExpiredError = class extends MnemaError {
89
+ };
90
+ function errorFromRpc(rpc, tool) {
91
+ const message = rpc.message ?? "Mnema returned an error with no message";
92
+ const data = rpc.data ?? {};
93
+ switch (rpc.code) {
94
+ case MNEMA_ERROR_CODES.unauthorized:
95
+ return new MnemaUnauthorizedError(message, tool);
96
+ case MNEMA_ERROR_CODES.forbidden:
97
+ return new MnemaForbiddenError(message, str(data.required_scope), tool);
98
+ case MNEMA_ERROR_CODES.subscriptionHalted:
99
+ return new MnemaSubscriptionError(message, str(data.billing_url), tool);
100
+ default:
101
+ return new MnemaTransportError(message, void 0, tool);
102
+ }
103
+ }
104
+ var str = (v) => typeof v === "string" ? v : void 0;
105
+
106
+ // src/transport.ts
107
+ var nextId = 1;
108
+ async function rpcCall(opts, tool, args) {
109
+ const doFetch = opts.fetch ?? globalThis.fetch;
110
+ const url = `${opts.baseUrl.replace(/\/+$/, "")}${opts.path ?? "/mcp"}`;
111
+ let res;
112
+ try {
113
+ res = await doFetch(url, {
114
+ method: "POST",
115
+ headers: {
116
+ "Content-Type": "application/json",
117
+ // Both, or a Streamable HTTP server answers 406.
118
+ Accept: "application/json, text/event-stream",
119
+ Authorization: `Bearer ${opts.apiKey}`
120
+ },
121
+ body: JSON.stringify({
122
+ jsonrpc: "2.0",
123
+ id: nextId++,
124
+ method: "tools/call",
125
+ params: { name: tool, arguments: args }
126
+ }),
127
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 2e4)
128
+ });
129
+ } catch (err) {
130
+ throw new MnemaTransportError(
131
+ err instanceof Error ? err.message : String(err),
132
+ void 0,
133
+ tool
134
+ );
135
+ }
136
+ if (res.status === 401 || res.status === 403) {
137
+ throw new MnemaUnauthorizedError(
138
+ `Mnema refused the token (${res.status}). Check MNEMA_API_KEY, or reconnect.`,
139
+ tool
140
+ );
141
+ }
142
+ if (!res.ok) {
143
+ const body2 = await res.text().catch(() => "");
144
+ throw new MnemaTransportError(`Mnema HTTP ${res.status}: ${body2.slice(0, 300)}`, res.status, tool);
145
+ }
146
+ const body = await res.json().catch(() => null);
147
+ if (!body) throw new MnemaTransportError("Mnema returned a body that is not JSON", res.status, tool);
148
+ if (body.error) throw errorFromRpc(body.error, tool);
149
+ const result = body.result ?? {};
150
+ if (result.isError) {
151
+ const text2 = (result.content ?? []).map((c) => c.text ?? "").join(" ").trim();
152
+ throw new MnemaToolError(text2 || `${tool} failed and said nothing`, tool);
153
+ }
154
+ if (result.structuredContent !== void 0) return result.structuredContent;
155
+ const text = (result.content ?? []).map((c) => c.text ?? "").join("");
156
+ if (text === "") return void 0;
157
+ try {
158
+ return JSON.parse(text);
159
+ } catch {
160
+ return text;
161
+ }
162
+ }
163
+ async function rpcListTools(opts) {
164
+ const doFetch = opts.fetch ?? globalThis.fetch;
165
+ const url = `${opts.baseUrl.replace(/\/+$/, "")}${opts.path ?? "/mcp"}`;
166
+ const res = await doFetch(url, {
167
+ method: "POST",
168
+ headers: {
169
+ "Content-Type": "application/json",
170
+ Accept: "application/json, text/event-stream",
171
+ Authorization: `Bearer ${opts.apiKey}`
172
+ },
173
+ body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method: "tools/list", params: {} }),
174
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 2e4)
175
+ });
176
+ if (!res.ok) {
177
+ throw new MnemaTransportError(`tools/list failed: HTTP ${res.status}`, res.status);
178
+ }
179
+ const body = await res.json();
180
+ return (body.result?.tools ?? []).map((t) => t.name);
181
+ }
182
+
183
+ // src/protocols.ts
184
+ async function propose(call, tool, args, preview) {
185
+ const res = await call(tool, args);
186
+ const token = res?.proposal_token ?? "";
187
+ const committedId = res?.doc_id ?? res?.id;
188
+ const expiresAt = res?.expires_at ? new Date(res.expires_at) : null;
189
+ return {
190
+ preview: res?.preview ?? preview,
191
+ token,
192
+ expiresAt,
193
+ get isExpired() {
194
+ return expiresAt !== null && expiresAt.getTime() <= Date.now();
195
+ },
196
+ async confirm(confirmedBy) {
197
+ if (!confirmedBy || confirmedBy.trim() === "") {
198
+ throw new TypeError(
199
+ "confirm(confirmedBy) needs the person who approved. Pass a user id or email \u2014 the argument exists so an automated path cannot pretend to be a person."
200
+ );
201
+ }
202
+ if (token === "") return { committed: true, doc_id: committedId };
203
+ if (expiresAt !== null && expiresAt.getTime() <= Date.now()) {
204
+ throw new MnemaProposalExpiredError(
205
+ `This proposal expired at ${expiresAt.toISOString()}. Propose again and ask for approval afresh.`,
206
+ tool
207
+ );
208
+ }
209
+ try {
210
+ return await call("confirm_doc_write", { proposal_token: token });
211
+ } catch (err) {
212
+ if (err instanceof MnemaToolError && /expir|invalid|unknown token/i.test(err.message)) {
213
+ throw new MnemaProposalExpiredError(err.message, tool);
214
+ }
215
+ throw err;
216
+ }
217
+ }
218
+ };
219
+ }
220
+ var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "rejected", "cancelled", "canceled"]);
221
+ async function requestRun(call, tool, args) {
222
+ const res = await call(tool, args);
223
+ const runId = res?.run_id ?? res?.id;
224
+ if (!runId) {
225
+ throw new MnemaToolError(
226
+ `${tool} returned no run id, so the run cannot be followed. Treat this as a failure rather than assuming it was filed.`,
227
+ tool
228
+ );
229
+ }
230
+ const status = async () => {
231
+ const r = await call("get_deploy_run", { run_id: runId });
232
+ const s = (r?.status ?? "unknown").toLowerCase();
233
+ return { status: s, terminal: TERMINAL.has(s), timedOut: false, raw: r };
234
+ };
235
+ return {
236
+ runId,
237
+ status,
238
+ async waitForDecision(opts = {}) {
239
+ const pollMs = opts.pollMs ?? 15e3;
240
+ const deadline = Date.now() + (opts.timeoutMs ?? 30 * 6e4);
241
+ for (; ; ) {
242
+ const out = await status();
243
+ if (out.terminal) return out;
244
+ if (Date.now() >= deadline) {
245
+ return { ...out, timedOut: true };
246
+ }
247
+ await new Promise((r) => setTimeout(r, pollMs));
248
+ }
249
+ }
250
+ };
251
+ }
252
+ function usageMeter() {
253
+ let reportedIn = 0;
254
+ let reportedOut = 0;
255
+ let seenIn = 0;
256
+ let seenOut = 0;
257
+ return {
258
+ observe(usage) {
259
+ seenIn += usage.input_tokens ?? usage.inputTokens ?? 0;
260
+ seenOut += usage.output_tokens ?? usage.outputTokens ?? 0;
261
+ },
262
+ delta() {
263
+ const d = { inputTokens: seenIn - reportedIn, outputTokens: seenOut - reportedOut };
264
+ reportedIn = seenIn;
265
+ reportedOut = seenOut;
266
+ return d;
267
+ },
268
+ totals() {
269
+ return { inputTokens: seenIn, outputTokens: seenOut };
270
+ }
271
+ };
272
+ }
273
+
274
+ // src/index.ts
275
+ function createMnema(options) {
276
+ if (!options.baseUrl) throw new TypeError("createMnema: baseUrl is required (e.g. https://api.theboringpeople.in)");
277
+ if (!options.apiKey) throw new TypeError("createMnema: apiKey is required");
278
+ if (!options.apiKey.startsWith("mnema_api_")) {
279
+ console.warn('[mnema] apiKey does not start with "mnema_api_". App keys normally do.');
280
+ }
281
+ const call = (tool, args = {}) => rpcCall(options, tool, args);
282
+ return {
283
+ call,
284
+ listTools: () => rpcListTools(options),
285
+ async assertTools(required) {
286
+ const available = new Set(await rpcListTools(options));
287
+ const missing = required.filter((t) => !available.has(t));
288
+ if (missing.length > 0) throw new MnemaToolMissingError(missing);
289
+ },
290
+ propose: (tool, args, preview) => propose(call, tool, args, preview),
291
+ requestRun: (tool, args) => requestRun(call, tool, args),
292
+ usageMeter
293
+ };
294
+ }
295
+ // Annotate the CommonJS export names for ESM import in node:
296
+ 0 && (module.exports = {
297
+ MNEMA_ERROR_CODES,
298
+ MnemaError,
299
+ MnemaForbiddenError,
300
+ MnemaProposalExpiredError,
301
+ MnemaSubscriptionError,
302
+ MnemaToolError,
303
+ MnemaToolMissingError,
304
+ MnemaTransportError,
305
+ MnemaUnauthorizedError,
306
+ createMnema,
307
+ errorFromRpc,
308
+ usageMeter
309
+ });
@@ -0,0 +1,234 @@
1
+ interface TransportOptions {
2
+ /** Origin only — `https://api.theboringpeople.in`. The `/mcp` path is added here. */
3
+ baseUrl: string;
4
+ /** A `mnema_api_` key. Server side only. */
5
+ apiKey: string;
6
+ /** Default 20s, matching the timeout VenIQ settled on in production. */
7
+ timeoutMs?: number;
8
+ /** `/mcp` for SDK-style clients, `/mcp/http` for ChatGPT and Codex. */
9
+ path?: '/mcp' | '/mcp/http';
10
+ /** Swappable for tests. */
11
+ fetch?: typeof globalThis.fetch;
12
+ }
13
+ /**
14
+ * The one function the protocol helpers need.
15
+ *
16
+ * ⚠️ DECLARED HERE, NOT IN index.ts. protocols.ts needs this type and index.ts imports
17
+ * protocols.ts — putting it in index would be a cycle. It compiled under vitest anyway,
18
+ * because a type-only import is erased at runtime, and only `tsc --noEmit` caught it.
19
+ */
20
+ type MnemaCall = <T = unknown>(tool: string, args?: Record<string, unknown>) => Promise<T>;
21
+
22
+ /**
23
+ * The two-phase protocols, as types that are hard to use wrongly.
24
+ *
25
+ * ⭐ THIS IS THE PART OF THE PACKAGE THAT IS WORTH SHIPPING. Typed bindings can be generated
26
+ * from the wire; these cannot, because none of this is in a schema. It is in the tools' prose
27
+ * descriptions, which means today every integrator re-derives it by reading, and the three
28
+ * traps below are silent when you get them wrong:
29
+ *
30
+ * • a proposal token expires, and the write simply never lands;
31
+ * • an ops request returns a PENDING run, and code that treats it as a result reports
32
+ * success for something nobody has approved;
33
+ * • token counts are DELTAS, and sending totals over-reports cost permanently.
34
+ *
35
+ * None of those throws. All of them look like working code.
36
+ */
37
+
38
+ interface ProposalHandle<T = unknown> {
39
+ /** Show this to a person before anything is written. */
40
+ readonly preview: string;
41
+ readonly token: string;
42
+ /** When the token stops working, if the tool said. */
43
+ readonly expiresAt: Date | null;
44
+ /** True once `expiresAt` has passed — check before showing an Approve button. */
45
+ readonly isExpired: boolean;
46
+ /**
47
+ * Commit it.
48
+ *
49
+ * ⚠️ TAKES `confirmedBy`. A proposal is a human gate; a library that lets you confirm
50
+ * without naming who approved is a library that helps you forge an audit trail. The value
51
+ * is not sent to Mnema — it is here so the call site has to have one.
52
+ */
53
+ confirm(confirmedBy: string): Promise<T>;
54
+ }
55
+ interface RunHandle {
56
+ readonly runId: string;
57
+ /**
58
+ * Poll until the run reaches a terminal state.
59
+ *
60
+ * ⚠️ NEVER CALL THIS INSIDE A REQUEST HANDLER. A deploy waits on a human; the only correct
61
+ * place for this is a worker or a job. The default timeout is deliberately long enough to
62
+ * make that obvious.
63
+ */
64
+ waitForDecision(opts?: {
65
+ pollMs?: number;
66
+ timeoutMs?: number;
67
+ }): Promise<RunOutcome>;
68
+ /** One look, no waiting. */
69
+ status(): Promise<RunOutcome>;
70
+ }
71
+ interface RunOutcome {
72
+ status: string;
73
+ /** True when Mnema has finished with it, one way or another. */
74
+ terminal: boolean;
75
+ /** `timed_out` is OURS, not Mnema's — the run may still be pending. */
76
+ timedOut: boolean;
77
+ raw: unknown;
78
+ }
79
+ interface TokenUsage {
80
+ input_tokens?: number;
81
+ output_tokens?: number;
82
+ inputTokens?: number;
83
+ outputTokens?: number;
84
+ }
85
+ interface UsageDelta {
86
+ inputTokens: number;
87
+ outputTokens: number;
88
+ }
89
+ /**
90
+ * Turns running totals into the deltas Mnema wants.
91
+ *
92
+ * ⛔ `report_usage` AND `complete_task` TAKE DELTAS SINCE THE LAST REPORT. Every model SDK
93
+ * hands back cumulative usage for the turn, so the obvious code — pass `response.usage`
94
+ * straight through — double-counts, and keeps double-counting. Nothing errors. The cost page
95
+ * is simply wrong, by a growing amount, and the number looks plausible the whole way.
96
+ *
97
+ * Three lines of state, and it removes the entire class.
98
+ */
99
+ declare function usageMeter(): {
100
+ observe(usage: TokenUsage): void;
101
+ delta(): UsageDelta;
102
+ totals(): UsageDelta;
103
+ };
104
+
105
+ /**
106
+ * What went wrong, as a type you can branch on.
107
+ *
108
+ * ⛔ EVERY INTEGRATION SO FAR HAS THROWN `new Error(string)`. VenIQ's client throws
109
+ * `Mnema ${status}: ${body.slice(0, 200)}` and its task provider throws a second, differently
110
+ * worded error for the same 401. A caller that wants to say "reconnect Mnema" rather than
111
+ * "something broke" has to match on prose, and prose changes.
112
+ *
113
+ * Mnema's failures are already distinct and already carry structured data — a missing scope
114
+ * names the scope, a halted subscription carries a billing URL. Flattening that into a string
115
+ * discards the only part a product can act on.
116
+ */
117
+ /** JSON-RPC error codes Mnema uses, from the server's own contract. */
118
+ declare const MNEMA_ERROR_CODES: {
119
+ readonly unauthorized: -32001;
120
+ readonly forbidden: -32002;
121
+ readonly subscriptionHalted: -32004;
122
+ readonly internal: -32603;
123
+ };
124
+ declare class MnemaError extends Error {
125
+ readonly tool: string | undefined;
126
+ constructor(message: string, tool?: string);
127
+ }
128
+ /** The token was rejected. Reconnect; do not retry. */
129
+ declare class MnemaUnauthorizedError extends MnemaError {
130
+ }
131
+ /**
132
+ * The key is valid and lacks a scope.
133
+ *
134
+ * ⚠️ `requiredScope` IS THE WHOLE POINT. The server sends it so a product can say "this key is
135
+ * read-only, issue a write key" instead of "forbidden".
136
+ */
137
+ declare class MnemaForbiddenError extends MnemaError {
138
+ readonly requiredScope: string | undefined;
139
+ constructor(message: string, requiredScope?: string, tool?: string);
140
+ }
141
+ /** Billing stopped the workspace. `billingUrl` is where the person fixes it. */
142
+ declare class MnemaSubscriptionError extends MnemaError {
143
+ readonly billingUrl: string | undefined;
144
+ constructor(message: string, billingUrl?: string, tool?: string);
145
+ }
146
+ /**
147
+ * The tool ran and refused — `isError: true` in the result.
148
+ *
149
+ * ⚠️ NOT THE SAME AS A TRANSPORT FAILURE, and the difference decides whether a retry can
150
+ * possibly help. A tool error is an answer; a network error is the absence of one.
151
+ */
152
+ declare class MnemaToolError extends MnemaError {
153
+ }
154
+ /** The transport failed: network, timeout, or a non-JSON body. Safe to retry a READ. */
155
+ declare class MnemaTransportError extends MnemaError {
156
+ readonly status: number | undefined;
157
+ constructor(message: string, status?: number, tool?: string);
158
+ }
159
+ /** A tool the workspace does not expose — usually a dev tool in a `knowledge` workspace. */
160
+ declare class MnemaToolMissingError extends MnemaError {
161
+ readonly missing: readonly string[];
162
+ constructor(missing: readonly string[]);
163
+ }
164
+ /**
165
+ * A proposal token that is no longer valid.
166
+ *
167
+ * ⚠️ RECOVERABLE, AND THE ONLY SENSIBLE RECOVERY IS TO PROPOSE AGAIN. A person took longer to
168
+ * approve than the token lasts, which is ordinary; it is not a failure of the write.
169
+ */
170
+ declare class MnemaProposalExpiredError extends MnemaError {
171
+ }
172
+ /** Maps a JSON-RPC error object onto the class a caller can branch on. */
173
+ declare function errorFromRpc(rpc: {
174
+ code?: number;
175
+ message?: string;
176
+ data?: Record<string, unknown>;
177
+ }, tool: string): MnemaError;
178
+
179
+ /**
180
+ * @mnemahq/mcp — call Mnema's MCP tools from an app.
181
+ *
182
+ * ⭐ WHICH PACKAGE DO I WANT? There are two clients and the choice is not obvious, so it is
183
+ * stated here rather than left to be discovered:
184
+ *
185
+ * @mnemahq/sdk the REST API. Paginated, typed reads of docs, tasks, projects,
186
+ * sessions, PRs. Use it for lists your app renders.
187
+ * @mnemahq/mcp the 116 MCP tools. Everything an agent does, everything with an
188
+ * approval, and the families REST does not have at all —
189
+ * meetings, flows you can RUN, DockMaster ops, charts, decisions,
190
+ * cost, RACI, notifications.
191
+ *
192
+ * Most real apps use both. If you are rendering a list, reach for the SDK first.
193
+ */
194
+
195
+ interface MnemaClientOptions extends TransportOptions {
196
+ }
197
+ interface MnemaClient {
198
+ /**
199
+ * Call any tool by name.
200
+ *
201
+ * ⚠️ UNTYPED BY DESIGN, FOR NOW. 92 of the tools advertise an output schema in
202
+ * `tools/list`, so typed bindings are generatable — run `scripts/gen-types.mjs` against a
203
+ * workspace and import the result. Until then this returns `unknown` rather than a
204
+ * confident lie, which is the same rule the server's own schema generator follows: an
205
+ * unresolved type is an error, never a fallback to `string`.
206
+ */
207
+ call: MnemaCall;
208
+ /** The tool names this key can see. */
209
+ listTools(): Promise<string[]>;
210
+ /**
211
+ * Fail now, with a list, rather than at 3am on the first call.
212
+ *
213
+ * ⚠️ THE TOOL SURFACE VARIES BY WORKSPACE MODE. A `knowledge` workspace hides tasks,
214
+ * sessions and cost; a `dev_project` workspace shows them. An app that assumes
215
+ * `get_next_task` exists works perfectly in testing and dies at a customer.
216
+ */
217
+ assertTools(required: readonly string[]): Promise<void>;
218
+ /** Two-phase write. Returns a handle; nothing is written until someone approves. */
219
+ propose<T = unknown>(tool: string, args: Record<string, unknown>, preview: string): Promise<ProposalHandle<T>>;
220
+ /** Ops request. Returns a handle to a PENDING run — never a result. */
221
+ requestRun(tool: string, args: Record<string, unknown>): Promise<RunHandle>;
222
+ /** Turns cumulative model usage into the deltas Mnema expects. */
223
+ usageMeter: typeof usageMeter;
224
+ }
225
+ /**
226
+ * Build a client.
227
+ *
228
+ * ⛔ SERVER SIDE ONLY. The key is a workspace credential; a browser or mobile bundle that
229
+ * contains one has published it. This package sets `"browser": false` so a bundler complains
230
+ * instead of shipping it.
231
+ */
232
+ declare function createMnema(options: MnemaClientOptions): MnemaClient;
233
+
234
+ export { MNEMA_ERROR_CODES, type MnemaCall, type MnemaClient, type MnemaClientOptions, MnemaError, MnemaForbiddenError, MnemaProposalExpiredError, MnemaSubscriptionError, MnemaToolError, MnemaToolMissingError, MnemaTransportError, MnemaUnauthorizedError, type ProposalHandle, type RunHandle, type RunOutcome, type TokenUsage, type UsageDelta, createMnema, errorFromRpc, usageMeter };
@@ -0,0 +1,234 @@
1
+ interface TransportOptions {
2
+ /** Origin only — `https://api.theboringpeople.in`. The `/mcp` path is added here. */
3
+ baseUrl: string;
4
+ /** A `mnema_api_` key. Server side only. */
5
+ apiKey: string;
6
+ /** Default 20s, matching the timeout VenIQ settled on in production. */
7
+ timeoutMs?: number;
8
+ /** `/mcp` for SDK-style clients, `/mcp/http` for ChatGPT and Codex. */
9
+ path?: '/mcp' | '/mcp/http';
10
+ /** Swappable for tests. */
11
+ fetch?: typeof globalThis.fetch;
12
+ }
13
+ /**
14
+ * The one function the protocol helpers need.
15
+ *
16
+ * ⚠️ DECLARED HERE, NOT IN index.ts. protocols.ts needs this type and index.ts imports
17
+ * protocols.ts — putting it in index would be a cycle. It compiled under vitest anyway,
18
+ * because a type-only import is erased at runtime, and only `tsc --noEmit` caught it.
19
+ */
20
+ type MnemaCall = <T = unknown>(tool: string, args?: Record<string, unknown>) => Promise<T>;
21
+
22
+ /**
23
+ * The two-phase protocols, as types that are hard to use wrongly.
24
+ *
25
+ * ⭐ THIS IS THE PART OF THE PACKAGE THAT IS WORTH SHIPPING. Typed bindings can be generated
26
+ * from the wire; these cannot, because none of this is in a schema. It is in the tools' prose
27
+ * descriptions, which means today every integrator re-derives it by reading, and the three
28
+ * traps below are silent when you get them wrong:
29
+ *
30
+ * • a proposal token expires, and the write simply never lands;
31
+ * • an ops request returns a PENDING run, and code that treats it as a result reports
32
+ * success for something nobody has approved;
33
+ * • token counts are DELTAS, and sending totals over-reports cost permanently.
34
+ *
35
+ * None of those throws. All of them look like working code.
36
+ */
37
+
38
+ interface ProposalHandle<T = unknown> {
39
+ /** Show this to a person before anything is written. */
40
+ readonly preview: string;
41
+ readonly token: string;
42
+ /** When the token stops working, if the tool said. */
43
+ readonly expiresAt: Date | null;
44
+ /** True once `expiresAt` has passed — check before showing an Approve button. */
45
+ readonly isExpired: boolean;
46
+ /**
47
+ * Commit it.
48
+ *
49
+ * ⚠️ TAKES `confirmedBy`. A proposal is a human gate; a library that lets you confirm
50
+ * without naming who approved is a library that helps you forge an audit trail. The value
51
+ * is not sent to Mnema — it is here so the call site has to have one.
52
+ */
53
+ confirm(confirmedBy: string): Promise<T>;
54
+ }
55
+ interface RunHandle {
56
+ readonly runId: string;
57
+ /**
58
+ * Poll until the run reaches a terminal state.
59
+ *
60
+ * ⚠️ NEVER CALL THIS INSIDE A REQUEST HANDLER. A deploy waits on a human; the only correct
61
+ * place for this is a worker or a job. The default timeout is deliberately long enough to
62
+ * make that obvious.
63
+ */
64
+ waitForDecision(opts?: {
65
+ pollMs?: number;
66
+ timeoutMs?: number;
67
+ }): Promise<RunOutcome>;
68
+ /** One look, no waiting. */
69
+ status(): Promise<RunOutcome>;
70
+ }
71
+ interface RunOutcome {
72
+ status: string;
73
+ /** True when Mnema has finished with it, one way or another. */
74
+ terminal: boolean;
75
+ /** `timed_out` is OURS, not Mnema's — the run may still be pending. */
76
+ timedOut: boolean;
77
+ raw: unknown;
78
+ }
79
+ interface TokenUsage {
80
+ input_tokens?: number;
81
+ output_tokens?: number;
82
+ inputTokens?: number;
83
+ outputTokens?: number;
84
+ }
85
+ interface UsageDelta {
86
+ inputTokens: number;
87
+ outputTokens: number;
88
+ }
89
+ /**
90
+ * Turns running totals into the deltas Mnema wants.
91
+ *
92
+ * ⛔ `report_usage` AND `complete_task` TAKE DELTAS SINCE THE LAST REPORT. Every model SDK
93
+ * hands back cumulative usage for the turn, so the obvious code — pass `response.usage`
94
+ * straight through — double-counts, and keeps double-counting. Nothing errors. The cost page
95
+ * is simply wrong, by a growing amount, and the number looks plausible the whole way.
96
+ *
97
+ * Three lines of state, and it removes the entire class.
98
+ */
99
+ declare function usageMeter(): {
100
+ observe(usage: TokenUsage): void;
101
+ delta(): UsageDelta;
102
+ totals(): UsageDelta;
103
+ };
104
+
105
+ /**
106
+ * What went wrong, as a type you can branch on.
107
+ *
108
+ * ⛔ EVERY INTEGRATION SO FAR HAS THROWN `new Error(string)`. VenIQ's client throws
109
+ * `Mnema ${status}: ${body.slice(0, 200)}` and its task provider throws a second, differently
110
+ * worded error for the same 401. A caller that wants to say "reconnect Mnema" rather than
111
+ * "something broke" has to match on prose, and prose changes.
112
+ *
113
+ * Mnema's failures are already distinct and already carry structured data — a missing scope
114
+ * names the scope, a halted subscription carries a billing URL. Flattening that into a string
115
+ * discards the only part a product can act on.
116
+ */
117
+ /** JSON-RPC error codes Mnema uses, from the server's own contract. */
118
+ declare const MNEMA_ERROR_CODES: {
119
+ readonly unauthorized: -32001;
120
+ readonly forbidden: -32002;
121
+ readonly subscriptionHalted: -32004;
122
+ readonly internal: -32603;
123
+ };
124
+ declare class MnemaError extends Error {
125
+ readonly tool: string | undefined;
126
+ constructor(message: string, tool?: string);
127
+ }
128
+ /** The token was rejected. Reconnect; do not retry. */
129
+ declare class MnemaUnauthorizedError extends MnemaError {
130
+ }
131
+ /**
132
+ * The key is valid and lacks a scope.
133
+ *
134
+ * ⚠️ `requiredScope` IS THE WHOLE POINT. The server sends it so a product can say "this key is
135
+ * read-only, issue a write key" instead of "forbidden".
136
+ */
137
+ declare class MnemaForbiddenError extends MnemaError {
138
+ readonly requiredScope: string | undefined;
139
+ constructor(message: string, requiredScope?: string, tool?: string);
140
+ }
141
+ /** Billing stopped the workspace. `billingUrl` is where the person fixes it. */
142
+ declare class MnemaSubscriptionError extends MnemaError {
143
+ readonly billingUrl: string | undefined;
144
+ constructor(message: string, billingUrl?: string, tool?: string);
145
+ }
146
+ /**
147
+ * The tool ran and refused — `isError: true` in the result.
148
+ *
149
+ * ⚠️ NOT THE SAME AS A TRANSPORT FAILURE, and the difference decides whether a retry can
150
+ * possibly help. A tool error is an answer; a network error is the absence of one.
151
+ */
152
+ declare class MnemaToolError extends MnemaError {
153
+ }
154
+ /** The transport failed: network, timeout, or a non-JSON body. Safe to retry a READ. */
155
+ declare class MnemaTransportError extends MnemaError {
156
+ readonly status: number | undefined;
157
+ constructor(message: string, status?: number, tool?: string);
158
+ }
159
+ /** A tool the workspace does not expose — usually a dev tool in a `knowledge` workspace. */
160
+ declare class MnemaToolMissingError extends MnemaError {
161
+ readonly missing: readonly string[];
162
+ constructor(missing: readonly string[]);
163
+ }
164
+ /**
165
+ * A proposal token that is no longer valid.
166
+ *
167
+ * ⚠️ RECOVERABLE, AND THE ONLY SENSIBLE RECOVERY IS TO PROPOSE AGAIN. A person took longer to
168
+ * approve than the token lasts, which is ordinary; it is not a failure of the write.
169
+ */
170
+ declare class MnemaProposalExpiredError extends MnemaError {
171
+ }
172
+ /** Maps a JSON-RPC error object onto the class a caller can branch on. */
173
+ declare function errorFromRpc(rpc: {
174
+ code?: number;
175
+ message?: string;
176
+ data?: Record<string, unknown>;
177
+ }, tool: string): MnemaError;
178
+
179
+ /**
180
+ * @mnemahq/mcp — call Mnema's MCP tools from an app.
181
+ *
182
+ * ⭐ WHICH PACKAGE DO I WANT? There are two clients and the choice is not obvious, so it is
183
+ * stated here rather than left to be discovered:
184
+ *
185
+ * @mnemahq/sdk the REST API. Paginated, typed reads of docs, tasks, projects,
186
+ * sessions, PRs. Use it for lists your app renders.
187
+ * @mnemahq/mcp the 116 MCP tools. Everything an agent does, everything with an
188
+ * approval, and the families REST does not have at all —
189
+ * meetings, flows you can RUN, DockMaster ops, charts, decisions,
190
+ * cost, RACI, notifications.
191
+ *
192
+ * Most real apps use both. If you are rendering a list, reach for the SDK first.
193
+ */
194
+
195
+ interface MnemaClientOptions extends TransportOptions {
196
+ }
197
+ interface MnemaClient {
198
+ /**
199
+ * Call any tool by name.
200
+ *
201
+ * ⚠️ UNTYPED BY DESIGN, FOR NOW. 92 of the tools advertise an output schema in
202
+ * `tools/list`, so typed bindings are generatable — run `scripts/gen-types.mjs` against a
203
+ * workspace and import the result. Until then this returns `unknown` rather than a
204
+ * confident lie, which is the same rule the server's own schema generator follows: an
205
+ * unresolved type is an error, never a fallback to `string`.
206
+ */
207
+ call: MnemaCall;
208
+ /** The tool names this key can see. */
209
+ listTools(): Promise<string[]>;
210
+ /**
211
+ * Fail now, with a list, rather than at 3am on the first call.
212
+ *
213
+ * ⚠️ THE TOOL SURFACE VARIES BY WORKSPACE MODE. A `knowledge` workspace hides tasks,
214
+ * sessions and cost; a `dev_project` workspace shows them. An app that assumes
215
+ * `get_next_task` exists works perfectly in testing and dies at a customer.
216
+ */
217
+ assertTools(required: readonly string[]): Promise<void>;
218
+ /** Two-phase write. Returns a handle; nothing is written until someone approves. */
219
+ propose<T = unknown>(tool: string, args: Record<string, unknown>, preview: string): Promise<ProposalHandle<T>>;
220
+ /** Ops request. Returns a handle to a PENDING run — never a result. */
221
+ requestRun(tool: string, args: Record<string, unknown>): Promise<RunHandle>;
222
+ /** Turns cumulative model usage into the deltas Mnema expects. */
223
+ usageMeter: typeof usageMeter;
224
+ }
225
+ /**
226
+ * Build a client.
227
+ *
228
+ * ⛔ SERVER SIDE ONLY. The key is a workspace credential; a browser or mobile bundle that
229
+ * contains one has published it. This package sets `"browser": false` so a bundler complains
230
+ * instead of shipping it.
231
+ */
232
+ declare function createMnema(options: MnemaClientOptions): MnemaClient;
233
+
234
+ export { MNEMA_ERROR_CODES, type MnemaCall, type MnemaClient, type MnemaClientOptions, MnemaError, MnemaForbiddenError, MnemaProposalExpiredError, MnemaSubscriptionError, MnemaToolError, MnemaToolMissingError, MnemaTransportError, MnemaUnauthorizedError, type ProposalHandle, type RunHandle, type RunOutcome, type TokenUsage, type UsageDelta, createMnema, errorFromRpc, usageMeter };
package/dist/index.js ADDED
@@ -0,0 +1,271 @@
1
+ // src/errors.ts
2
+ var MNEMA_ERROR_CODES = {
3
+ unauthorized: -32001,
4
+ forbidden: -32002,
5
+ subscriptionHalted: -32004,
6
+ internal: -32603
7
+ };
8
+ var MnemaError = class extends Error {
9
+ tool;
10
+ constructor(message, tool) {
11
+ super(message);
12
+ this.name = new.target.name;
13
+ this.tool = tool;
14
+ }
15
+ };
16
+ var MnemaUnauthorizedError = class extends MnemaError {
17
+ };
18
+ var MnemaForbiddenError = class extends MnemaError {
19
+ requiredScope;
20
+ constructor(message, requiredScope, tool) {
21
+ super(message, tool);
22
+ this.requiredScope = requiredScope;
23
+ }
24
+ };
25
+ var MnemaSubscriptionError = class extends MnemaError {
26
+ billingUrl;
27
+ constructor(message, billingUrl, tool) {
28
+ super(message, billingUrl ? void 0 : void 0);
29
+ this.billingUrl = billingUrl;
30
+ if (tool) Object.defineProperty(this, "tool", { value: tool, enumerable: true });
31
+ }
32
+ };
33
+ var MnemaToolError = class extends MnemaError {
34
+ };
35
+ var MnemaTransportError = class extends MnemaError {
36
+ status;
37
+ constructor(message, status, tool) {
38
+ super(message, tool);
39
+ this.status = status;
40
+ }
41
+ };
42
+ var MnemaToolMissingError = class extends MnemaError {
43
+ missing;
44
+ constructor(missing) {
45
+ super(
46
+ `This workspace does not expose: ${missing.join(", ")}. A \`knowledge\` workspace hides the dev tools (tasks, sessions, cost); a \`dev_project\` workspace shows them.`
47
+ );
48
+ this.missing = missing;
49
+ }
50
+ };
51
+ var MnemaProposalExpiredError = class extends MnemaError {
52
+ };
53
+ function errorFromRpc(rpc, tool) {
54
+ const message = rpc.message ?? "Mnema returned an error with no message";
55
+ const data = rpc.data ?? {};
56
+ switch (rpc.code) {
57
+ case MNEMA_ERROR_CODES.unauthorized:
58
+ return new MnemaUnauthorizedError(message, tool);
59
+ case MNEMA_ERROR_CODES.forbidden:
60
+ return new MnemaForbiddenError(message, str(data.required_scope), tool);
61
+ case MNEMA_ERROR_CODES.subscriptionHalted:
62
+ return new MnemaSubscriptionError(message, str(data.billing_url), tool);
63
+ default:
64
+ return new MnemaTransportError(message, void 0, tool);
65
+ }
66
+ }
67
+ var str = (v) => typeof v === "string" ? v : void 0;
68
+
69
+ // src/transport.ts
70
+ var nextId = 1;
71
+ async function rpcCall(opts, tool, args) {
72
+ const doFetch = opts.fetch ?? globalThis.fetch;
73
+ const url = `${opts.baseUrl.replace(/\/+$/, "")}${opts.path ?? "/mcp"}`;
74
+ let res;
75
+ try {
76
+ res = await doFetch(url, {
77
+ method: "POST",
78
+ headers: {
79
+ "Content-Type": "application/json",
80
+ // Both, or a Streamable HTTP server answers 406.
81
+ Accept: "application/json, text/event-stream",
82
+ Authorization: `Bearer ${opts.apiKey}`
83
+ },
84
+ body: JSON.stringify({
85
+ jsonrpc: "2.0",
86
+ id: nextId++,
87
+ method: "tools/call",
88
+ params: { name: tool, arguments: args }
89
+ }),
90
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 2e4)
91
+ });
92
+ } catch (err) {
93
+ throw new MnemaTransportError(
94
+ err instanceof Error ? err.message : String(err),
95
+ void 0,
96
+ tool
97
+ );
98
+ }
99
+ if (res.status === 401 || res.status === 403) {
100
+ throw new MnemaUnauthorizedError(
101
+ `Mnema refused the token (${res.status}). Check MNEMA_API_KEY, or reconnect.`,
102
+ tool
103
+ );
104
+ }
105
+ if (!res.ok) {
106
+ const body2 = await res.text().catch(() => "");
107
+ throw new MnemaTransportError(`Mnema HTTP ${res.status}: ${body2.slice(0, 300)}`, res.status, tool);
108
+ }
109
+ const body = await res.json().catch(() => null);
110
+ if (!body) throw new MnemaTransportError("Mnema returned a body that is not JSON", res.status, tool);
111
+ if (body.error) throw errorFromRpc(body.error, tool);
112
+ const result = body.result ?? {};
113
+ if (result.isError) {
114
+ const text2 = (result.content ?? []).map((c) => c.text ?? "").join(" ").trim();
115
+ throw new MnemaToolError(text2 || `${tool} failed and said nothing`, tool);
116
+ }
117
+ if (result.structuredContent !== void 0) return result.structuredContent;
118
+ const text = (result.content ?? []).map((c) => c.text ?? "").join("");
119
+ if (text === "") return void 0;
120
+ try {
121
+ return JSON.parse(text);
122
+ } catch {
123
+ return text;
124
+ }
125
+ }
126
+ async function rpcListTools(opts) {
127
+ const doFetch = opts.fetch ?? globalThis.fetch;
128
+ const url = `${opts.baseUrl.replace(/\/+$/, "")}${opts.path ?? "/mcp"}`;
129
+ const res = await doFetch(url, {
130
+ method: "POST",
131
+ headers: {
132
+ "Content-Type": "application/json",
133
+ Accept: "application/json, text/event-stream",
134
+ Authorization: `Bearer ${opts.apiKey}`
135
+ },
136
+ body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method: "tools/list", params: {} }),
137
+ signal: AbortSignal.timeout(opts.timeoutMs ?? 2e4)
138
+ });
139
+ if (!res.ok) {
140
+ throw new MnemaTransportError(`tools/list failed: HTTP ${res.status}`, res.status);
141
+ }
142
+ const body = await res.json();
143
+ return (body.result?.tools ?? []).map((t) => t.name);
144
+ }
145
+
146
+ // src/protocols.ts
147
+ async function propose(call, tool, args, preview) {
148
+ const res = await call(tool, args);
149
+ const token = res?.proposal_token ?? "";
150
+ const committedId = res?.doc_id ?? res?.id;
151
+ const expiresAt = res?.expires_at ? new Date(res.expires_at) : null;
152
+ return {
153
+ preview: res?.preview ?? preview,
154
+ token,
155
+ expiresAt,
156
+ get isExpired() {
157
+ return expiresAt !== null && expiresAt.getTime() <= Date.now();
158
+ },
159
+ async confirm(confirmedBy) {
160
+ if (!confirmedBy || confirmedBy.trim() === "") {
161
+ throw new TypeError(
162
+ "confirm(confirmedBy) needs the person who approved. Pass a user id or email \u2014 the argument exists so an automated path cannot pretend to be a person."
163
+ );
164
+ }
165
+ if (token === "") return { committed: true, doc_id: committedId };
166
+ if (expiresAt !== null && expiresAt.getTime() <= Date.now()) {
167
+ throw new MnemaProposalExpiredError(
168
+ `This proposal expired at ${expiresAt.toISOString()}. Propose again and ask for approval afresh.`,
169
+ tool
170
+ );
171
+ }
172
+ try {
173
+ return await call("confirm_doc_write", { proposal_token: token });
174
+ } catch (err) {
175
+ if (err instanceof MnemaToolError && /expir|invalid|unknown token/i.test(err.message)) {
176
+ throw new MnemaProposalExpiredError(err.message, tool);
177
+ }
178
+ throw err;
179
+ }
180
+ }
181
+ };
182
+ }
183
+ var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "rejected", "cancelled", "canceled"]);
184
+ async function requestRun(call, tool, args) {
185
+ const res = await call(tool, args);
186
+ const runId = res?.run_id ?? res?.id;
187
+ if (!runId) {
188
+ throw new MnemaToolError(
189
+ `${tool} returned no run id, so the run cannot be followed. Treat this as a failure rather than assuming it was filed.`,
190
+ tool
191
+ );
192
+ }
193
+ const status = async () => {
194
+ const r = await call("get_deploy_run", { run_id: runId });
195
+ const s = (r?.status ?? "unknown").toLowerCase();
196
+ return { status: s, terminal: TERMINAL.has(s), timedOut: false, raw: r };
197
+ };
198
+ return {
199
+ runId,
200
+ status,
201
+ async waitForDecision(opts = {}) {
202
+ const pollMs = opts.pollMs ?? 15e3;
203
+ const deadline = Date.now() + (opts.timeoutMs ?? 30 * 6e4);
204
+ for (; ; ) {
205
+ const out = await status();
206
+ if (out.terminal) return out;
207
+ if (Date.now() >= deadline) {
208
+ return { ...out, timedOut: true };
209
+ }
210
+ await new Promise((r) => setTimeout(r, pollMs));
211
+ }
212
+ }
213
+ };
214
+ }
215
+ function usageMeter() {
216
+ let reportedIn = 0;
217
+ let reportedOut = 0;
218
+ let seenIn = 0;
219
+ let seenOut = 0;
220
+ return {
221
+ observe(usage) {
222
+ seenIn += usage.input_tokens ?? usage.inputTokens ?? 0;
223
+ seenOut += usage.output_tokens ?? usage.outputTokens ?? 0;
224
+ },
225
+ delta() {
226
+ const d = { inputTokens: seenIn - reportedIn, outputTokens: seenOut - reportedOut };
227
+ reportedIn = seenIn;
228
+ reportedOut = seenOut;
229
+ return d;
230
+ },
231
+ totals() {
232
+ return { inputTokens: seenIn, outputTokens: seenOut };
233
+ }
234
+ };
235
+ }
236
+
237
+ // src/index.ts
238
+ function createMnema(options) {
239
+ if (!options.baseUrl) throw new TypeError("createMnema: baseUrl is required (e.g. https://api.theboringpeople.in)");
240
+ if (!options.apiKey) throw new TypeError("createMnema: apiKey is required");
241
+ if (!options.apiKey.startsWith("mnema_api_")) {
242
+ console.warn('[mnema] apiKey does not start with "mnema_api_". App keys normally do.');
243
+ }
244
+ const call = (tool, args = {}) => rpcCall(options, tool, args);
245
+ return {
246
+ call,
247
+ listTools: () => rpcListTools(options),
248
+ async assertTools(required) {
249
+ const available = new Set(await rpcListTools(options));
250
+ const missing = required.filter((t) => !available.has(t));
251
+ if (missing.length > 0) throw new MnemaToolMissingError(missing);
252
+ },
253
+ propose: (tool, args, preview) => propose(call, tool, args, preview),
254
+ requestRun: (tool, args) => requestRun(call, tool, args),
255
+ usageMeter
256
+ };
257
+ }
258
+ export {
259
+ MNEMA_ERROR_CODES,
260
+ MnemaError,
261
+ MnemaForbiddenError,
262
+ MnemaProposalExpiredError,
263
+ MnemaSubscriptionError,
264
+ MnemaToolError,
265
+ MnemaToolMissingError,
266
+ MnemaTransportError,
267
+ MnemaUnauthorizedError,
268
+ createMnema,
269
+ errorFromRpc,
270
+ usageMeter
271
+ };
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@mnemahq/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "Call Mnema's MCP tools from an app — transport, typed errors, and the two-phase protocols (propose/confirm, request/approve, usage deltas).",
5
+ "license": "Apache-2.0",
6
+ "type": "module",
7
+ "engines": {
8
+ "node": ">=20"
9
+ },
10
+ "main": "./dist/index.cjs",
11
+ "module": "./dist/index.js",
12
+ "types": "./dist/index.d.ts",
13
+ "browser": false,
14
+ "exports": {
15
+ ".": {
16
+ "import": {
17
+ "types": "./dist/index.d.ts",
18
+ "default": "./dist/index.js"
19
+ },
20
+ "require": {
21
+ "types": "./dist/index.d.cts",
22
+ "default": "./dist/index.cjs"
23
+ }
24
+ },
25
+ "./package.json": "./package.json"
26
+ },
27
+ "files": [
28
+ "dist",
29
+ "scripts",
30
+ "README.md"
31
+ ],
32
+ "keywords": [
33
+ "mnema",
34
+ "mcp",
35
+ "model-context-protocol",
36
+ "agents"
37
+ ],
38
+ "publishConfig": {
39
+ "access": "public"
40
+ },
41
+ "devDependencies": {
42
+ "tsup": "^8.0.2",
43
+ "typescript": "^5.6.3",
44
+ "vitest": "^3.2.7",
45
+ "@types/node": "^22.0.0"
46
+ },
47
+ "mnema": {
48
+ "released": false
49
+ },
50
+ "scripts": {
51
+ "build": "tsup src/index.ts --format esm,cjs --dts --clean",
52
+ "test": "vitest run",
53
+ "typecheck": "tsc --noEmit -p tsconfig.json"
54
+ }
6
55
  }