neozip-mcp 0.1.0-beta → 0.8.0-beta.2

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/CHANGELOG.md CHANGED
@@ -2,6 +2,36 @@
2
2
 
3
3
  Release notes for [neozip-mcp](https://www.npmjs.com/package/neozip-mcp).
4
4
 
5
+ ## 0.8.0-beta.2 (2026-07-04)
6
+
7
+ - **neozipkit & neozip-blockchain 0.8.0.** Production dependencies updated to
8
+ `neozipkit@^0.8.0` and `neozip-blockchain@^0.8.0` (npm), aligned with the
9
+ latest NeoZip library releases.
10
+ - **Shared Token Service clients.** Account, funding, and identity HTTP clients
11
+ now come from `neozip-blockchain@0.8.0` (`neozip-blockchain/token-service`)
12
+ instead of a local duplicate, matching `neozip-cli`. Internal refactor with no
13
+ user-facing behavioral change to existing tools.
14
+ - **Silent token refresh.** An expired Token Service access token is now renewed
15
+ automatically via a local Data Wallet signature (SIWE-style wallet-login) when
16
+ a wallet is configured. Startup no longer hard-fails on an expired token that
17
+ can be silently renewed, and Bearer tools (`stamp`, `upgrade_timestamped`,
18
+ `identity_status`, blockchain verification) refresh best-effort before running.
19
+ - **New gated `fund_wallet` tool.** Request a small native-gas grant for the
20
+ Data Wallet from the Token Service. `action: policy | status | request`
21
+ (default `status`); `policy`/`status` are read-only. The `request` action is
22
+ deliberately gated so an agent cannot spend by accident: it requires
23
+ `NEOZIP_MCP_ALLOW_FUNDING=1`, `confirm: true`, and a testnet chain (override
24
+ with `NEOZIP_MCP_ALLOW_MAINNET_FUNDING=1`). The recipient is the account's own
25
+ primary Data Wallet, chosen server-side and not redirectable. `wallet_info`
26
+ and `mint` now surface a low-balance hint pointing at this tool (no
27
+ auto-funding).
28
+ - **`neozip-connect fund`** subcommand (`policy|status|request`, testnet-default)
29
+ for human parity with the MCP tool.
30
+
31
+ ## 0.1.0-beta.1 (2026-06-28)
32
+
33
+ Documentation fix: clarify that npmjs.com shows `npm i neozip-mcp` but the correct install is **`npm install -g neozip-mcp@beta`**. Workspace setup examples now use `$(npm root -g)/neozip-mcp` instead of `node_modules/neozip-mcp/`.
34
+
5
35
  ## 0.1.0-beta (2026-06-26)
6
36
 
7
37
  First npm release (**beta**).
package/README.md CHANGED
@@ -15,7 +15,7 @@
15
15
 
16
16
  ## Release notice
17
17
 
18
- **Current version: v0.1.0-beta.** See [CHANGELOG.md](CHANGELOG.md) for details.
18
+ **Current version: v0.8.0-beta.2.** See [CHANGELOG.md](CHANGELOG.md) for details.
19
19
 
20
20
  - **API stability:** MCP tool names and parameters may change before a stable release
21
21
  - **Testing:** Test thoroughly in your MCP host before production use
@@ -69,6 +69,23 @@ Account, identity, and recipient-key tools that talk to the NeoZip Token Service
69
69
 
70
70
  ## Installation
71
71
 
72
+ ### Important: use the beta global install
73
+
74
+ The [npmjs.com package page](https://www.npmjs.com/package/neozip-mcp) shows **`npm i neozip-mcp`** in the sidebar. That command is **not sufficient** for this package:
75
+
76
+ | Command | Problem |
77
+ |---------|---------|
78
+ | `npm i neozip-mcp` | No **`@beta`** tag (version is on the `beta` dist-tag only) and no **`-g`** (CLI bins must be global) |
79
+ | `npm i neozip-mcp@beta` | Still local-only — `neozip-mcp` / `neozip-connect` won't be on your PATH for MCP hosts |
80
+
81
+ **Use this:**
82
+
83
+ ```bash
84
+ npm install -g neozip-mcp@beta
85
+ ```
86
+
87
+ This package sets **`preferGlobal: true`**. MCP hosts (Claude Code, Cursor) spawn `neozip-mcp` from your PATH — a project-local `npm install` is not the supported install path.
88
+
72
89
  ### Prerequisites
73
90
 
74
91
  - Node.js 20.0.0 or higher
@@ -95,6 +112,14 @@ which neozip-connect
95
112
  neozip-connect status
96
113
  ```
97
114
 
115
+ If `which neozip-mcp` prints nothing, add npm's global bin directory to your PATH:
116
+
117
+ ```bash
118
+ export PATH="$(npm config get prefix)/bin:$PATH"
119
+ ```
120
+
121
+ See [Troubleshooting](#troubleshooting) below.
122
+
98
123
  ### Install in MCP hosts
99
124
 
100
125
  | Host | Guide |
@@ -127,7 +152,14 @@ Full index: [docs/installation-guides/README.md](docs/installation-guides/README
127
152
  cp "$pkg/docs/examples/claude/skills/neozip-notarization/SKILL.md" ~/.claude/skills/neozip-notarization/
128
153
  ```
129
154
 
130
- Workspace teams: `cp -R node_modules/neozip-mcp/docs/examples/claude/skills .claude/` and commit.
155
+ Workspace teams (after global install):
156
+
157
+ ```bash
158
+ pkg="$(npm root -g)/neozip-mcp"
159
+ cp -R "$pkg/docs/examples/claude/skills" .claude/
160
+ ```
161
+
162
+ Optional: add `neozip-mcp@beta` as a project devDependency only if you need `node_modules/neozip-mcp/` paths for copying examples — the MCP server itself should still be installed globally.
131
163
 
132
164
  4. Optional always-on memory: copy [`docs/examples/CLAUDE.md.example`](docs/examples/CLAUDE.md.example) to `CLAUDE.md`.
133
165
 
@@ -189,6 +221,26 @@ Connection secrets use **machine-local encryption** in `~/.neozip/connection/`.
189
221
 
190
222
  Token Service email, access token, wallet key, and service URL come from **`neozip-connect`** (`~/.neozip/connection/`), not MCP env or NeoZip Desktop `wallet.json`.
191
223
 
224
+ ## Troubleshooting
225
+
226
+ **Install hangs or never finishes (`npm i neozip-mcp`):**
227
+
228
+ - Do not run a plain local install from the npm sidebar command.
229
+ - Do not run `npm i neozip-mcp` inside the **neozip-mcp source repository** (same package name as the project).
230
+ - Use: `npm install -g neozip-mcp@beta`
231
+
232
+ **`neozip-mcp`: command not found after install:**
233
+
234
+ ```bash
235
+ npm config get prefix
236
+ export PATH="$(npm config get prefix)/bin:$PATH"
237
+ which neozip-mcp
238
+ ```
239
+
240
+ **`No matching version found`:**
241
+
242
+ - The beta release is on the **`beta`** dist-tag. Install with `@beta` (or `@0.8.0-beta`).
243
+
192
244
  ## Documentation
193
245
 
194
246
  The following documentation is included with this package:
@@ -1,7 +1,6 @@
1
- import { getTokenServiceUrl } from "neozip-blockchain/token-service";
1
+ import { getTokenServiceUrl, fetchCoordinatorConfig } from "neozip-blockchain/token-service";
2
2
  import { maskEmail } from "../util/mask.js";
3
3
  import { getActiveProfile, getActiveProfileId, listProfiles, readActiveSecrets, } from "./profile-store.js";
4
- import { fetchCoordinatorConfig } from "./token-service-identity.js";
5
4
  function nextStepsForPhase(phase) {
6
5
  switch (phase) {
7
6
  case "no_profile":
@@ -1,7 +1,7 @@
1
1
  import { IdentityKeyTamperError } from "../archive/identity-key.js";
2
2
  import { fetchCryptoSelf } from "../archive/crypto-self.js";
3
3
  import { buildIdentityKeyInitMessage, wrapNewX25519Keypair, } from "./identity-wrap.js";
4
- import { IdentityKeyConflictError, completeIdentityKeyInit, getIdentityKeyBundle, requestIdentityKeyInitChallenge, } from "./token-service-identity.js";
4
+ import { IdentityKeyConflictError, completeIdentityKeyInit, getIdentityKeyBundle, requestIdentityKeyInitChallenge, } from "neozip-blockchain/token-service";
5
5
  import { rawEoaBytes, signEvmMessage } from "./wallet-evm.js";
6
6
  export async function provisionWalletIdentityKey(params) {
7
7
  const existing = await getIdentityKeyBundle(params.baseUrl, params.accessToken, params.walletId);
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Local orchestration for linking the Data Wallet to a Token Service account.
3
+ *
4
+ * The individual HTTP calls live in `neozip-blockchain/token-service`; this
5
+ * module composes the challenge/complete pairs around a local EVM signer, since
6
+ * signing requires the wallet's private key, which never leaves the MCP host.
7
+ */
8
+ import { requestWalletEnsureChallenge, completeWalletEnsure, requestWalletAttachChallenge, completeWalletAttach, } from "neozip-blockchain/token-service";
9
+ import { signEvmMessage } from "./wallet-evm.js";
10
+ /**
11
+ * Ensure a wallet record exists for `evmAddress` and attach it to the
12
+ * authenticated account as the primary wallet, signing both challenges locally.
13
+ */
14
+ export async function runWalletEnsureAndAttach(baseUrl, accessToken, evmPrivateKey, evmAddress) {
15
+ const ensureCh = await requestWalletEnsureChallenge(baseUrl, evmAddress);
16
+ const ensureSig = await signEvmMessage(evmPrivateKey, ensureCh.message);
17
+ const ensured = await completeWalletEnsure(baseUrl, {
18
+ evmAddress,
19
+ challengeId: ensureCh.challengeId,
20
+ evmSignature: ensureSig,
21
+ });
22
+ const attachCh = await requestWalletAttachChallenge(baseUrl, accessToken, ensured.walletId);
23
+ const attachSig = await signEvmMessage(evmPrivateKey, attachCh.message);
24
+ const { linkId } = await completeWalletAttach(baseUrl, accessToken, ensured.walletId, {
25
+ challengeId: attachCh.challengeId,
26
+ evmSignature: attachSig,
27
+ });
28
+ return { walletId: ensured.walletId, evmAddress: ensured.evmAddress, linkId };
29
+ }
30
+ //# sourceMappingURL=wallet-setup.js.map
@@ -7,7 +7,7 @@ import { isMetadataEntryPath } from "./metadata-paths.js";
7
7
  import { hasRecipientAccessMetadata } from "./recipient-access.js";
8
8
  import { computeMerkleRoot } from "./merkle.js";
9
9
  import { enrichTimestampMetadata } from "./timestamp-network.js";
10
- import { requireTokenServiceConfigured } from "../token-service/require-configured.js";
10
+ import { ensureTokenServiceConfigured } from "../token-service/require-configured.js";
11
11
  export { isMetadataEntryPath } from "./metadata-paths.js";
12
12
  /** Pending TS-SUBMIT archives require live Token Service checks; upgrade for standalone verification. */
13
13
  export function timestampUpgradeWarningLines() {
@@ -74,7 +74,7 @@ export async function verifyArchiveBlockchain(zip, entries, config) {
74
74
  };
75
75
  }
76
76
  if (isTimestampArchiveKind(kind)) {
77
- const tsErr = requireTokenServiceConfigured("Blockchain verification for timestamped archives", config);
77
+ const tsErr = await ensureTokenServiceConfigured("Blockchain verification for timestamped archives", config);
78
78
  if (tsErr) {
79
79
  return {
80
80
  kind,
@@ -2,6 +2,7 @@
2
2
  import "./load-env.js";
3
3
  import { connectFinish, connectDelete, connectLogout, connectMigrate, connectPhoneRequest, connectPhoneVerify, connectRegister, connectRename, connectSelect, connectSetup, connectStatus, connectVerify, connectWalletCreate, connectWalletImportKey, connectWalletImportMnemonic, } from "./connection/onboarding.js";
4
4
  import { buildConnectionDump, formatConnectionDump } from "./connection/dump.js";
5
+ import { connectFund, formatFundResult } from "./connection/funding.js";
5
6
  import { resetConnectionStore } from "./connection/reset.js";
6
7
  import { runInteractiveConnect } from "./connection/interactive.js";
7
8
  import { formatVerboseStatusText } from "./connection/status-report.js";
@@ -57,6 +58,12 @@ function parseArgs(argv) {
57
58
  else if (arg === "--connection-id" && args[i + 1]) {
58
59
  flags.connectionId = args[++i];
59
60
  }
61
+ else if (arg === "--network" && args[i + 1]) {
62
+ flags.network = args[++i];
63
+ }
64
+ else if (arg === "--chain" && args[i + 1]) {
65
+ flags.chain = args[++i];
66
+ }
60
67
  else if (arg === "--help" || arg === "-h") {
61
68
  command = "help";
62
69
  }
@@ -111,6 +118,7 @@ Usage:
111
118
  neozip-connect wallet import-mnemonic --mnemonic "word1 word2 ..." [--force] [--json]
112
119
  neozip-connect wallet import-key --private-key 0x... [--force] [--json]
113
120
  neozip-connect finish [--create-wallet] [--json] [--token-service-url URL]
121
+ neozip-connect fund [policy|status|request] [--network NAME] [--chain ID] [--json]
114
122
  neozip-connect setup --email EMAIL --code CODE [--json] [--token-service-url URL]
115
123
  neozip-connect logout [--json]
116
124
  neozip-connect delete [--json] [--connection-id ID]
@@ -250,6 +258,28 @@ async function main() {
250
258
  createWallet: Boolean(flags.createWallet),
251
259
  });
252
260
  break;
261
+ case "fund": {
262
+ const action = positional[0] ?? "request";
263
+ if (!["policy", "status", "request"].includes(action)) {
264
+ throw new Error("Usage: neozip-connect fund [policy|status|request] [--network NAME] [--chain ID]");
265
+ }
266
+ const network = typeof flags.network === "string" ? flags.network : undefined;
267
+ const chainRaw = typeof flags.chain === "string" ? flags.chain : undefined;
268
+ const chainId = chainRaw ? Number.parseInt(chainRaw, 10) : undefined;
269
+ if (chainRaw && !Number.isFinite(chainId)) {
270
+ throw new Error(`Invalid --chain value: ${chainRaw}`);
271
+ }
272
+ const fundRes = await connectFund({ action, network, chainId, tokenServiceUrl });
273
+ if (json) {
274
+ console.log(JSON.stringify(fundRes, null, 2));
275
+ }
276
+ else {
277
+ console.log(formatFundResult(fundRes));
278
+ }
279
+ if (!fundRes.success)
280
+ process.exit(1);
281
+ return;
282
+ }
253
283
  case "setup": {
254
284
  const email = String(flags.email || "");
255
285
  const code = String(flags.code || "");
@@ -0,0 +1,173 @@
1
+ /**
2
+ * neozip-connect fund — request native gas for the local Data Wallet from the
3
+ * Token Service funding API (human-facing parity with `neozip connect fund`).
4
+ *
5
+ * The Token Service sends a small fixed grant (policy-defined) to the account's
6
+ * primary linked Data Wallet so on-chain operations can pay for gas. The
7
+ * recipient is chosen server-side; the client cannot redirect funds.
8
+ *
9
+ * Actions:
10
+ * policy Show the grant size/cooldown for a chain (no auth).
11
+ * status Show eligibility + recent grants (Bearer).
12
+ * request Request a grant to the Data Wallet (Bearer). [default]
13
+ *
14
+ * This human-invoked path is not env-gated (unlike the MCP fund_wallet tool),
15
+ * but defaults to a testnet network.
16
+ */
17
+ import neoBlockchain from "neozip-blockchain";
18
+ import { FundingUnavailableError, getFundingPolicy, getFundingStatus, requestFundingGrant, } from "neozip-blockchain/token-service";
19
+ import { resolveTokenServiceOrigin } from "./origin.js";
20
+ import { ensureFreshTokenServiceToken } from "./wallet-login.js";
21
+ import { applyActiveConnectionToEnv, getActiveConnection, readActiveConnectionSecrets, } from "./store.js";
22
+ const { getChainIdByName } = neoBlockchain;
23
+ /** Testnet-first default so `fund` never targets mainnet by accident. */
24
+ const DEFAULT_FUND_NETWORK = "base-sepolia";
25
+ const FAUCET_HINT = "Or get testnet ETH from https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet";
26
+ function resolveChain(input) {
27
+ if (typeof input.chainId === "number" && Number.isFinite(input.chainId)) {
28
+ return { chainId: input.chainId, network: input.network?.trim() || "" };
29
+ }
30
+ const network = input.network?.trim() || process.env.NEOZIP_NETWORK?.trim() || DEFAULT_FUND_NETWORK;
31
+ const chainId = getChainIdByName(network);
32
+ return { chainId: chainId ?? null, network };
33
+ }
34
+ export async function connectFund(input) {
35
+ const action = input.action ?? "request";
36
+ const origin = resolveTokenServiceOrigin(input.tokenServiceUrl);
37
+ const { chainId, network } = resolveChain(input);
38
+ if (chainId == null) {
39
+ return {
40
+ success: false,
41
+ action,
42
+ network,
43
+ chainId: null,
44
+ message: network
45
+ ? `Unknown network "${network}". Pass --chain <id> or a supported --network name.`
46
+ : "Could not resolve a chain. Pass --chain <id> or --network <name>.",
47
+ };
48
+ }
49
+ if (action === "policy") {
50
+ try {
51
+ const res = await getFundingPolicy(origin, chainId);
52
+ return {
53
+ success: true,
54
+ action,
55
+ network: res.network || network,
56
+ chainId: res.chainId,
57
+ policy: res.policy,
58
+ message: res.policy.enabled
59
+ ? `Funding is available on ${res.network || network} (chain ${res.chainId}): ${res.policy.grantEth} per grant, ${res.policy.cooldownHours}h cooldown.`
60
+ : `Funding is not enabled on ${res.network || network} (chain ${res.chainId}).`,
61
+ };
62
+ }
63
+ catch (err) {
64
+ return fundError(action, network, chainId, err);
65
+ }
66
+ }
67
+ // status + request both require a Bearer token. Renew silently if possible.
68
+ await ensureFreshTokenServiceToken({ tokenServiceUrl: input.tokenServiceUrl });
69
+ applyActiveConnectionToEnv();
70
+ const secrets = readActiveConnectionSecrets();
71
+ const accessToken = secrets?.accessToken?.trim();
72
+ const meta = getActiveConnection();
73
+ const recipientAddress = meta?.evmAddress ?? null;
74
+ if (!accessToken) {
75
+ return {
76
+ success: false,
77
+ action,
78
+ network,
79
+ chainId,
80
+ recipientAddress,
81
+ message: "No Token Service access token. Run neozip-connect to set up an account, then retry.",
82
+ nextCommand: "neozip-connect",
83
+ };
84
+ }
85
+ if (action === "status") {
86
+ try {
87
+ const status = await getFundingStatus(origin, accessToken, chainId);
88
+ const lines = [];
89
+ lines.push(status.enabled
90
+ ? `Funding enabled on chain ${chainId}.`
91
+ : `Funding not enabled on chain ${chainId}.`);
92
+ lines.push(`Data Wallet: ${status.recipientAddress ?? recipientAddress ?? "unknown"}`);
93
+ if (status.lastGrantAt)
94
+ lines.push(`Last grant: ${status.lastGrantAt}`);
95
+ if (status.nextEligibleAt) {
96
+ lines.push(`Next eligible: ${status.nextEligibleAt}`);
97
+ }
98
+ else if (status.enabled) {
99
+ lines.push("Eligible now.");
100
+ }
101
+ return {
102
+ success: true,
103
+ action,
104
+ network,
105
+ chainId,
106
+ recipientAddress: status.recipientAddress ?? recipientAddress,
107
+ status,
108
+ message: lines.join("\n"),
109
+ nextCommand: status.enabled ? "neozip-connect fund" : undefined,
110
+ };
111
+ }
112
+ catch (err) {
113
+ return fundError(action, network, chainId, err, recipientAddress);
114
+ }
115
+ }
116
+ // action === "request"
117
+ try {
118
+ const grant = await requestFundingGrant(origin, accessToken, chainId);
119
+ if (grant.success) {
120
+ const where = grant.recipientAddress || recipientAddress || "your Data Wallet";
121
+ const tx = grant.transactionHash ? ` (tx ${grant.transactionHash})` : "";
122
+ return {
123
+ success: true,
124
+ action,
125
+ network,
126
+ chainId,
127
+ recipientAddress: grant.recipientAddress || recipientAddress,
128
+ grant,
129
+ message: `Sent ${grant.amountEth} to ${where}${tx}. Status: ${grant.status}.`,
130
+ };
131
+ }
132
+ return {
133
+ success: false,
134
+ action,
135
+ network,
136
+ chainId,
137
+ recipientAddress: grant.recipientAddress || recipientAddress,
138
+ grant,
139
+ message: grant.error ?? `Funding request failed (${grant.errorCode ?? "unknown"}).`,
140
+ nextCommand: grant.errorCode === "NO_DATA_WALLET" ? "neozip-connect" : undefined,
141
+ };
142
+ }
143
+ catch (err) {
144
+ return fundError(action, network, chainId, err, recipientAddress);
145
+ }
146
+ }
147
+ function fundError(action, network, chainId, err, recipientAddress) {
148
+ if (err instanceof FundingUnavailableError) {
149
+ return {
150
+ success: false,
151
+ action,
152
+ network,
153
+ chainId,
154
+ recipientAddress,
155
+ message: `This Token Service does not offer wallet funding. ${FAUCET_HINT}`,
156
+ };
157
+ }
158
+ return {
159
+ success: false,
160
+ action,
161
+ network,
162
+ chainId,
163
+ recipientAddress,
164
+ message: err instanceof Error ? err.message : String(err),
165
+ };
166
+ }
167
+ export function formatFundResult(res) {
168
+ const lines = [res.message];
169
+ if (res.nextCommand)
170
+ lines.push(`Next: ${res.nextCommand}`);
171
+ return lines.join("\n");
172
+ }
173
+ //# sourceMappingURL=funding.js.map
@@ -1,5 +1,6 @@
1
1
  import { provisionWalletIdentityKey } from "../account/identity-provision.js";
2
- import { registerEmailCli, exchangeMagicLinkToken, requestPhoneOtp, runWalletEnsureAndAttach, verifyEmailAndExtractToken, verifyPhoneOtp, } from "../account/token-service-identity.js";
2
+ import { registerEmailCli, exchangeMagicLinkToken, requestPhoneOtp, verifyEmailAndExtractToken, verifyPhoneOtp, } from "neozip-blockchain/token-service";
3
+ import { runWalletEnsureAndAttach } from "../account/wallet-setup.js";
3
4
  import { generateEvmIdentity } from "../account/wallet-evm.js";
4
5
  import { assertCoordinatorWrapSupported, fetchCoordinatorConfigParsed, } from "./coordinator.js";
5
6
  import { activeWalletContext, createLocalWalletIdentity, importWalletFromMnemonic, importWalletFromPrivateKey, requirePhonePreconditions, requireWalletPreconditions, saveImportedWallet, validateWalletImportAgainstServer, WALLET_SETUP_HINT, walletAlreadyConfigured, } from "./wallet-setup.js";
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Silent Token Service token renewal via the local Data Wallet (EVM) signature.
3
+ *
4
+ * The Token Service has no refresh-token grant, but it accepts a SIWE-style
5
+ * wallet-login: prove control of the Data Wallet private key (already the master
6
+ * key for the account's data wallet) and receive a fresh access token without an
7
+ * email OTP. This module performs that exchange and persists the new token,
8
+ * leaving the wallet/identity untouched.
9
+ */
10
+ import { requestWalletLoginChallenge, walletLogin, WalletLoginUnavailableError, } from "neozip-blockchain/token-service";
11
+ import { signEvmMessage } from "../account/wallet-evm.js";
12
+ import { resolveTokenServiceOrigin } from "./origin.js";
13
+ import { applyActiveConnectionToEnv, getActiveConnection, readActiveConnectionSecrets, saveAccessToken, } from "./store.js";
14
+ import { isAccessTokenExpired } from "./token-auth.js";
15
+ /** Attempt a silent wallet-signature token renewal for the active connection. */
16
+ export async function refreshAccessTokenViaWallet(options) {
17
+ const meta = getActiveConnection();
18
+ const secrets = readActiveConnectionSecrets();
19
+ const evmAddress = meta?.evmAddress?.trim();
20
+ const privateKeyHex = secrets?.evmPrivateKeyHex?.trim();
21
+ if (!meta || !evmAddress || !privateKeyHex) {
22
+ return { ok: false, reason: "no_wallet" };
23
+ }
24
+ const origin = resolveTokenServiceOrigin(options?.tokenServiceUrl ?? meta.tokenServiceOrigin);
25
+ const privateKey = privateKeyHex.startsWith("0x") ? privateKeyHex : `0x${privateKeyHex}`;
26
+ try {
27
+ const challenge = await requestWalletLoginChallenge(origin, evmAddress);
28
+ const signature = await signEvmMessage(privateKey, challenge.message);
29
+ const out = await walletLogin(origin, {
30
+ evmAddress,
31
+ challengeId: challenge.challengeId,
32
+ evmSignature: signature,
33
+ });
34
+ saveAccessToken(meta.id, out.accessToken, meta.email ?? out.email ?? "", out.expiresAt);
35
+ applyActiveConnectionToEnv();
36
+ return { ok: true, expiresAt: out.expiresAt };
37
+ }
38
+ catch (err) {
39
+ if (err instanceof WalletLoginUnavailableError) {
40
+ return { ok: false, reason: "unsupported", message: err.message };
41
+ }
42
+ return {
43
+ ok: false,
44
+ reason: "error",
45
+ message: err instanceof Error ? err.message : String(err),
46
+ };
47
+ }
48
+ }
49
+ /**
50
+ * Best-effort: if the active access token is expired and a wallet is available,
51
+ * silently renew it via wallet login. Never throws; callers proceed and let the
52
+ * normal readiness checks surface any remaining problem.
53
+ */
54
+ export async function ensureFreshTokenServiceToken(options) {
55
+ const secrets = readActiveConnectionSecrets();
56
+ if (!secrets?.accessToken || !isAccessTokenExpired(secrets)) {
57
+ return;
58
+ }
59
+ await refreshAccessTokenViaWallet(options);
60
+ }
61
+ //# sourceMappingURL=wallet-login.js.map
@@ -13,6 +13,7 @@ import { stampParameters, executeStamp } from "../tools/stamp.js";
13
13
  import { upgradeTimestampedParameters, executeUpgradeTimestamped } from "../tools/upgrade.js";
14
14
  import { tokenServiceStatusParameters, executeTokenServiceStatus, tokenServiceRegisterParameters, executeTokenServiceRegister, tokenServiceVerifyParameters, executeTokenServiceVerify, } from "../tools/token-service-account.js";
15
15
  import { walletInfoParameters, executeWalletInfo } from "../tools/wallet-info.js";
16
+ import { fundWalletParameters, executeFundWallet } from "../tools/fund-wallet.js";
16
17
  import { walletConfigStatusParameters, executeWalletConfigStatus, } from "../tools/wallet-config-status.js";
17
18
  import { connectStatusParameters, executeConnectStatus, } from "../tools/connect-status.js";
18
19
  import { identityStatusParameters, executeIdentityStatus, } from "../tools/identity-status.js";
@@ -55,6 +56,7 @@ export function registerTools(deps) {
55
56
  registerTool(deps, "token_service_verify", "Verify a NeoZip Token Service email with the 6-digit code from the registration email. Required before timestamping via compress or stamp.", tokenServiceVerifyParameters, (args) => executeTokenServiceVerify(args, resourceLimiter, config));
56
57
  registerTool(deps, "lookup_recipient", "Look up a recipient's Token Service X25519 public key by verified email (GET /crypto/public). Use before compress with options.recipientEmails. Does not return private keys.", lookupRecipientParameters, (args) => executeLookupRecipient(args, resourceLimiter, config));
57
58
  registerTool(deps, "wallet_info", "Display wallet and network status including masked key, address, balance, and supported networks.", walletInfoParameters, (args) => executeWalletInfo(args, auth, resourceLimiter, config.network));
59
+ registerTool(deps, "fund_wallet", "Request a small native-gas grant for the Data Wallet from the NeoZip Token Service. action: policy | status | request (default status). policy/status are read-only. request spends testnet gas and is gated: requires NEOZIP_MCP_ALLOW_FUNDING=1, confirm: true, and a testnet chain (or NEOZIP_MCP_ALLOW_MAINNET_FUNDING=1). The recipient is the account's own primary Data Wallet (server-chosen; not redirectable).", fundWalletParameters, (args) => executeFundWallet(args, resourceLimiter, config));
58
60
  registerTool(deps, "wallet_config_status", "Report how wallet, Token Service, and identity credentials are configured (sources and readiness flags; no secret values).", walletConfigStatusParameters, (args) => executeWalletConfigStatus(args, config, auth));
59
61
  registerTool(deps, "connect_status", "Fast neozip-connect readiness check: phase, store health, compress/blockchain tool readiness, interactive and scriptable next commands. Call before compress with timestamp/tokenize/recipientEmails. No network calls.", connectStatusParameters, (args) => executeConnectStatus(args, config, auth));
60
62
  registerTool(deps, "identity_status", "Query Token Service GET /crypto/self for provisioned X25519 identity (requires NEOZIP_TOKEN_SERVICE_ACCESS_TOKEN in MCP env).", identityStatusParameters, (args) => executeIdentityStatus(args, resourceLimiter, config));
@@ -21,6 +21,7 @@ const TOOL_GROUPS = {
21
21
  "stamp",
22
22
  "upgrade_timestamped",
23
23
  "wallet_info",
24
+ "fund_wallet",
24
25
  "wallet_config_status",
25
26
  "identity_status",
26
27
  "token_service_status",
@@ -42,6 +43,7 @@ const TOOL_GROUPS = {
42
43
  "account_remove",
43
44
  "account_logout",
44
45
  "account_initialize",
46
+ "fund_wallet",
45
47
  "wallet_config_status",
46
48
  "identity_status",
47
49
  "connect_status",
@@ -5,6 +5,7 @@ import { nextConnectCommand, resolveConnectionPhase } from "./connection/phase.j
5
5
  import { promoteReadyActiveConnection } from "./connection/promote-active.js";
6
6
  import { getActiveConnection, readActiveConnectionSecrets, readConnectionPublic, } from "./connection/store.js";
7
7
  import { formatTokenReauthGuidance, isAccessTokenExpired, } from "./connection/token-auth.js";
8
+ import { ensureFreshTokenServiceToken } from "./connection/wallet-login.js";
8
9
  function readConnectionPublicLabel(connectionId) {
9
10
  return readConnectionPublic(connectionId)?.label ?? connectionId;
10
11
  }
@@ -55,7 +56,14 @@ export async function assertAccountReadyForStartup(config) {
55
56
  }
56
57
  const phase = await resolveConnectionPhase(config.tokenServiceUrl ?? undefined);
57
58
  if (phase === "ready") {
58
- const secrets = readActiveConnectionSecrets();
59
+ let secrets = readActiveConnectionSecrets();
60
+ if (isAccessTokenExpired(secrets)) {
61
+ // Best-effort: silently renew via the local Data Wallet before failing.
62
+ await ensureFreshTokenServiceToken({
63
+ tokenServiceUrl: config.tokenServiceUrl ?? undefined,
64
+ });
65
+ secrets = readActiveConnectionSecrets();
66
+ }
59
67
  if (isAccessTokenExpired(secrets)) {
60
68
  const meta = getActiveConnection();
61
69
  const lines = [
@@ -1,6 +1,7 @@
1
1
  import { formatConnectSetupError, isTokenServiceConfigured } from "../connection/setup-guidance.js";
2
2
  import { getActiveConnection, readActiveConnectionSecrets, } from "../connection/store.js";
3
3
  import { formatTokenReauthGuidance, isAccessTokenExpired, } from "../connection/token-auth.js";
4
+ import { ensureFreshTokenServiceToken } from "../connection/wallet-login.js";
4
5
  export { isTokenServiceConfigured, tokenServiceInfoUrl } from "../connection/setup-guidance.js";
5
6
  export function formatTokenServiceRequiredMessage(ability, config) {
6
7
  return formatConnectSetupError(ability, config);
@@ -19,5 +20,16 @@ export function requireTokenServiceConfigured(ability, config) {
19
20
  return null;
20
21
  return formatTokenServiceRequiredMessage(ability, config);
21
22
  }
23
+ /**
24
+ * Async Bearer preflight: attempt a silent wallet-signature token renewal for an
25
+ * expired access token, then run the standard {@link requireTokenServiceConfigured}
26
+ * check. Never throws on refresh failure — the sync check still surfaces guidance.
27
+ */
28
+ export async function ensureTokenServiceConfigured(ability, config) {
29
+ await ensureFreshTokenServiceToken({
30
+ tokenServiceUrl: config.tokenServiceUrl ?? undefined,
31
+ });
32
+ return requireTokenServiceConfigured(ability, config);
33
+ }
22
34
  export { requireWalletForBlockchain } from "../connection/setup-guidance.js";
23
35
  //# sourceMappingURL=require-configured.js.map
@@ -3,7 +3,8 @@ import { buildAccountStatusReport, computeAccountPhase } from "../account/accoun
3
3
  import { formatAccountStatusText } from "../account/format-account-status.js";
4
4
  import { provisionWalletIdentityKey } from "../account/identity-provision.js";
5
5
  import { applyActiveProfileToEnv, createProfile, getActiveProfile, getActiveProfileId, listProfiles, readActiveSecrets, removeProfile, saveAccessToken, saveEvmWallet, saveIdentityProvision, savePhoneVerified, saveWalletLink, selectProfile, logoutProfile, clearProfileCredentialsFromEnv, } from "../account/profile-store.js";
6
- import { registerEmailApp, requestPhoneOtp, runWalletEnsureAndAttach, verifyEmailAndExtractToken, verifyPhoneOtp, } from "../account/token-service-identity.js";
6
+ import { registerEmailApp, requestPhoneOtp, verifyEmailAndExtractToken, verifyPhoneOtp, } from "neozip-blockchain/token-service";
7
+ import { runWalletEnsureAndAttach } from "../account/wallet-setup.js";
7
8
  import { needsPhoneVerification, validatePhoneE164 } from "../connection/phone.js";
8
9
  import { getActiveConnection } from "../connection/store.js";
9
10
  import { evmIdentityFromMnemonic, evmIdentityFromPrivateKey, generateEvmIdentity, } from "../account/wallet-evm.js";
@@ -0,0 +1,191 @@
1
+ /**
2
+ * fund_wallet — request a small native-gas grant for the local Data Wallet from
3
+ * the NeoZip Token Service funding API.
4
+ *
5
+ * The Token Service sends a fixed, cooldown-limited grant to the account's
6
+ * primary linked Data Wallet; the recipient is chosen server-side and cannot be
7
+ * redirected by the client. Because this spends (testnet) funds, the `request`
8
+ * action is deliberately gated so an AI agent cannot fund a wallet by accident:
9
+ *
10
+ * - `NEOZIP_MCP_ALLOW_FUNDING` must be enabled in the MCP environment.
11
+ * - the caller must pass `confirm: true`.
12
+ * - the target chain must be a testnet, unless
13
+ * `NEOZIP_MCP_ALLOW_MAINNET_FUNDING` is enabled.
14
+ *
15
+ * `policy` and `status` are read-only and require no gating.
16
+ */
17
+ import { z } from "zod";
18
+ import neoBlockchain from "neozip-blockchain";
19
+ import { FundingUnavailableError, getFundingPolicy, getFundingStatus, requestFundingGrant, } from "neozip-blockchain/token-service";
20
+ import { resolveTokenServiceOrigin } from "../connection/origin.js";
21
+ import { ensureFreshTokenServiceToken } from "../connection/wallet-login.js";
22
+ import { applyActiveConnectionToEnv, getActiveConnection, readActiveConnectionSecrets, } from "../connection/store.js";
23
+ import { successResult, errorResult } from "../types/index.js";
24
+ const { getChainIdByName } = neoBlockchain;
25
+ /** Testnet chains eligible for funding without an explicit mainnet override. */
26
+ export const TESTNET_CHAIN_IDS = new Set([
27
+ 84532, // Base Sepolia
28
+ 11155111, // Ethereum Sepolia
29
+ 421614, // Arbitrum Sepolia
30
+ ]);
31
+ export function isTestnetChain(chainId) {
32
+ return TESTNET_CHAIN_IDS.has(chainId);
33
+ }
34
+ const FAUCET_HINT = "Or get testnet ETH from https://www.coinbase.com/faucets/base-ethereum-sepolia-faucet";
35
+ /** Typical grant size — balances below this cannot reliably pay for gas. */
36
+ export const LOW_BALANCE_ETH = 0.001;
37
+ export function isLowWalletBalance(balanceEth) {
38
+ const n = typeof balanceEth === "number" ? balanceEth : Number.parseFloat(balanceEth);
39
+ return Number.isFinite(n) && n < LOW_BALANCE_ETH;
40
+ }
41
+ /** One-line hint pointing agents/users at the funding tool (no auto-funding). */
42
+ export function formatLowBalanceFundingHint() {
43
+ return "Low balance — request gas via the fund_wallet tool (action: \"request\", confirm: true; requires NEOZIP_MCP_ALLOW_FUNDING).";
44
+ }
45
+ function envEnabled(value) {
46
+ const s = value?.trim().toLowerCase();
47
+ return s === "1" || s === "true" || s === "yes" || s === "on";
48
+ }
49
+ /**
50
+ * Pure gating decision for the `request` action. Kept separate so it can be unit
51
+ * tested without any network or store access.
52
+ */
53
+ export function evaluateFundingGate(input) {
54
+ if (!input.allowFunding) {
55
+ return {
56
+ allowed: false,
57
+ message: "Funding requests are disabled. Set NEOZIP_MCP_ALLOW_FUNDING=1 in the MCP environment to allow the fund_wallet request action.",
58
+ };
59
+ }
60
+ if (!input.confirm) {
61
+ return {
62
+ allowed: false,
63
+ message: "Funding request requires confirm: true. Re-run fund_wallet with { action: \"request\", confirm: true }.",
64
+ };
65
+ }
66
+ if (!isTestnetChain(input.chainId) && !input.allowMainnetFunding) {
67
+ return {
68
+ allowed: false,
69
+ message: `Refusing to fund a non-testnet chain (chainId ${input.chainId}). Set NEOZIP_MCP_ALLOW_MAINNET_FUNDING=1 to override.`,
70
+ };
71
+ }
72
+ return { allowed: true };
73
+ }
74
+ export const fundWalletParameters = z.object({
75
+ action: z.enum(["policy", "status", "request"]).optional(),
76
+ confirm: z.boolean().optional(),
77
+ options: z
78
+ .object({
79
+ network: z.string().optional(),
80
+ chainId: z.number().optional(),
81
+ serverUrl: z.string().optional(),
82
+ })
83
+ .optional(),
84
+ });
85
+ function resolveChain(args, config) {
86
+ const chainIdArg = args.options?.chainId;
87
+ if (typeof chainIdArg === "number" && Number.isFinite(chainIdArg)) {
88
+ return { chainId: chainIdArg, network: args.options?.network?.trim() || "" };
89
+ }
90
+ const network = args.options?.network?.trim() || config.network;
91
+ const chainId = getChainIdByName(network);
92
+ return { chainId: chainId ?? null, network };
93
+ }
94
+ function fundErrorText(err) {
95
+ if (err instanceof FundingUnavailableError) {
96
+ return `This Token Service does not offer wallet funding. ${FAUCET_HINT}`;
97
+ }
98
+ return err instanceof Error ? err.message : String(err);
99
+ }
100
+ export async function executeFundWallet(args, resourceLimiter, config) {
101
+ try {
102
+ const action = args.action ?? "status";
103
+ const origin = resolveTokenServiceOrigin(args.options?.serverUrl ?? config.tokenServiceUrl ?? undefined);
104
+ const { chainId, network } = resolveChain(args, config);
105
+ if (chainId == null) {
106
+ return errorResult(network
107
+ ? `Unknown network "${network}". Pass options.chainId or a supported options.network.`
108
+ : "Could not resolve a chain. Pass options.chainId or options.network.");
109
+ }
110
+ return await resourceLimiter.withTimeout(async () => {
111
+ if (action === "policy") {
112
+ try {
113
+ const res = await getFundingPolicy(origin, chainId);
114
+ const lines = [];
115
+ lines.push(res.policy.enabled
116
+ ? `Funding available on ${res.network || network} (chain ${res.chainId}): ${res.policy.grantEth} per grant, ${res.policy.cooldownHours}h cooldown.`
117
+ : `Funding is not enabled on ${res.network || network} (chain ${res.chainId}).`);
118
+ if (!isTestnetChain(chainId)) {
119
+ lines.push("Note: this is a non-testnet chain; fund_wallet request needs NEOZIP_MCP_ALLOW_MAINNET_FUNDING=1.");
120
+ }
121
+ return successResult(lines.join("\n"));
122
+ }
123
+ catch (err) {
124
+ return errorResult(fundErrorText(err));
125
+ }
126
+ }
127
+ // status + request both need a Bearer token; renew silently if possible.
128
+ await ensureFreshTokenServiceToken({ tokenServiceUrl: origin });
129
+ applyActiveConnectionToEnv();
130
+ const secrets = readActiveConnectionSecrets();
131
+ const accessToken = secrets?.accessToken?.trim();
132
+ const meta = getActiveConnection();
133
+ const recipientAddress = meta?.evmAddress ?? null;
134
+ if (!accessToken) {
135
+ return errorResult("No Token Service access token. Run neozip-connect to set up an account, then retry.");
136
+ }
137
+ if (action === "status") {
138
+ try {
139
+ const status = await getFundingStatus(origin, accessToken, chainId);
140
+ const lines = [];
141
+ lines.push(status.enabled
142
+ ? `Funding enabled on chain ${chainId}.`
143
+ : `Funding not enabled on chain ${chainId}.`);
144
+ lines.push(`Data Wallet: ${status.recipientAddress ?? recipientAddress ?? "unknown"}`);
145
+ if (status.lastGrantAt)
146
+ lines.push(`Last grant: ${status.lastGrantAt}`);
147
+ if (status.nextEligibleAt) {
148
+ lines.push(`Next eligible: ${status.nextEligibleAt}`);
149
+ }
150
+ else if (status.enabled) {
151
+ lines.push("Eligible now.");
152
+ }
153
+ if (status.enabled) {
154
+ lines.push("");
155
+ lines.push("To request: fund_wallet { action: \"request\", confirm: true } (requires NEOZIP_MCP_ALLOW_FUNDING).");
156
+ }
157
+ return successResult(lines.join("\n"));
158
+ }
159
+ catch (err) {
160
+ return errorResult(fundErrorText(err));
161
+ }
162
+ }
163
+ // action === "request" — enforce gating before spending anything.
164
+ const gate = evaluateFundingGate({
165
+ allowFunding: envEnabled(process.env.NEOZIP_MCP_ALLOW_FUNDING),
166
+ allowMainnetFunding: envEnabled(process.env.NEOZIP_MCP_ALLOW_MAINNET_FUNDING),
167
+ confirm: args.confirm === true,
168
+ chainId,
169
+ });
170
+ if (!gate.allowed) {
171
+ return errorResult(gate.message ?? "Funding request is not allowed.");
172
+ }
173
+ try {
174
+ const grant = await requestFundingGrant(origin, accessToken, chainId);
175
+ if (grant.success) {
176
+ const where = grant.recipientAddress || recipientAddress || "your Data Wallet";
177
+ const tx = grant.transactionHash ? ` (tx ${grant.transactionHash})` : "";
178
+ return successResult(`Sent ${grant.amountEth} to ${where}${tx}. Status: ${grant.status}.`);
179
+ }
180
+ return errorResult(grant.error ?? `Funding request failed (${grant.errorCode ?? "unknown"}).`);
181
+ }
182
+ catch (err) {
183
+ return errorResult(fundErrorText(err));
184
+ }
185
+ }, "fund_wallet");
186
+ }
187
+ catch (err) {
188
+ return errorResult(err instanceof Error ? err.message : String(err));
189
+ }
190
+ }
191
+ //# sourceMappingURL=fund-wallet.js.map
@@ -2,7 +2,7 @@ import { z } from "zod";
2
2
  import { getTokenServiceUrl } from "neozip-blockchain/token-service";
3
3
  import { fetchCryptoSelf } from "../archive/crypto-self.js";
4
4
  import { maskEmail, maskPublicKey } from "../util/mask.js";
5
- import { requireTokenServiceConfigured } from "../token-service/require-configured.js";
5
+ import { ensureTokenServiceConfigured } from "../token-service/require-configured.js";
6
6
  import { successResult, errorResult } from "../types/index.js";
7
7
  export const identityStatusParameters = z.object({
8
8
  options: z
@@ -134,7 +134,7 @@ function formatIdentityStatusText(report) {
134
134
  }
135
135
  export async function executeIdentityStatus(args, resourceLimiter, config) {
136
136
  try {
137
- const tsErr = requireTokenServiceConfigured("identity_status", config);
137
+ const tsErr = await ensureTokenServiceConfigured("identity_status", config);
138
138
  if (tsErr)
139
139
  return errorResult(tsErr);
140
140
  const result = await resourceLimiter.withTimeout(async () => {
@@ -1,7 +1,27 @@
1
1
  import { z } from "zod";
2
+ import { ethers } from "ethers";
3
+ import neoBlockchain from "neozip-blockchain";
2
4
  import { mintArchiveToken } from "../archive/mint-archive.js";
3
5
  import { requireWalletForBlockchain } from "../token-service/require-configured.js";
6
+ import { formatLowBalanceFundingHint, isLowWalletBalance } from "./fund-wallet.js";
4
7
  import { successResult, errorResult } from "../types/index.js";
8
+ const { getNetworkByName } = neoBlockchain;
9
+ /** Best-effort native-balance probe; returns true when the wallet looks underfunded. */
10
+ async function walletLooksUnderfunded(walletKey, network) {
11
+ try {
12
+ const contractConfig = getNetworkByName(network);
13
+ const rpc = contractConfig?.rpcUrls?.[0];
14
+ if (!rpc)
15
+ return false;
16
+ const wallet = new ethers.Wallet(walletKey);
17
+ const provider = new ethers.JsonRpcProvider(rpc);
18
+ const balance = await provider.getBalance(wallet.address);
19
+ return isLowWalletBalance(ethers.formatEther(balance));
20
+ }
21
+ catch {
22
+ return false;
23
+ }
24
+ }
5
25
  export const mintParameters = z.object({
6
26
  merkleRoot: z.string(),
7
27
  options: z
@@ -17,12 +37,21 @@ export async function executeMint(args, auth, resourceLimiter, config, defaultNe
17
37
  return errorResult(preflight);
18
38
  const walletKey = auth.requireWalletKey();
19
39
  const network = args.options?.network || defaultNetwork;
20
- const result = await resourceLimiter.withTimeout(async () => {
21
- return mintArchiveToken(args.merkleRoot, {
22
- walletPrivateKey: walletKey,
23
- network,
24
- });
25
- }, "mint");
40
+ const underfunded = await walletLooksUnderfunded(walletKey, network);
41
+ let result;
42
+ try {
43
+ result = await resourceLimiter.withTimeout(async () => {
44
+ return mintArchiveToken(args.merkleRoot, {
45
+ walletPrivateKey: walletKey,
46
+ network,
47
+ });
48
+ }, "mint");
49
+ }
50
+ catch (mintErr) {
51
+ const msg = mintErr instanceof Error ? mintErr.message : String(mintErr);
52
+ const looksLikeGas = underfunded || /insufficient funds|insufficient balance|exceeds the balance/i.test(msg);
53
+ return errorResult(looksLikeGas ? `${msg}\n\n${formatLowBalanceFundingHint()}` : msg);
54
+ }
26
55
  const lines = [];
27
56
  lines.push("NFT minting completed successfully.");
28
57
  const mintResult = result.mintingResult;
@@ -3,7 +3,7 @@ import neozipkit from "neozipkit";
3
3
  const { HashCalculator } = neozipkit;
4
4
  import { ZipkitNode } from "../neozipkit-node.js";
5
5
  import { embedTimestampMetadata } from "../archive/embed-metadata.js";
6
- import { requireTokenServiceConfigured } from "../token-service/require-configured.js";
6
+ import { ensureTokenServiceConfigured } from "../token-service/require-configured.js";
7
7
  import { successResult, errorResult } from "../types/index.js";
8
8
  export const stampParameters = z.object({
9
9
  input: z.string(),
@@ -16,7 +16,7 @@ export const stampParameters = z.object({
16
16
  });
17
17
  export async function executeStamp(args, sandbox, resourceLimiter, config) {
18
18
  try {
19
- const tsErr = requireTokenServiceConfigured("stamp", config);
19
+ const tsErr = await ensureTokenServiceConfigured("stamp", config);
20
20
  if (tsErr)
21
21
  return errorResult(tsErr);
22
22
  const inputPath = await sandbox.validatePath(args.input);
@@ -1,7 +1,7 @@
1
1
  import { z } from "zod";
2
2
  import * as fs from "fs";
3
3
  import { upgradeTimestampArchive } from "../archive/embed-metadata.js";
4
- import { requireTokenServiceConfigured } from "../token-service/require-configured.js";
4
+ import { ensureTokenServiceConfigured } from "../token-service/require-configured.js";
5
5
  import { successResult, errorResult } from "../types/index.js";
6
6
  export const upgradeTimestampedParameters = z.object({
7
7
  input: z.string(),
@@ -16,7 +16,7 @@ export const upgradeTimestampedParameters = z.object({
16
16
  });
17
17
  export async function executeUpgradeTimestamped(args, sandbox, resourceLimiter, config) {
18
18
  try {
19
- const tsErr = requireTokenServiceConfigured("upgrade_timestamped", config);
19
+ const tsErr = await ensureTokenServiceConfigured("upgrade_timestamped", config);
20
20
  if (tsErr)
21
21
  return errorResult(tsErr);
22
22
  const inputPath = await sandbox.validatePath(args.input);
@@ -3,6 +3,7 @@ import { ethers } from "ethers";
3
3
  import neoBlockchain from "neozip-blockchain";
4
4
  const { getNetworkByName, getChainIdByName, getSupportedNetworkNames } = neoBlockchain;
5
5
  import { AuthGuard } from "../security/auth.js";
6
+ import { formatLowBalanceFundingHint, isLowWalletBalance } from "./fund-wallet.js";
6
7
  import { successResult, errorResult } from "../types/index.js";
7
8
  export const walletInfoParameters = z.object({
8
9
  options: z
@@ -37,7 +38,11 @@ export async function executeWalletInfo(args, auth, resourceLimiter, defaultNetw
37
38
  try {
38
39
  const provider = new ethers.JsonRpcProvider(contractConfig.rpcUrls[0]);
39
40
  const balance = await provider.getBalance(wallet.address);
40
- lines.push(`Balance: ${ethers.formatEther(balance)} ETH`);
41
+ const balanceEth = ethers.formatEther(balance);
42
+ lines.push(`Balance: ${balanceEth} ETH`);
43
+ if (isLowWalletBalance(balanceEth)) {
44
+ lines.push(formatLowBalanceFundingHint());
45
+ }
41
46
  }
42
47
  catch {
43
48
  lines.push("Balance: unable to fetch (RPC unavailable)");
@@ -9,9 +9,9 @@ Tools are enabled via capability groups (`NEOZIP_MCP_CAPABILITIES`, default **`a
9
9
  | Group | Tools |
10
10
  |-------|-------|
11
11
  | `zip` | `compress`, `extract`, `list`, `info`, `test`, `read_entry`, `search_entries`, `grep_entries`, `upgrade_timestamped`, `token_service_status`, `lookup_recipient`, `wallet_config_status`, `identity_status`, **`connect_status`** |
12
- | `blockchain` | `mint`, `verify`, `stamp`, `upgrade_timestamped`, `wallet_info`, `wallet_config_status`, `identity_status`, `token_service_status`, `token_service_register`, `token_service_verify`, `lookup_recipient`, **`connect_status`** |
12
+ | `blockchain` | `mint`, `verify`, `stamp`, `upgrade_timestamped`, `wallet_info`, **`fund_wallet`**, `wallet_config_status`, `identity_status`, `token_service_status`, `token_service_register`, `token_service_verify`, `lookup_recipient`, **`connect_status`** |
13
13
  | `readonly` | `list`, `info`, `test`, `verify`, `wallet_info`, `wallet_config_status`, `identity_status`, `read_entry`, `search_entries`, `grep_entries`, `upgrade_timestamped`, `token_service_status`, `lookup_recipient`, **`connect_status`** |
14
- | `account` | `account_status`, `account_list`, `account_create`, `account_select`, `account_register_email`, `account_verify_email`, `account_create_wallet`, `account_import_wallet`, `account_link_wallet`, `account_provision_identity`, `account_remove`, `account_logout`, `account_initialize`, `wallet_config_status`, `identity_status`, **`connect_status`** |
14
+ | `account` | `account_status`, `account_list`, `account_create`, `account_select`, `account_register_email`, `account_verify_email`, `account_create_wallet`, `account_import_wallet`, `account_link_wallet`, `account_provision_identity`, `account_remove`, `account_logout`, `account_initialize`, **`fund_wallet`**, `wallet_config_status`, `identity_status`, **`connect_status`** |
15
15
 
16
16
  ### `auto` capabilities (default)
17
17
 
@@ -710,7 +710,59 @@ Display wallet and network status. Does not require a wallet key to run, but bal
710
710
 
711
711
  **Output**
712
712
 
713
- Network name, chain ID, contract address, masked wallet key, wallet address, ETH balance (when RPC is available), and list of supported networks.
713
+ Network name, chain ID, contract address, masked wallet key, wallet address, ETH balance (when RPC is available), and list of supported networks. When the balance is below the funding threshold (`0.001 ETH`), a hint points to `fund_wallet`.
714
+
715
+ ---
716
+
717
+ ### `fund_wallet`
718
+
719
+ Request a small native-gas grant for the local Data Wallet from the NeoZip Token Service funding API. The Token Service sends a fixed, cooldown-limited grant to the account's **own primary Data Wallet** — the recipient is chosen server-side and cannot be redirected by the caller.
720
+
721
+ **Parameters**
722
+
723
+ | Name | Type | Required | Description |
724
+ |------|------|----------|-------------|
725
+ | `action` | `string` | No | `policy`, `status`, or `request`. Default `status`. |
726
+ | `confirm` | `boolean` | No | Required (`true`) for `action: request`. |
727
+ | `options` | `object` | No | Chain selection / `serverUrl` override (see below). |
728
+
729
+ **Options**
730
+
731
+ | Name | Type | Default | Description |
732
+ |------|------|---------|-------------|
733
+ | `network` | `string` | `NEOZIP_NETWORK` | Network name used to resolve the chain ID. |
734
+ | `chainId` | `number` | — | Explicit chain ID (overrides `network`). |
735
+ | `serverUrl` | `string` | profile URL | Token Service base URL override. |
736
+
737
+ **Actions**
738
+
739
+ - `policy` — read-only; shows grant size and cooldown for the chain (no auth).
740
+ - `status` — shows eligibility, recipient address, and recent grants (Bearer).
741
+ - `request` — requests a grant (Bearer). **Gated** (see below).
742
+
743
+ **Gating (for `request` only)**
744
+
745
+ To prevent an agent from spending funds by accident, `request` requires **all** of:
746
+
747
+ - `NEOZIP_MCP_ALLOW_FUNDING=1` in the MCP environment.
748
+ - `confirm: true` in the tool input.
749
+ - A **testnet** chain (`84532`, `11155111`, `421614`), unless `NEOZIP_MCP_ALLOW_MAINNET_FUNDING=1`.
750
+
751
+ `policy` and `status` are always readable. An expired access token is silently renewed via the local Data Wallet before `status`/`request`.
752
+
753
+ **Example**
754
+
755
+ ```json
756
+ {
757
+ "action": "request",
758
+ "confirm": true,
759
+ "options": { "network": "base-sepolia" }
760
+ }
761
+ ```
762
+
763
+ **Output**
764
+
765
+ For `policy`/`status`: the funding policy or eligibility summary. For `request`: the grant amount, recipient, transaction hash, and status — or a clear gating/refusal message.
714
766
 
715
767
  ---
716
768
 
@@ -958,6 +1010,8 @@ These settings apply across operations (not per-tool parameters):
958
1010
  | `NEOZIP_MCP_GREP_MAX_SNIPPET_CHARS` | `200` | Max snippet length per grep match |
959
1011
  | `NEOZIP_MCP_GREP_MAX_FILE_BYTES` | `1048576` (1 MB) | Skip grepping individual entries larger than this |
960
1012
  | `NEOZIP_NETWORK` | `base-sepolia` | Default blockchain network |
1013
+ | `NEOZIP_MCP_ALLOW_FUNDING` | unset (off) | Allow the `fund_wallet` `request` action to spend gas |
1014
+ | `NEOZIP_MCP_ALLOW_MAINNET_FUNDING` | unset (off) | Allow `fund_wallet` `request` on non-testnet chains |
961
1015
  | `NEOZIP_TOKEN_SERVICE_INFO_URL` | `{profile URL}/info` | Setup docs link in Token Service error messages |
962
1016
 
963
1017
  Token Service email, access token, wallet key, and service URL are loaded from **neozip-connect** only (`~/.neozip/connection/`).
@@ -12,11 +12,12 @@ This project uses **neozip-mcp** for ZIP and `.nzip` archive operations via MCP
12
12
 
13
13
  ## Setup (maintainers)
14
14
 
15
- Copy from the installed npm package:
15
+ Copy from the globally installed npm package (after `npm install -g neozip-mcp@beta`):
16
16
 
17
17
  ```bash
18
- cp node_modules/neozip-mcp/docs/examples/mcp.json.claude.example .mcp.json
19
- cp -R node_modules/neozip-mcp/docs/examples/claude/skills .claude/
18
+ pkg="$(npm root -g)/neozip-mcp"
19
+ cp "$pkg/docs/examples/mcp.json.claude.example" .mcp.json
20
+ cp -R "$pkg/docs/examples/claude/skills" .claude/
20
21
  ```
21
22
 
22
23
  Or merge this file from `docs/examples/CLAUDE.md.example`.
@@ -49,10 +49,13 @@ Claude Code **merges** scopes by server name; **local** overrides **project**, w
49
49
 
50
50
  ### 1. Add `.mcp.json` to the repo
51
51
 
52
- Copy the example and adjust capabilities/sandbox if needed:
52
+ Copy the example and adjust capabilities/sandbox if needed.
53
+
54
+ **After global install** (`npm install -g neozip-mcp@beta`):
53
55
 
54
56
  ```bash
55
- cp node_modules/neozip-mcp/docs/examples/mcp.json.claude.example .mcp.json
57
+ pkg="$(npm root -g)/neozip-mcp"
58
+ cp "$pkg/docs/examples/mcp.json.claude.example" .mcp.json
56
59
  ```
57
60
 
58
61
  From a neozip-mcp source checkout:
@@ -81,10 +84,11 @@ After `neozip-connect` reaches `phase: ready`, reload MCP so blockchain tools ap
81
84
 
82
85
  ### 2. Add agent skills (recommended)
83
86
 
84
- Copy project skills from the npm package so Claude auto-invokes the right procedures. Commit `.claude/skills/` so every teammate gets the same agent behavior.
87
+ Copy project skills from the globally installed npm package so Claude auto-invokes the right procedures. Commit `.claude/skills/` so every teammate gets the same agent behavior.
85
88
 
86
89
  ```bash
87
- cp -R node_modules/neozip-mcp/docs/examples/claude/skills .claude/
90
+ pkg="$(npm root -g)/neozip-mcp"
91
+ cp -R "$pkg/docs/examples/claude/skills" .claude/
88
92
  ```
89
93
 
90
94
  From a neozip-mcp source checkout:
@@ -101,16 +105,18 @@ cp -R docs/examples/claude/skills .claude/
101
105
  Optional always-on project memory — copy or merge [`docs/examples/CLAUDE.md.example`](../examples/CLAUDE.md.example) to `CLAUDE.md`:
102
106
 
103
107
  ```bash
104
- cp node_modules/neozip-mcp/docs/examples/CLAUDE.md.example CLAUDE.md
108
+ pkg="$(npm root -g)/neozip-mcp"
109
+ cp "$pkg/docs/examples/CLAUDE.md.example" CLAUDE.md
105
110
  # or merge the NeoZip section into an existing CLAUDE.md
106
111
  ```
107
112
 
108
113
  **Cursor teammates (optional)** — same skill content, personal install:
109
114
 
110
115
  ```bash
116
+ pkg="$(npm root -g)/neozip-mcp"
111
117
  mkdir -p ~/.cursor/skills/neozip-mcp ~/.cursor/skills/neozip-notarization
112
- cp node_modules/neozip-mcp/docs/examples/claude/skills/neozip-mcp/SKILL.md ~/.cursor/skills/neozip-mcp/
113
- cp node_modules/neozip-mcp/docs/examples/claude/skills/neozip-notarization/SKILL.md ~/.cursor/skills/neozip-notarization/
118
+ cp "$pkg/docs/examples/claude/skills/neozip-mcp/SKILL.md" ~/.cursor/skills/neozip-mcp/
119
+ cp "$pkg/docs/examples/claude/skills/neozip-notarization/SKILL.md" ~/.cursor/skills/neozip-notarization/
114
120
  ```
115
121
 
116
122
  ### 3. Commit and push
@@ -12,12 +12,14 @@ Step-by-step setup for **neozip-mcp** (**beta**) in common MCP host applications
12
12
 
13
13
  ## Before you configure MCP
14
14
 
15
- 1. **Install the beta package** (Node.js 20+) from npm:
15
+ 1. **Install the beta package globally** (Node.js 20+) — once per machine:
16
16
 
17
17
  ```bash
18
18
  npm install -g neozip-mcp@beta
19
19
  ```
20
20
 
21
+ Do **not** use the npmjs.com sidebar command `npm i neozip-mcp` (missing `@beta` and `-g`). See the package README [Installation](https://www.npmjs.com/package/neozip-mcp) section.
22
+
21
23
  2. **Verify binaries**:
22
24
 
23
25
  ```bash
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "neozip-mcp",
3
- "version": "0.1.0-beta",
4
- "release_date": "2026-06-27",
3
+ "version": "0.8.0-beta.2",
4
+ "release_date": "2026-07-04",
5
5
  "description": "NeoZip MCP server for ZIP archives, blockchain notarization, and AI agent integration (Beta)",
6
6
  "main": "dist/index.js",
7
7
  "bin": {
@@ -31,7 +31,7 @@
31
31
  "pack:dry-run": "npm publish --access public --dry-run",
32
32
  "publish:dry-run": "npm publish --access public --dry-run",
33
33
  "prepublishOnly": "pnpm test && node scripts/verify-pack-leaks.mjs",
34
- "test": "pnpm run build && node --test dist/config/capabilities.test.js dist/archive/archive.test.js dist/archive/encryption.test.js dist/archive/encryption.integration.test.js dist/archive/recipient-lookup.test.js dist/archive/recipient.integration.test.js dist/archive/crypto-self.test.js dist/archive/grep-content.test.js dist/archive/timestamp-network.test.js dist/tools/wallet-config-status.test.js dist/tools/connect-status.test.js dist/tools/identity-status.test.js dist/util/mask.test.js dist/util/token-service-fetch.test.js dist/token-service/require-configured.test.js dist/connection/credentials.test.js dist/connection/setup-guidance.test.js dist/connection/incomplete-setup.test.js dist/account/profile-store.test.js dist/account/account-state.test.js dist/startup-account-gate.test.js dist/connection/origin.test.js dist/connection/store.test.js dist/connection/migrate.test.js dist/connection/desktop-parity.test.js dist/connection/phone.test.js dist/connection/wallet-setup.test.js dist/connection/onboarding.test.js dist/connection/onboarding-phone.test.js dist/connection/onboarding-wallet.test.js dist/connection/onboarding-cli-polish.test.js dist/connection/magic-link.test.js dist/connection/phase.test.js dist/connection/token-auth.test.js dist/connection/interactive.test.js dist/connection/dump.test.js dist/connection/promote-active.test.js dist/connection/reset.test.js",
34
+ "test": "pnpm run build && node --test dist/config/capabilities.test.js dist/archive/archive.test.js dist/archive/encryption.test.js dist/archive/encryption.integration.test.js dist/archive/recipient-lookup.test.js dist/archive/recipient.integration.test.js dist/archive/crypto-self.test.js dist/archive/grep-content.test.js dist/archive/timestamp-network.test.js dist/tools/wallet-config-status.test.js dist/tools/fund-wallet.test.js dist/tools/connect-status.test.js dist/tools/identity-status.test.js dist/util/mask.test.js dist/util/token-service-fetch.test.js dist/token-service/require-configured.test.js dist/connection/credentials.test.js dist/connection/setup-guidance.test.js dist/connection/incomplete-setup.test.js dist/account/profile-store.test.js dist/account/account-state.test.js dist/startup-account-gate.test.js dist/connection/origin.test.js dist/connection/store.test.js dist/connection/migrate.test.js dist/connection/desktop-parity.test.js dist/connection/phone.test.js dist/connection/wallet-setup.test.js dist/connection/onboarding.test.js dist/connection/onboarding-phone.test.js dist/connection/onboarding-wallet.test.js dist/connection/onboarding-cli-polish.test.js dist/connection/magic-link.test.js dist/connection/phase.test.js dist/connection/token-auth.test.js dist/connection/interactive.test.js dist/connection/dump.test.js dist/connection/promote-active.test.js dist/connection/reset.test.js",
35
35
  "test:fixtures:build": "tsx test/scripts/build-archive.ts",
36
36
  "test:fixtures:build-blockchain": "tsx test/scripts/build-blockchain-archives.ts",
37
37
  "test:fixtures:smoke": "tsx test/scripts/smoke.ts",
@@ -45,8 +45,8 @@
45
45
  "ethers": "^6.0.0",
46
46
  "fastmcp": "^4.3.2",
47
47
  "minimatch": "^10.0.3",
48
- "neozip-blockchain": "^0.7.2",
49
- "neozipkit": "^0.7.2",
48
+ "neozip-blockchain": "^0.8.0",
49
+ "neozipkit": "^0.8.0",
50
50
  "zod": "^3.23.0"
51
51
  },
52
52
  "overrides": {