@floatonnear/mcp 0.3.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,55 @@
1
+ export declare class KeyFileError extends Error {
2
+ }
3
+ export interface KeyFileContents {
4
+ secret: string;
5
+ /** From a `~/.near-credentials`-shaped file. Absent for a bare key file. */
6
+ accountId?: string;
7
+ publicKey?: string;
8
+ }
9
+ /**
10
+ * Read a key out of `path`.
11
+ *
12
+ * Accepts either the `~/.near-credentials` JSON shape or a bare key on one
13
+ * line. Throws `KeyFileError` for anything else — never returns an empty or
14
+ * partial credential, because "I could not read it" collapsing into "there
15
+ * isn't one" is the failure this is built to avoid.
16
+ */
17
+ export declare function readKeyFile(path: string): KeyFileContents;
18
+ export type KeySource = "file" | "inline" | "none";
19
+ export interface ResolvedKey {
20
+ /** Absent when nothing is configured OR when the named file failed to read. */
21
+ secret?: string;
22
+ source: KeySource;
23
+ /** The path that was tried, when one was named. */
24
+ path?: string;
25
+ accountId?: string;
26
+ publicKey?: string;
27
+ /**
28
+ * Set when a file was NAMED but could not be read.
29
+ *
30
+ * Distinct from `source === "none"` on purpose, and the caller must keep it
31
+ * that way: "no key is configured" and "the key file you named is broken"
32
+ * are different problems with different fixes, and reporting the second as
33
+ * the first sends the reader to set a variable that is already set. The
34
+ * adapter's `loadKeyring` carries `skippedOtherVault` for exactly this
35
+ * reason.
36
+ */
37
+ error?: string;
38
+ /** Operator-facing notes. NAMES ONLY — these get logged. */
39
+ warnings: string[];
40
+ }
41
+ /**
42
+ * Decide which of the two variables supplies a secret.
43
+ *
44
+ * The file wins. A failed file read does NOT fall back to the inline value:
45
+ * silently using the config an operator believes they have stopped using is
46
+ * worse than not starting.
47
+ */
48
+ export declare function resolveKeySource(opts: {
49
+ inline?: string;
50
+ file?: string;
51
+ /** e.g. "NEAR_VAULT_AGENT_KEY" — named so messages can be acted on. */
52
+ inlineVar: string;
53
+ /** e.g. "NEAR_VAULT_AGENT_KEY_FILE" */
54
+ fileVar: string;
55
+ }): ResolvedKey;
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Read a secret from a FILE PATH instead of a plaintext env value.
3
+ *
4
+ * This is the same reasoning as `env-file.ts` in the adapter, taken one step
5
+ * further, so it is worth saying what the two have in common and where they
6
+ * part.
7
+ *
8
+ * `env-file.ts` exists because a secrets file must be DATA, never something a
9
+ * shell executes: `set -a && . .float/adapter.env` makes the shell run `$(...)`
10
+ * and backticks found in a value, and it has already died for real on one
11
+ * unquoted value containing a space. That argument is about how a file is
12
+ * LOADED.
13
+ *
14
+ * This module is about where the secret LIVES. Right now the agent key is a
15
+ * plaintext env value in two places — `.mcp.json` (`mcpServers.float-near.env`)
16
+ * and `.float/adapter.env`. Both are gitignored and neither has ever been
17
+ * committed, so nothing has leaked. The exposure is ORDINARY WORK: checking
18
+ * which vault an adapter is pointed at means reading its config, and reading
19
+ * its config prints a live private key into a terminal scrollback and into the
20
+ * transcript of whatever agent is driving. That is routine, it is not a
21
+ * mistake anyone would flag in review, and it is how the session that filed
22
+ * this acquired one.
23
+ *
24
+ * A PATH is not a secret, so the same `cat` becomes harmless. This repo already
25
+ * prefers that shape for the one credential it handles most carefully: NEAR CLI
26
+ * signing uses `sign-with-access-key-file` rather than
27
+ * `sign-with-plaintext-private-key`, chosen after a key was echoed into a
28
+ * terminal. This brings the MCP server and the adapter to the same footing.
29
+ *
30
+ * THE INLINE VARIABLES KEEP WORKING. They are in use; a file is an
31
+ * alternative, not a replacement. When both are set the file wins and the
32
+ * inline one is reported as ignored — the other way round would let an operator
33
+ * believe they had moved a secret out of their config while the config was
34
+ * still silently the thing being read.
35
+ *
36
+ * ---- WHAT NO MESSAGE IN HERE MAY CONTAIN
37
+ *
38
+ * The secret. Every refusal below is reached while holding a usable key, so
39
+ * quoting "what the file contained" would undo the entire point of the change
40
+ * at the one moment an operator is most likely to paste the output somewhere.
41
+ * Field NAMES are safe and are the actual diagnosis; values are not. This is
42
+ * pinned by `no refusal ever names the secret` in key-file.test.ts, which drives
43
+ * only cases that have a real secret in hand.
44
+ *
45
+ * That rule is also why a JSON parse failure is reported as "not valid JSON"
46
+ * with the parser's own message DISCARDED: V8's `JSON.parse` errors quote a
47
+ * fragment of the input, so passing one through would print part of the key.
48
+ */
49
+ import { readFileSync, existsSync, statSync } from "node:fs";
50
+ export class KeyFileError extends Error {
51
+ }
52
+ /** The shape to quote in a refusal, so the fix is in the message. */
53
+ const CRED_SHAPE = '{"account_id", "public_key", "private_key"}';
54
+ /**
55
+ * An env-file assignment, which is a FILE POINTED AT THE WRONG VARIABLE
56
+ * rather than a key.
57
+ *
58
+ * Why the name must contain an underscore and the value must be non-empty
59
+ * after stripping '=': a base64url secret can legitimately end in '=' padding
60
+ * and base64url's alphabet includes '_', so `ABC_DEF=` is a possible SECRET,
61
+ * not necessarily an assignment. Padding is always trailing, so requiring
62
+ * something other than '=' after the first one tells the two apart. Neither of
63
+ * the keys this actually carries can collide anyway — an `ed25519:` key is
64
+ * base58 (no '=', no '_') and a quote signer is hex — but this reader is
65
+ * generic and the wrong answer here is the silent kind.
66
+ */
67
+ const ENV_LINE = /^(?:export\s+)?([A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+)\s*=(.*)$/;
68
+ /**
69
+ * Read a key out of `path`.
70
+ *
71
+ * Accepts either the `~/.near-credentials` JSON shape or a bare key on one
72
+ * line. Throws `KeyFileError` for anything else — never returns an empty or
73
+ * partial credential, because "I could not read it" collapsing into "there
74
+ * isn't one" is the failure this is built to avoid.
75
+ */
76
+ export function readKeyFile(path) {
77
+ if (!existsSync(path)) {
78
+ throw new KeyFileError(`key file ${path} does not exist. It should hold either the ` +
79
+ `~/.near-credentials shape ${CRED_SHAPE} or the bare key on one line.`);
80
+ }
81
+ let raw;
82
+ try {
83
+ // Checked explicitly: readFileSync on a directory throws EISDIR, and an
84
+ // errno in an error message is not a diagnosis.
85
+ if (statSync(path).isDirectory()) {
86
+ throw new KeyFileError(`key file ${path} is a directory, not a file.`);
87
+ }
88
+ raw = readFileSync(path, "utf8");
89
+ }
90
+ catch (e) {
91
+ if (e instanceof KeyFileError)
92
+ throw e;
93
+ const code = e.code;
94
+ throw new KeyFileError(`key file ${path} could not be read${code ? ` (${code})` : ""}.`);
95
+ }
96
+ /**
97
+ * A BOM IS ALREADY HANDLED, by `trim()`, and that is worth a sentence
98
+ * because it does not look handled.
99
+ *
100
+ * PowerShell's Set-Content and Out-File write a U+FEFF by default, so any
101
+ * file the operator has touched from a one-liner carries one, and left in
102
+ * place it becomes part of the secret or of the first JSON key's name — a
103
+ * failure whose cause is invisible. env-file.ts strips it explicitly, so the
104
+ * obvious thing here was to copy that.
105
+ *
106
+ * It is not needed. U+FEFF satisfies the spec's WhiteSpace production, so
107
+ * `String.prototype.trim` removes it (verified on node 24.14:
108
+ * `/^\s$/.test("")` is true). An explicit `startsWith("") ?
109
+ * slice(1)` ahead of this line is therefore dead code — it was written, and
110
+ * mutation testing exposed it: deleting it killed no test, because it could
111
+ * not change any outcome.
112
+ *
113
+ * The `tolerates CRLF and a BOM` test stays, pinning the real behaviour
114
+ * rather than the redundant guard.
115
+ */
116
+ const trimmed = raw.trim();
117
+ // EMPTY IS NOT ABSENT. A zero-byte key file resolving to "no key configured"
118
+ // would send the operator to set a variable they have already set, while the
119
+ // real fault is the file they are pointing at.
120
+ if (!trimmed) {
121
+ throw new KeyFileError(`key file ${path} is empty — there is no key in it.`);
122
+ }
123
+ // `[` as well as `{`: a JSON array must be named as the wrong shape, not fed
124
+ // to the bare-key reader, which would otherwise accept the literal text
125
+ // `["ed25519:..."]` as a secret.
126
+ if (trimmed.startsWith("{") || trimmed.startsWith("["))
127
+ return fromJson(trimmed, path);
128
+ return { secret: fromBare(trimmed, path) };
129
+ }
130
+ function fromJson(text, path) {
131
+ let parsed;
132
+ try {
133
+ parsed = JSON.parse(text);
134
+ }
135
+ catch {
136
+ /**
137
+ * THE PARSER'S MESSAGE IS DELIBERATELY DROPPED, and this is load-bearing
138
+ * rather than tidiness.
139
+ *
140
+ * V8 quotes a run of the input in its `is not valid JSON` form. Measured on
141
+ * node 24.14 against a credentials file whose private_key had been
142
+ * hand-edited and left unquoted:
143
+ *
144
+ * Unexpected token 'e', ..."ate_key": ed25519:3D"... is not valid JSON
145
+ *
146
+ * Forwarding that publishes the head of the key — into a terminal, a pm2
147
+ * log, or an agent transcript, which is the exact exposure this module
148
+ * exists to close. Pinned by `unquoted JSON value` in the leak test.
149
+ */
150
+ throw new KeyFileError(`key file ${path} is not valid JSON. Expected the ~/.near-credentials shape ` +
151
+ `${CRED_SHAPE}, or a bare key on one line.`);
152
+ }
153
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
154
+ throw new KeyFileError(`key file ${path} is JSON but not an object. Expected the ~/.near-credentials ` +
155
+ `shape ${CRED_SHAPE}.`);
156
+ }
157
+ const o = parsed;
158
+ const secret = typeof o.private_key === "string" ? o.private_key.trim() : "";
159
+ if (!secret) {
160
+ // FIELD NAMES, NEVER VALUES. The names are the whole diagnosis: a file
161
+ // written by a tool that calls it `secret` or `privateKey` is otherwise
162
+ // indistinguishable from a corrupt one.
163
+ const names = Object.keys(o);
164
+ throw new KeyFileError(`key file ${path} has no usable "private_key". Fields present: ` +
165
+ `${names.length ? names.join(", ") : "none"}. Expected the ~/.near-credentials ` +
166
+ `shape ${CRED_SHAPE}.`);
167
+ }
168
+ const str = (v) => (typeof v === "string" && v.trim() ? v.trim() : undefined);
169
+ return { secret, accountId: str(o.account_id), publicKey: str(o.public_key) };
170
+ }
171
+ function fromBare(text, path) {
172
+ const lines = text
173
+ .split(/\r?\n/)
174
+ .map((l) => l.trim())
175
+ .filter((l) => l && !l.startsWith("#"));
176
+ // Reachable: a file holding nothing but comments trims to something, then
177
+ // filters to nothing.
178
+ if (lines.length === 0) {
179
+ throw new KeyFileError(`key file ${path} is empty — there is no key in it.`);
180
+ }
181
+ // BEFORE the line count, because an env file has many lines and "expected
182
+ // one key" would be a true statement that hides the actual mistake.
183
+ for (const line of lines) {
184
+ const m = ENV_LINE.exec(line);
185
+ if (m && m[2].replace(/=/g, "").trim()) {
186
+ throw new KeyFileError(`key file ${path} looks like an env file: it contains an assignment to ` +
187
+ `${m[1]}. This variable wants a file holding ONLY the key — either the ` +
188
+ `~/.near-credentials shape ${CRED_SHAPE} or the bare key on one line. ` +
189
+ `To load a whole env file instead, use FLOAT_ENV_FILE.`);
190
+ }
191
+ }
192
+ if (lines.length > 1) {
193
+ throw new KeyFileError(`key file ${path} has ${lines.length} content lines; expected exactly one key. ` +
194
+ `Which key signs is which budget is charged, so this is not guessed.`);
195
+ }
196
+ return lines[0];
197
+ }
198
+ /**
199
+ * Decide which of the two variables supplies a secret.
200
+ *
201
+ * The file wins. A failed file read does NOT fall back to the inline value:
202
+ * silently using the config an operator believes they have stopped using is
203
+ * worse than not starting.
204
+ */
205
+ export function resolveKeySource(opts) {
206
+ const warnings = [];
207
+ // Trimmed, and blank treated as absent. `NEAR_VAULT_AGENT_KEY=` in an env
208
+ // file parses to "", and a key made of spaces fails at the signer several
209
+ // frames from its cause. No valid key has surrounding whitespace, so this
210
+ // can only rescue a config that was already broken.
211
+ const inline = (opts.inline ?? "").trim() || undefined;
212
+ const path = (opts.file ?? "").trim() || undefined;
213
+ if (!path) {
214
+ return inline ? { secret: inline, source: "inline", warnings } : { source: "none", warnings };
215
+ }
216
+ if (inline) {
217
+ warnings.push(`${opts.fileVar} is set, so ${opts.inlineVar} is ignored. Remove the inline ` +
218
+ `value: a key held in an env value is printed by any read of the config, ` +
219
+ `which is routine, whereas a path is not a secret.`);
220
+ }
221
+ try {
222
+ const got = readKeyFile(path);
223
+ return {
224
+ secret: got.secret,
225
+ source: "file",
226
+ path,
227
+ accountId: got.accountId,
228
+ publicKey: got.publicKey,
229
+ warnings,
230
+ };
231
+ }
232
+ catch (e) {
233
+ // `source` stays "file" with no secret. A caller that reports this as
234
+ // "nothing configured" has lost the only useful part of the message.
235
+ return { source: "file", path, error: `${opts.fileVar}: ${e.message}`, warnings };
236
+ }
237
+ }
@@ -12,10 +12,6 @@
12
12
  * message can explain *why* a bound exists.
13
13
  */
14
14
  export declare const ONE_YOCTO = "1";
15
- /** Mirrors `AGENT_ACCOUNT_STORAGE` in the contract: 0.05 NEAR. */
16
- export declare const AGENT_ACCOUNT_STORAGE_YOCTO: string;
17
- /** Mirrors `MIN_AGENT_KEY_ALLOWANCE` in the contract: 0.5 NEAR. */
18
- export declare const MIN_AGENT_KEY_ALLOWANCE_YOCTO: string;
19
15
  /**
20
16
  * Gas attached to a payment, for every route.
21
17
  *
@@ -28,7 +24,6 @@ export declare const DEFAULT_GAS_TGAS = 100;
28
24
  export declare const MAX_TOKENS = 4;
29
25
  export declare const MAX_RECIPIENTS = 32;
30
26
  export declare const MAX_LABEL_LEN = 48;
31
- export declare const MAX_SUB_LABEL_LEN = 32;
32
27
  export declare const MAX_COOLDOWN_SEC: number;
33
28
  export declare const MAX_PURGE_LIMIT = 100;
34
29
  export interface HumanTokenLimit {
@@ -51,13 +46,66 @@ export interface OwnerPayload {
51
46
  export declare function planAddNode(vault: string, parent: number | null, label: string, limits: HumanTokenLimit[], cooldownSec: number, recipients: string[] | null): OwnerPayload;
52
47
  export declare function planSetNodeCaps(vault: string, nodeId: number, limits: HumanTokenLimit[]): OwnerPayload;
53
48
  export declare function planBindAgent(vault: string, nodeId: number, accountId: string): OwnerPayload;
54
- export declare function planCreateAgentAccount(vault: string, nodeId: number, subLabel: string, publicKey: string, keyAllowanceNear: string): OwnerPayload;
49
+ /**
50
+ * A whole departmental agent in ONE owner signature: node, binding, gas key.
51
+ *
52
+ * WHY THIS IS NOT `add_node` + `bind_virtual_agent` + an AddKey.
53
+ *
54
+ * Installing a gas key is an `AddKey` action, and NEAR requires
55
+ * `signer_id == receiver_id` for one. The owner signing a transaction TO the
56
+ * vault cannot carry it — only the vault can key itself. A browser wallet
57
+ * signs as the connected account and cannot sign as the vault, so composing
58
+ * this client-side would make fleet expansion CLI-only.
59
+ *
60
+ * And the node id cannot be threaded: `add_node` returns it, but no client
61
+ * can read one action's return value inside the same transaction, and
62
+ * predicting it from `next_node_id` races a concurrent `add_node`.
63
+ *
64
+ * So the contract does all three. This is one plain FunctionCall.
65
+ *
66
+ * THE DEPOSIT IS THE GAS KEY'S ENTIRE BALANCE, and that balance is its
67
+ * spending cap — a gas key's `allowance` is null by design. It is not a fee:
68
+ * the owner can reclaim it, because `WithdrawFromGasKey` is account-signed
69
+ * and the vault carries the owner's full-access key.
70
+ */
71
+ export declare function planAddRole(vault: string, label: string, limits: HumanTokenLimit[], cooldownSec: number, recipients: string[] | null, publicKey: string, fundingYocto: string): OwnerPayload;
72
+ export declare function planBindVirtualAgent(vault: string, nodeId: number, publicKey: string): OwnerPayload;
73
+ /**
74
+ * Revoke a virtual agent's authority.
75
+ *
76
+ * Frees the 82-byte `pubkey_to_node` entry. The 86-byte `pubkey_to_nonce`
77
+ * entry is RETAINED deliberately and never reclaimed — confirmed live, where
78
+ * next_nonce stayed at 2 instead of resetting to 1. Dropping it would let
79
+ * unbind-then-rebind reset the nonce and reopen the replay window, so about
80
+ * half the binding's storage is intentionally unrecoverable.
81
+ */
82
+ export declare function planUnbindVirtualAgent(vault: string, publicKey: string): OwnerPayload;
55
83
  export declare function planSetRecipients(vault: string, nodeId: number, recipients: string[] | null): OwnerPayload;
56
84
  export declare function planSetCooldown(vault: string, nodeId: number, cooldownSec: number): OwnerPayload;
57
85
  export declare function planFreezeNode(vault: string, nodeId: number, frozen: boolean): OwnerPayload;
58
86
  export declare function planSetPaused(vault: string, paused: boolean): OwnerPayload;
59
87
  export declare function planSetStrictAllocation(vault: string, strict: boolean): OwnerPayload;
60
88
  export declare function planPurgeSettled(vault: string, beforeDay: number, limit: number): OwnerPayload;
89
+ /**
90
+ * Move tokens out of the vault, to anywhere the owner says.
91
+ *
92
+ * THE STEP THAT DECIDES WHETHER MONEY SURVIVES A TEARDOWN. Deleting a NEAR
93
+ * account does NOT return its fungible tokens — the token ledger keeps a row
94
+ * keyed to an account nobody can ever sign for again. So this is not hygiene
95
+ * before closing a vault, it is the difference between recovering a balance
96
+ * and burning it, and `scripts/teardown-vault.mjs` runs it first for exactly
97
+ * that reason.
98
+ *
99
+ * BASE UNITS, NOT HUMAN ONES. `withdraw` passes the amount straight to
100
+ * `ft_transfer`, so this takes what the token uses. The caller scales, and
101
+ * the summary says the human figure so the two cannot silently disagree in
102
+ * the wallet.
103
+ *
104
+ * The contract refuses a zero amount (`amount must be positive`), so this
105
+ * does too — refusing here means the owner is not sent to a wallet to sign
106
+ * something that will revert and cost gas to learn.
107
+ */
108
+ export declare function planWithdraw(vault: string, token: string, amountBase: string, receiverId: string, decimals: number): OwnerPayload;
61
109
  /** Registry used by the MCP server, and asserted against the contract's method list. */
62
110
  export declare const OWNER_PLANNERS: {
63
111
  readonly add_node: {
@@ -72,9 +120,17 @@ export declare const OWNER_PLANNERS: {
72
120
  readonly methodName: "bind_agent";
73
121
  readonly fn: typeof planBindAgent;
74
122
  };
75
- readonly create_agent_account: {
76
- readonly methodName: "create_agent_account";
77
- readonly fn: typeof planCreateAgentAccount;
123
+ readonly add_role: {
124
+ readonly methodName: "add_role";
125
+ readonly fn: typeof planAddRole;
126
+ };
127
+ readonly bind_virtual_agent: {
128
+ readonly methodName: "bind_virtual_agent";
129
+ readonly fn: typeof planBindVirtualAgent;
130
+ };
131
+ readonly unbind_virtual_agent: {
132
+ readonly methodName: "unbind_virtual_agent";
133
+ readonly fn: typeof planUnbindVirtualAgent;
78
134
  };
79
135
  readonly set_recipients: {
80
136
  readonly methodName: "set_recipients";
@@ -100,6 +156,10 @@ export declare const OWNER_PLANNERS: {
100
156
  readonly methodName: "purge_settled";
101
157
  readonly fn: typeof planPurgeSettled;
102
158
  };
159
+ readonly withdraw: {
160
+ readonly methodName: "withdraw";
161
+ readonly fn: typeof planWithdraw;
162
+ };
103
163
  };
104
164
  /** A ready-to-run command, so approving does not require trusting this server. */
105
165
  export declare function toCliCommand(p: OwnerPayload, network?: string): string;