@mnemahq/mcp 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE.md +83 -0
- package/README.md +185 -2
- package/dist/index.cjs +313 -0
- package/dist/index.d.cts +235 -0
- package/dist/index.d.ts +235 -0
- package/dist/index.js +275 -0
- package/package.json +51 -3
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,186 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @mnemahq/mcp
|
|
2
2
|
|
|
3
|
-
|
|
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, // key wrong or revoked, or no longer a member — reconnect, do not retry
|
|
124
|
+
MnemaSubscriptionError, // subscription halted or workspace suspended; .billingUrl when halted
|
|
125
|
+
MnemaToolError, // the tool could not run — unknown tool, bad arguments, missing scope, a tool that errored
|
|
126
|
+
MnemaTransportError, // no answer — safe to retry a READ
|
|
127
|
+
MnemaToolMissingError, // .missing lists the tools this workspace lacks (from assertTools)
|
|
128
|
+
MnemaProposalExpiredError,
|
|
129
|
+
MnemaForbiddenError, // .requiredScope — see the note below
|
|
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
|
+
### ⚠️ Not every refusal throws
|
|
138
|
+
|
|
139
|
+
Many Mnema tools report a refusal **as data**, not as an error. `call()` resolves with it, and
|
|
140
|
+
nothing is thrown:
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
const res = await mnema.call<{ error?: string }>("move_task", { taskId, status: "done" });
|
|
144
|
+
if (typeof res?.error === "string") {
|
|
145
|
+
// a refusal: "task_not_found", "not_found", "invalid_args", "dev_mode_required", …
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
If you rely on `try/catch` alone, a refused call looks like a success. Check for an `error`
|
|
150
|
+
string on any tool whose result you act on.
|
|
151
|
+
|
|
152
|
+
### ⚠️ A missing scope is a `MnemaToolError`, not a `MnemaForbiddenError`
|
|
153
|
+
|
|
154
|
+
When a key lacks the scope a tool needs, the server answers inside the tool result, so it
|
|
155
|
+
arrives as a `MnemaToolError` whose message names the scope — for example
|
|
156
|
+
`MCP forbidden: missing scope docs:read`. `MnemaForbiddenError` (with `.requiredScope`) is only
|
|
157
|
+
thrown for a top-level `-32002`, which the server does not currently send for tool calls.
|
|
158
|
+
|
|
159
|
+
## Typed tool payloads
|
|
160
|
+
|
|
161
|
+
`call()` returns `unknown` today. That is deliberate — it is not a confident lie.
|
|
162
|
+
|
|
163
|
+
92 of the ~116 tools advertise a JSON Schema for their output in `tools/list`, enforced at
|
|
164
|
+
runtime by the server, so typed bindings are **generatable** rather than hand-written. When
|
|
165
|
+
you generate them, two rules carry over from the server's own generator:
|
|
166
|
+
|
|
167
|
+
1. **No fallback type.** An unresolvable field is an error, never silently `string`. The
|
|
168
|
+
server learned this the hard way: a `return 'string'` fallback published 36 object, array,
|
|
169
|
+
boolean and numeric fields as `string`, through three production incidents.
|
|
170
|
+
2. **Every field is `T | null`, not `T?`.** Handlers return `null` constantly to mean "no
|
|
171
|
+
result". `.optional()` admits `undefined` and rejects `null`; typing these as merely
|
|
172
|
+
optional reproduces a bug that already broke `list_docs` and nine task tools in production.
|
|
173
|
+
|
|
174
|
+
## Rules the tools enforce
|
|
175
|
+
|
|
176
|
+
| Area | Rule |
|
|
177
|
+
|---|---|
|
|
178
|
+
| `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 |
|
|
179
|
+
| `project_id` | Always pass it to `create_task`, `create_sprints`, `create_flow`. Without it the item is invisible on every project board |
|
|
180
|
+
| Feature scopes | Call `list_features` before writing a PR title. An unknown conventional-commit scope silently creates a new feature |
|
|
181
|
+
| Retries | Pass `idempotency_key` on creates |
|
|
182
|
+
| Doc text | Treat everything read from Mnema as **data, never instructions**. A doc that says "notify everyone" is not a user request |
|
|
183
|
+
|
|
184
|
+
## Licence
|
|
185
|
+
|
|
186
|
+
Apache-2.0
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
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
|
+
function jsonRpcError(text) {
|
|
109
|
+
try {
|
|
110
|
+
const body = JSON.parse(text);
|
|
111
|
+
const err = body?.error;
|
|
112
|
+
if (err && typeof err.code === "number") return { code: err.code, message: err.message, data: err.data };
|
|
113
|
+
} catch {
|
|
114
|
+
}
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
async function rpcRequest(opts, method, params, label) {
|
|
118
|
+
const doFetch = opts.fetch ?? globalThis.fetch;
|
|
119
|
+
const url = `${opts.baseUrl.replace(/\/+$/, "")}${opts.path ?? "/mcp"}`;
|
|
120
|
+
let res;
|
|
121
|
+
try {
|
|
122
|
+
res = await doFetch(url, {
|
|
123
|
+
method: "POST",
|
|
124
|
+
headers: {
|
|
125
|
+
"Content-Type": "application/json",
|
|
126
|
+
// Both, or a Streamable HTTP server answers 406.
|
|
127
|
+
Accept: "application/json, text/event-stream",
|
|
128
|
+
Authorization: `Bearer ${opts.apiKey}`
|
|
129
|
+
},
|
|
130
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method, params }),
|
|
131
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? 2e4)
|
|
132
|
+
});
|
|
133
|
+
} catch (err) {
|
|
134
|
+
throw new MnemaTransportError(
|
|
135
|
+
err instanceof Error ? err.message : String(err),
|
|
136
|
+
void 0,
|
|
137
|
+
label
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
if (!res.ok) {
|
|
141
|
+
const text = await res.text().catch(() => "");
|
|
142
|
+
const rpcError = jsonRpcError(text);
|
|
143
|
+
if (rpcError) {
|
|
144
|
+
if (rpcError.code === MNEMA_ERROR_CODES.unauthorized && /^\s*unauthorized\.?\s*$/i.test(rpcError.message ?? "")) {
|
|
145
|
+
const reason = typeof rpcError.data?.reason === "string" ? `: ${rpcError.data.reason}` : "";
|
|
146
|
+
rpcError.message = `Mnema refused the token (${res.status}${reason}). Check MNEMA_API_KEY, or reconnect.`;
|
|
147
|
+
}
|
|
148
|
+
throw errorFromRpc(rpcError, label);
|
|
149
|
+
}
|
|
150
|
+
if (res.status === 401 || res.status === 403) {
|
|
151
|
+
throw new MnemaUnauthorizedError(
|
|
152
|
+
`Mnema refused the token (${res.status}). Check MNEMA_API_KEY, or reconnect.`,
|
|
153
|
+
label
|
|
154
|
+
);
|
|
155
|
+
}
|
|
156
|
+
throw new MnemaTransportError(`Mnema HTTP ${res.status}: ${text.slice(0, 300)}`, res.status, label);
|
|
157
|
+
}
|
|
158
|
+
const body = await res.json().catch(() => null);
|
|
159
|
+
if (!body) throw new MnemaTransportError("Mnema returned a body that is not JSON", res.status, label);
|
|
160
|
+
if (body.error) throw errorFromRpc(body.error, label);
|
|
161
|
+
return body.result ?? {};
|
|
162
|
+
}
|
|
163
|
+
async function rpcCall(opts, tool, args) {
|
|
164
|
+
const result = await rpcRequest(opts, "tools/call", { name: tool, arguments: args }, tool);
|
|
165
|
+
if (result.isError) {
|
|
166
|
+
const text2 = (result.content ?? []).map((c) => c.text ?? "").join(" ").trim();
|
|
167
|
+
throw new MnemaToolError(text2 || `${tool} failed and said nothing`, tool);
|
|
168
|
+
}
|
|
169
|
+
if (result.structuredContent !== void 0) return result.structuredContent;
|
|
170
|
+
const text = (result.content ?? []).map((c) => c.text ?? "").join("");
|
|
171
|
+
if (text === "") return void 0;
|
|
172
|
+
try {
|
|
173
|
+
return JSON.parse(text);
|
|
174
|
+
} catch {
|
|
175
|
+
return text;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
async function rpcListTools(opts) {
|
|
179
|
+
const result = await rpcRequest(opts, "tools/list", {}, "tools/list");
|
|
180
|
+
const tools = result.tools;
|
|
181
|
+
if (!Array.isArray(tools)) {
|
|
182
|
+
throw new MnemaTransportError("tools/list answered without a tools array", void 0, "tools/list");
|
|
183
|
+
}
|
|
184
|
+
return tools.map((t) => t.name);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// src/protocols.ts
|
|
188
|
+
async function propose(call, tool, args, preview) {
|
|
189
|
+
const res = await call(tool, args);
|
|
190
|
+
const token = res?.proposal_token ?? "";
|
|
191
|
+
const committedId = res?.doc_id ?? res?.id;
|
|
192
|
+
const expiresAt = res?.expires_at ? new Date(res.expires_at) : null;
|
|
193
|
+
return {
|
|
194
|
+
preview: res?.preview ?? preview,
|
|
195
|
+
token,
|
|
196
|
+
expiresAt,
|
|
197
|
+
get isExpired() {
|
|
198
|
+
return expiresAt !== null && expiresAt.getTime() <= Date.now();
|
|
199
|
+
},
|
|
200
|
+
async confirm(confirmedBy) {
|
|
201
|
+
if (!confirmedBy || confirmedBy.trim() === "") {
|
|
202
|
+
throw new TypeError(
|
|
203
|
+
"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."
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
if (token === "") return { committed: true, doc_id: committedId };
|
|
207
|
+
if (expiresAt !== null && expiresAt.getTime() <= Date.now()) {
|
|
208
|
+
throw new MnemaProposalExpiredError(
|
|
209
|
+
`This proposal expired at ${expiresAt.toISOString()}. Propose again and ask for approval afresh.`,
|
|
210
|
+
tool
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
try {
|
|
214
|
+
return await call("confirm_doc_write", { proposal_token: token });
|
|
215
|
+
} catch (err) {
|
|
216
|
+
if (err instanceof MnemaToolError && /expir|invalid|unknown token/i.test(err.message)) {
|
|
217
|
+
throw new MnemaProposalExpiredError(err.message, tool);
|
|
218
|
+
}
|
|
219
|
+
throw err;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
}
|
|
224
|
+
var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "rejected", "cancelled", "canceled"]);
|
|
225
|
+
async function requestRun(call, tool, args) {
|
|
226
|
+
const res = await call(tool, args);
|
|
227
|
+
const runId = res?.run_id ?? res?.id;
|
|
228
|
+
if (!runId) {
|
|
229
|
+
throw new MnemaToolError(
|
|
230
|
+
`${tool} returned no run id, so the run cannot be followed. Treat this as a failure rather than assuming it was filed.`,
|
|
231
|
+
tool
|
|
232
|
+
);
|
|
233
|
+
}
|
|
234
|
+
const status = async () => {
|
|
235
|
+
const r = await call("get_deploy_run", { run_id: runId });
|
|
236
|
+
const s = (r?.status ?? "unknown").toLowerCase();
|
|
237
|
+
return { status: s, terminal: TERMINAL.has(s), timedOut: false, raw: r };
|
|
238
|
+
};
|
|
239
|
+
return {
|
|
240
|
+
runId,
|
|
241
|
+
status,
|
|
242
|
+
async waitForDecision(opts = {}) {
|
|
243
|
+
const pollMs = opts.pollMs ?? 15e3;
|
|
244
|
+
const deadline = Date.now() + (opts.timeoutMs ?? 30 * 6e4);
|
|
245
|
+
for (; ; ) {
|
|
246
|
+
const out = await status();
|
|
247
|
+
if (out.terminal) return out;
|
|
248
|
+
if (Date.now() >= deadline) {
|
|
249
|
+
return { ...out, timedOut: true };
|
|
250
|
+
}
|
|
251
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
};
|
|
255
|
+
}
|
|
256
|
+
function usageMeter() {
|
|
257
|
+
let reportedIn = 0;
|
|
258
|
+
let reportedOut = 0;
|
|
259
|
+
let seenIn = 0;
|
|
260
|
+
let seenOut = 0;
|
|
261
|
+
return {
|
|
262
|
+
observe(usage) {
|
|
263
|
+
seenIn += usage.input_tokens ?? usage.inputTokens ?? 0;
|
|
264
|
+
seenOut += usage.output_tokens ?? usage.outputTokens ?? 0;
|
|
265
|
+
},
|
|
266
|
+
delta() {
|
|
267
|
+
const d = { inputTokens: seenIn - reportedIn, outputTokens: seenOut - reportedOut };
|
|
268
|
+
reportedIn = seenIn;
|
|
269
|
+
reportedOut = seenOut;
|
|
270
|
+
return d;
|
|
271
|
+
},
|
|
272
|
+
totals() {
|
|
273
|
+
return { inputTokens: seenIn, outputTokens: seenOut };
|
|
274
|
+
}
|
|
275
|
+
};
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
// src/index.ts
|
|
279
|
+
function createMnema(options) {
|
|
280
|
+
if (!options.baseUrl) throw new TypeError("createMnema: baseUrl is required (e.g. https://api.theboringpeople.in)");
|
|
281
|
+
if (!options.apiKey) throw new TypeError("createMnema: apiKey is required");
|
|
282
|
+
if (!options.apiKey.startsWith("mnema_api_")) {
|
|
283
|
+
console.warn('[mnema] apiKey does not start with "mnema_api_". App keys normally do.');
|
|
284
|
+
}
|
|
285
|
+
const call = (tool, args = {}) => rpcCall(options, tool, args);
|
|
286
|
+
return {
|
|
287
|
+
call,
|
|
288
|
+
listTools: () => rpcListTools(options),
|
|
289
|
+
async assertTools(required) {
|
|
290
|
+
const available = new Set(await rpcListTools(options));
|
|
291
|
+
const missing = required.filter((t) => !available.has(t));
|
|
292
|
+
if (missing.length > 0) throw new MnemaToolMissingError(missing);
|
|
293
|
+
},
|
|
294
|
+
propose: (tool, args, preview) => propose(call, tool, args, preview),
|
|
295
|
+
requestRun: (tool, args) => requestRun(call, tool, args),
|
|
296
|
+
usageMeter
|
|
297
|
+
};
|
|
298
|
+
}
|
|
299
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
300
|
+
0 && (module.exports = {
|
|
301
|
+
MNEMA_ERROR_CODES,
|
|
302
|
+
MnemaError,
|
|
303
|
+
MnemaForbiddenError,
|
|
304
|
+
MnemaProposalExpiredError,
|
|
305
|
+
MnemaSubscriptionError,
|
|
306
|
+
MnemaToolError,
|
|
307
|
+
MnemaToolMissingError,
|
|
308
|
+
MnemaTransportError,
|
|
309
|
+
MnemaUnauthorizedError,
|
|
310
|
+
createMnema,
|
|
311
|
+
errorFromRpc,
|
|
312
|
+
usageMeter
|
|
313
|
+
});
|
package/dist/index.d.cts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
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 — but no generator ships in this
|
|
203
|
+
* version. Pass the shape you expect as `T` (`call<{ results: Hit[] }>(…)`); until then
|
|
204
|
+
* this returns `unknown` rather than a confident lie, which is the same rule the server's
|
|
205
|
+
* own schema generator follows: an unresolved type is an error, never a fallback to
|
|
206
|
+
* `string`.
|
|
207
|
+
*/
|
|
208
|
+
call: MnemaCall;
|
|
209
|
+
/** The tool names this key can see. */
|
|
210
|
+
listTools(): Promise<string[]>;
|
|
211
|
+
/**
|
|
212
|
+
* Fail now, with a list, rather than at 3am on the first call.
|
|
213
|
+
*
|
|
214
|
+
* ⚠️ THE TOOL SURFACE VARIES BY WORKSPACE MODE. A `knowledge` workspace hides tasks,
|
|
215
|
+
* sessions and cost; a `dev_project` workspace shows them. An app that assumes
|
|
216
|
+
* `get_next_task` exists works perfectly in testing and dies at a customer.
|
|
217
|
+
*/
|
|
218
|
+
assertTools(required: readonly string[]): Promise<void>;
|
|
219
|
+
/** Two-phase write. Returns a handle; nothing is written until someone approves. */
|
|
220
|
+
propose<T = unknown>(tool: string, args: Record<string, unknown>, preview: string): Promise<ProposalHandle<T>>;
|
|
221
|
+
/** Ops request. Returns a handle to a PENDING run — never a result. */
|
|
222
|
+
requestRun(tool: string, args: Record<string, unknown>): Promise<RunHandle>;
|
|
223
|
+
/** Turns cumulative model usage into the deltas Mnema expects. */
|
|
224
|
+
usageMeter: typeof usageMeter;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Build a client.
|
|
228
|
+
*
|
|
229
|
+
* ⛔ SERVER SIDE ONLY. The key is a workspace credential; a browser or mobile bundle that
|
|
230
|
+
* contains one has published it. This package sets `"browser": false` so a bundler complains
|
|
231
|
+
* instead of shipping it.
|
|
232
|
+
*/
|
|
233
|
+
declare function createMnema(options: MnemaClientOptions): MnemaClient;
|
|
234
|
+
|
|
235
|
+
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.d.ts
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
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 — but no generator ships in this
|
|
203
|
+
* version. Pass the shape you expect as `T` (`call<{ results: Hit[] }>(…)`); until then
|
|
204
|
+
* this returns `unknown` rather than a confident lie, which is the same rule the server's
|
|
205
|
+
* own schema generator follows: an unresolved type is an error, never a fallback to
|
|
206
|
+
* `string`.
|
|
207
|
+
*/
|
|
208
|
+
call: MnemaCall;
|
|
209
|
+
/** The tool names this key can see. */
|
|
210
|
+
listTools(): Promise<string[]>;
|
|
211
|
+
/**
|
|
212
|
+
* Fail now, with a list, rather than at 3am on the first call.
|
|
213
|
+
*
|
|
214
|
+
* ⚠️ THE TOOL SURFACE VARIES BY WORKSPACE MODE. A `knowledge` workspace hides tasks,
|
|
215
|
+
* sessions and cost; a `dev_project` workspace shows them. An app that assumes
|
|
216
|
+
* `get_next_task` exists works perfectly in testing and dies at a customer.
|
|
217
|
+
*/
|
|
218
|
+
assertTools(required: readonly string[]): Promise<void>;
|
|
219
|
+
/** Two-phase write. Returns a handle; nothing is written until someone approves. */
|
|
220
|
+
propose<T = unknown>(tool: string, args: Record<string, unknown>, preview: string): Promise<ProposalHandle<T>>;
|
|
221
|
+
/** Ops request. Returns a handle to a PENDING run — never a result. */
|
|
222
|
+
requestRun(tool: string, args: Record<string, unknown>): Promise<RunHandle>;
|
|
223
|
+
/** Turns cumulative model usage into the deltas Mnema expects. */
|
|
224
|
+
usageMeter: typeof usageMeter;
|
|
225
|
+
}
|
|
226
|
+
/**
|
|
227
|
+
* Build a client.
|
|
228
|
+
*
|
|
229
|
+
* ⛔ SERVER SIDE ONLY. The key is a workspace credential; a browser or mobile bundle that
|
|
230
|
+
* contains one has published it. This package sets `"browser": false` so a bundler complains
|
|
231
|
+
* instead of shipping it.
|
|
232
|
+
*/
|
|
233
|
+
declare function createMnema(options: MnemaClientOptions): MnemaClient;
|
|
234
|
+
|
|
235
|
+
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,275 @@
|
|
|
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
|
+
function jsonRpcError(text) {
|
|
72
|
+
try {
|
|
73
|
+
const body = JSON.parse(text);
|
|
74
|
+
const err = body?.error;
|
|
75
|
+
if (err && typeof err.code === "number") return { code: err.code, message: err.message, data: err.data };
|
|
76
|
+
} catch {
|
|
77
|
+
}
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
async function rpcRequest(opts, method, params, label) {
|
|
81
|
+
const doFetch = opts.fetch ?? globalThis.fetch;
|
|
82
|
+
const url = `${opts.baseUrl.replace(/\/+$/, "")}${opts.path ?? "/mcp"}`;
|
|
83
|
+
let res;
|
|
84
|
+
try {
|
|
85
|
+
res = await doFetch(url, {
|
|
86
|
+
method: "POST",
|
|
87
|
+
headers: {
|
|
88
|
+
"Content-Type": "application/json",
|
|
89
|
+
// Both, or a Streamable HTTP server answers 406.
|
|
90
|
+
Accept: "application/json, text/event-stream",
|
|
91
|
+
Authorization: `Bearer ${opts.apiKey}`
|
|
92
|
+
},
|
|
93
|
+
body: JSON.stringify({ jsonrpc: "2.0", id: nextId++, method, params }),
|
|
94
|
+
signal: AbortSignal.timeout(opts.timeoutMs ?? 2e4)
|
|
95
|
+
});
|
|
96
|
+
} catch (err) {
|
|
97
|
+
throw new MnemaTransportError(
|
|
98
|
+
err instanceof Error ? err.message : String(err),
|
|
99
|
+
void 0,
|
|
100
|
+
label
|
|
101
|
+
);
|
|
102
|
+
}
|
|
103
|
+
if (!res.ok) {
|
|
104
|
+
const text = await res.text().catch(() => "");
|
|
105
|
+
const rpcError = jsonRpcError(text);
|
|
106
|
+
if (rpcError) {
|
|
107
|
+
if (rpcError.code === MNEMA_ERROR_CODES.unauthorized && /^\s*unauthorized\.?\s*$/i.test(rpcError.message ?? "")) {
|
|
108
|
+
const reason = typeof rpcError.data?.reason === "string" ? `: ${rpcError.data.reason}` : "";
|
|
109
|
+
rpcError.message = `Mnema refused the token (${res.status}${reason}). Check MNEMA_API_KEY, or reconnect.`;
|
|
110
|
+
}
|
|
111
|
+
throw errorFromRpc(rpcError, label);
|
|
112
|
+
}
|
|
113
|
+
if (res.status === 401 || res.status === 403) {
|
|
114
|
+
throw new MnemaUnauthorizedError(
|
|
115
|
+
`Mnema refused the token (${res.status}). Check MNEMA_API_KEY, or reconnect.`,
|
|
116
|
+
label
|
|
117
|
+
);
|
|
118
|
+
}
|
|
119
|
+
throw new MnemaTransportError(`Mnema HTTP ${res.status}: ${text.slice(0, 300)}`, res.status, label);
|
|
120
|
+
}
|
|
121
|
+
const body = await res.json().catch(() => null);
|
|
122
|
+
if (!body) throw new MnemaTransportError("Mnema returned a body that is not JSON", res.status, label);
|
|
123
|
+
if (body.error) throw errorFromRpc(body.error, label);
|
|
124
|
+
return body.result ?? {};
|
|
125
|
+
}
|
|
126
|
+
async function rpcCall(opts, tool, args) {
|
|
127
|
+
const result = await rpcRequest(opts, "tools/call", { name: tool, arguments: args }, tool);
|
|
128
|
+
if (result.isError) {
|
|
129
|
+
const text2 = (result.content ?? []).map((c) => c.text ?? "").join(" ").trim();
|
|
130
|
+
throw new MnemaToolError(text2 || `${tool} failed and said nothing`, tool);
|
|
131
|
+
}
|
|
132
|
+
if (result.structuredContent !== void 0) return result.structuredContent;
|
|
133
|
+
const text = (result.content ?? []).map((c) => c.text ?? "").join("");
|
|
134
|
+
if (text === "") return void 0;
|
|
135
|
+
try {
|
|
136
|
+
return JSON.parse(text);
|
|
137
|
+
} catch {
|
|
138
|
+
return text;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
async function rpcListTools(opts) {
|
|
142
|
+
const result = await rpcRequest(opts, "tools/list", {}, "tools/list");
|
|
143
|
+
const tools = result.tools;
|
|
144
|
+
if (!Array.isArray(tools)) {
|
|
145
|
+
throw new MnemaTransportError("tools/list answered without a tools array", void 0, "tools/list");
|
|
146
|
+
}
|
|
147
|
+
return tools.map((t) => t.name);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
// src/protocols.ts
|
|
151
|
+
async function propose(call, tool, args, preview) {
|
|
152
|
+
const res = await call(tool, args);
|
|
153
|
+
const token = res?.proposal_token ?? "";
|
|
154
|
+
const committedId = res?.doc_id ?? res?.id;
|
|
155
|
+
const expiresAt = res?.expires_at ? new Date(res.expires_at) : null;
|
|
156
|
+
return {
|
|
157
|
+
preview: res?.preview ?? preview,
|
|
158
|
+
token,
|
|
159
|
+
expiresAt,
|
|
160
|
+
get isExpired() {
|
|
161
|
+
return expiresAt !== null && expiresAt.getTime() <= Date.now();
|
|
162
|
+
},
|
|
163
|
+
async confirm(confirmedBy) {
|
|
164
|
+
if (!confirmedBy || confirmedBy.trim() === "") {
|
|
165
|
+
throw new TypeError(
|
|
166
|
+
"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."
|
|
167
|
+
);
|
|
168
|
+
}
|
|
169
|
+
if (token === "") return { committed: true, doc_id: committedId };
|
|
170
|
+
if (expiresAt !== null && expiresAt.getTime() <= Date.now()) {
|
|
171
|
+
throw new MnemaProposalExpiredError(
|
|
172
|
+
`This proposal expired at ${expiresAt.toISOString()}. Propose again and ask for approval afresh.`,
|
|
173
|
+
tool
|
|
174
|
+
);
|
|
175
|
+
}
|
|
176
|
+
try {
|
|
177
|
+
return await call("confirm_doc_write", { proposal_token: token });
|
|
178
|
+
} catch (err) {
|
|
179
|
+
if (err instanceof MnemaToolError && /expir|invalid|unknown token/i.test(err.message)) {
|
|
180
|
+
throw new MnemaProposalExpiredError(err.message, tool);
|
|
181
|
+
}
|
|
182
|
+
throw err;
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
}
|
|
187
|
+
var TERMINAL = /* @__PURE__ */ new Set(["succeeded", "failed", "rejected", "cancelled", "canceled"]);
|
|
188
|
+
async function requestRun(call, tool, args) {
|
|
189
|
+
const res = await call(tool, args);
|
|
190
|
+
const runId = res?.run_id ?? res?.id;
|
|
191
|
+
if (!runId) {
|
|
192
|
+
throw new MnemaToolError(
|
|
193
|
+
`${tool} returned no run id, so the run cannot be followed. Treat this as a failure rather than assuming it was filed.`,
|
|
194
|
+
tool
|
|
195
|
+
);
|
|
196
|
+
}
|
|
197
|
+
const status = async () => {
|
|
198
|
+
const r = await call("get_deploy_run", { run_id: runId });
|
|
199
|
+
const s = (r?.status ?? "unknown").toLowerCase();
|
|
200
|
+
return { status: s, terminal: TERMINAL.has(s), timedOut: false, raw: r };
|
|
201
|
+
};
|
|
202
|
+
return {
|
|
203
|
+
runId,
|
|
204
|
+
status,
|
|
205
|
+
async waitForDecision(opts = {}) {
|
|
206
|
+
const pollMs = opts.pollMs ?? 15e3;
|
|
207
|
+
const deadline = Date.now() + (opts.timeoutMs ?? 30 * 6e4);
|
|
208
|
+
for (; ; ) {
|
|
209
|
+
const out = await status();
|
|
210
|
+
if (out.terminal) return out;
|
|
211
|
+
if (Date.now() >= deadline) {
|
|
212
|
+
return { ...out, timedOut: true };
|
|
213
|
+
}
|
|
214
|
+
await new Promise((r) => setTimeout(r, pollMs));
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
function usageMeter() {
|
|
220
|
+
let reportedIn = 0;
|
|
221
|
+
let reportedOut = 0;
|
|
222
|
+
let seenIn = 0;
|
|
223
|
+
let seenOut = 0;
|
|
224
|
+
return {
|
|
225
|
+
observe(usage) {
|
|
226
|
+
seenIn += usage.input_tokens ?? usage.inputTokens ?? 0;
|
|
227
|
+
seenOut += usage.output_tokens ?? usage.outputTokens ?? 0;
|
|
228
|
+
},
|
|
229
|
+
delta() {
|
|
230
|
+
const d = { inputTokens: seenIn - reportedIn, outputTokens: seenOut - reportedOut };
|
|
231
|
+
reportedIn = seenIn;
|
|
232
|
+
reportedOut = seenOut;
|
|
233
|
+
return d;
|
|
234
|
+
},
|
|
235
|
+
totals() {
|
|
236
|
+
return { inputTokens: seenIn, outputTokens: seenOut };
|
|
237
|
+
}
|
|
238
|
+
};
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// src/index.ts
|
|
242
|
+
function createMnema(options) {
|
|
243
|
+
if (!options.baseUrl) throw new TypeError("createMnema: baseUrl is required (e.g. https://api.theboringpeople.in)");
|
|
244
|
+
if (!options.apiKey) throw new TypeError("createMnema: apiKey is required");
|
|
245
|
+
if (!options.apiKey.startsWith("mnema_api_")) {
|
|
246
|
+
console.warn('[mnema] apiKey does not start with "mnema_api_". App keys normally do.');
|
|
247
|
+
}
|
|
248
|
+
const call = (tool, args = {}) => rpcCall(options, tool, args);
|
|
249
|
+
return {
|
|
250
|
+
call,
|
|
251
|
+
listTools: () => rpcListTools(options),
|
|
252
|
+
async assertTools(required) {
|
|
253
|
+
const available = new Set(await rpcListTools(options));
|
|
254
|
+
const missing = required.filter((t) => !available.has(t));
|
|
255
|
+
if (missing.length > 0) throw new MnemaToolMissingError(missing);
|
|
256
|
+
},
|
|
257
|
+
propose: (tool, args, preview) => propose(call, tool, args, preview),
|
|
258
|
+
requestRun: (tool, args) => requestRun(call, tool, args),
|
|
259
|
+
usageMeter
|
|
260
|
+
};
|
|
261
|
+
}
|
|
262
|
+
export {
|
|
263
|
+
MNEMA_ERROR_CODES,
|
|
264
|
+
MnemaError,
|
|
265
|
+
MnemaForbiddenError,
|
|
266
|
+
MnemaProposalExpiredError,
|
|
267
|
+
MnemaSubscriptionError,
|
|
268
|
+
MnemaToolError,
|
|
269
|
+
MnemaToolMissingError,
|
|
270
|
+
MnemaTransportError,
|
|
271
|
+
MnemaUnauthorizedError,
|
|
272
|
+
createMnema,
|
|
273
|
+
errorFromRpc,
|
|
274
|
+
usageMeter
|
|
275
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mnemahq/mcp",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
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
|
+
"README.md"
|
|
30
|
+
],
|
|
31
|
+
"keywords": [
|
|
32
|
+
"mnema",
|
|
33
|
+
"mcp",
|
|
34
|
+
"model-context-protocol",
|
|
35
|
+
"agents"
|
|
36
|
+
],
|
|
37
|
+
"publishConfig": {
|
|
38
|
+
"access": "public"
|
|
39
|
+
},
|
|
40
|
+
"devDependencies": {
|
|
41
|
+
"tsup": "^8.0.2",
|
|
42
|
+
"typescript": "^5.6.3",
|
|
43
|
+
"vitest": "^3.2.7",
|
|
44
|
+
"@types/node": "^22.0.0"
|
|
45
|
+
},
|
|
46
|
+
"mnema": {
|
|
47
|
+
"released": true
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "tsup src/index.ts --format esm,cjs --dts --clean",
|
|
51
|
+
"test": "vitest run",
|
|
52
|
+
"typecheck": "tsc --noEmit -p tsconfig.json"
|
|
53
|
+
}
|
|
6
54
|
}
|