@haven_ai/mcp 0.2.0-alpha.0 → 0.3.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -6,20 +6,8 @@ interface HavenCredentialFile {
6
6
  apiKey: string;
7
7
  delegateKey: string;
8
8
  agentId?: string;
9
- /**
10
- * The Haven account (smart account) the agent spends from — #2908, the
11
- * account-vocabulary name, added EXPLICITLY here (this shape and the
12
- * signer's are separate types; the epic's review found they must not be
13
- * assumed to match). Same value as `safeAddress`.
14
- */
9
+ /** The Haven account (smart account) the agent spends from. */
15
10
  accountAddress?: string;
16
- /**
17
- * @deprecated #2908 — same value as {@link HavenCredentialFile.accountAddress}.
18
- * Removed from this shape in the release after the one carrying #2908
19
- * (#2914). The credential-FILE keys are read permanently — see
20
- * `readAccountAddressField`.
21
- */
22
- safeAddress?: string;
23
11
  delegateAddress?: string;
24
12
  chainId?: number;
25
13
  network?: string;
@@ -55,9 +43,9 @@ interface HavenCredentialSource {
55
43
  * 1. Explicit `path` argument (typically from `--credentials <path>`).
56
44
  * 2. `HAVEN_CREDENTIALS` env var pointing at a credential JSON file.
57
45
  * 3. Inline env vars: `HAVEN_API_KEY` + `HAVEN_DELEGATE_KEY` (+ optional
58
- * `HAVEN_AGENT_ID`, `HAVEN_ACCOUNT_ADDRESS` — or, until #2914, its
59
- * pre-#2908 spellings `HAVEN_WALLET_ADDRESS` / `HAVEN_SAFE_ADDRESS` —
60
- * and `HAVEN_API_URL`).
46
+ * `HAVEN_AGENT_ID`, `HAVEN_ACCOUNT_ADDRESS` and `HAVEN_API_URL`). The
47
+ * pre-#2908 spellings `HAVEN_WALLET_ADDRESS` / `HAVEN_SAFE_ADDRESS` are
48
+ * retired as of #2914.
61
49
  *
62
50
  * The inline-env path exists so that runtime config snippets emitted by the
63
51
  * Haven dashboard (Claude Desktop / Cursor / generic MCP configs) can be a
@@ -113,6 +101,13 @@ interface ToolFailure {
113
101
  nextAction?: string;
114
102
  resume_state?: unknown;
115
103
  body?: unknown;
104
+ /**
105
+ * #2983: carried on `MERCHANT_NOT_READY` — mirrors the hosted MCP's
106
+ * `retry_with_new_quote` (`mcp-context.ts`'s `merchantNotReadyErrorFor`).
107
+ * Genuinely retryable: nothing about the CALL was wrong, the merchant's
108
+ * own wallet needs to recover first.
109
+ */
110
+ retry_with_new_quote?: boolean;
116
111
  }
117
112
  type ToolPayload<T = unknown> = ToolSuccess<T> | ToolFailure;
118
113
  declare function createToolHandlers(haven: HavenClient): Record<HavenMcpToolName, (input: unknown) => Promise<ToolPayload>>;
@@ -155,7 +150,7 @@ interface ConsentInput {
155
150
  /** Agent identity from the credential file, when present. */
156
151
  agentId?: string;
157
152
  /** Haven wallet (Safe) the agent spends from. */
158
- safeAddress?: string;
153
+ accountAddress?: string;
159
154
  /** Agent's delegate EOA — the local signer. */
160
155
  delegateAddress?: string;
161
156
  /** Chain the agent operates on. */
@@ -195,8 +190,8 @@ interface CredentialIdentitySeed {
195
190
  apiKey: string;
196
191
  apiUrl?: string;
197
192
  agentId?: string;
198
- /** Safe address from the credential file, used as a fallback. */
199
- safeAddress?: string;
193
+ /** Account address from the credential file, used as a fallback. */
194
+ accountAddress?: string;
200
195
  /** Delegate address from the credential file, used before live allowance metadata is available. */
201
196
  delegateAddress?: string;
202
197
  /** Chain from the credential file, used as a fallback. */
@@ -260,7 +255,7 @@ declare function createHavenMcpServer(options?: HavenMcpServerOptions): Promise<
260
255
  * `agent_tool_invocations` rows are always attributed to the right tool.
261
256
  */
262
257
  declare const MCP_NAME = "@haven_ai/mcp";
263
- declare const MCP_VERSION = "0.2.0-alpha.0";
258
+ declare const MCP_VERSION = "0.3.0-alpha.0";
264
259
  /**
265
260
  * Refuse to start on an unsupported Node (#1161).
266
261
  *
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
- import { composeDescription, toolDescriptions as toolDescriptions$1, HavenPaymentStateError, HavenSigningError, HavenApiError, AgentPaymentNextAction, HavenError, HavenClient, isSupportedNodeVersion, unsupportedNodeVersionMessage, verifyPaymentReceipt, discoverMerchantMcpUrl, sameUrl } from '@haven_ai/sdk';
3
+ import { composeDescription, toolDescriptions as toolDescriptions$1, HavenPaymentStateError, HavenSigningError, HavenApiError, AgentPaymentNextAction, HavenError, HavenClient, isSupportedNodeVersion, unsupportedNodeVersionMessage, verifyPaymentReceipt, discoverMerchantMcpUrl, sameUrl, AgentPaymentFailureCode } from '@haven_ai/sdk';
4
4
  import { readFile, stat, mkdir, writeFile } from 'fs/promises';
5
5
  import { z } from 'zod/v3';
6
6
  import { createHash } from 'crypto';
@@ -54,7 +54,6 @@ async function loadCredentialsFromFile(path) {
54
54
  delegateKey,
55
55
  agentId: stringField(raw.agent_id ?? raw.agentId),
56
56
  accountAddress,
57
- safeAddress: accountAddress,
58
57
  delegateAddress: stringField(raw.delegate_address ?? raw.delegateAddress),
59
58
  chainId: numberField(raw.chain_id ?? raw.chainId),
60
59
  network: stringField(raw.network),
@@ -84,13 +83,11 @@ async function loadCredentialsFromSplitFiles(identityPath, signerPath) {
84
83
  identity.agent_id ?? identity.agentId,
85
84
  signer.agent_id ?? signer.agentId
86
85
  ),
87
- ...accountAddressTwins(
88
- matchingStringField(
89
- "account_address",
90
- readAccountAddressField(identity),
91
- readAccountAddressField(signer),
92
- { caseInsensitive: true }
93
- )
86
+ accountAddress: matchingStringField(
87
+ "account_address",
88
+ readAccountAddressField(identity),
89
+ readAccountAddressField(signer),
90
+ { caseInsensitive: true }
94
91
  ),
95
92
  delegateAddress: matchingStringField(
96
93
  "delegate_address",
@@ -145,7 +142,7 @@ function loadCredentialsFromEnv() {
145
142
  apiKey,
146
143
  delegateKey,
147
144
  agentId: stringField(process.env.HAVEN_AGENT_ID),
148
- ...accountAddressTwins(readAccountAddressEnv(process.env)),
145
+ accountAddress: readAccountAddressEnv(process.env),
149
146
  chainId: numberField(process.env.HAVEN_CHAIN_ID),
150
147
  network: stringField(process.env.HAVEN_NETWORK),
151
148
  apiUrl: stringField(process.env.HAVEN_API_URL)
@@ -155,10 +152,22 @@ function readAccountAddressField(raw) {
155
152
  return stringField(raw.account_address ?? raw.safe_address ?? raw.safeAddress);
156
153
  }
157
154
  function readAccountAddressEnv(env) {
158
- return stringField(env.HAVEN_ACCOUNT_ADDRESS ?? env.HAVEN_WALLET_ADDRESS ?? env.HAVEN_SAFE_ADDRESS);
159
- }
160
- function accountAddressTwins(address) {
161
- return { accountAddress: address, safeAddress: address };
155
+ const current = stringField(env.HAVEN_ACCOUNT_ADDRESS);
156
+ for (const name of ["HAVEN_WALLET_ADDRESS", "HAVEN_SAFE_ADDRESS"]) {
157
+ const retired = stringField(env[name]);
158
+ if (!retired) continue;
159
+ if (!current) {
160
+ throw new Error(
161
+ `${name} is retired (#2906) \u2014 Haven accounts are addressed as accounts, not Safes. Set HAVEN_ACCOUNT_ADDRESS to the same value. Refusing rather than ignoring it, because an unset account address silently skips the sweep-destination check.`
162
+ );
163
+ }
164
+ if (retired.toLowerCase() !== current.toLowerCase()) {
165
+ throw new Error(
166
+ `${name} and HAVEN_ACCOUNT_ADDRESS were both set to different addresses. Remove the retired name, or make them match \u2014 picking one silently would hide the mismatch.`
167
+ );
168
+ }
169
+ }
170
+ return current;
162
171
  }
163
172
  function stringField(value) {
164
173
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
@@ -372,6 +381,8 @@ function createToolHandlers(haven) {
372
381
  const attempt = () => haven.fetch(merchantUrl, init, { idempotencyKey });
373
382
  let response = await attempt();
374
383
  if (!response.ok) {
384
+ const notReady = await merchantNotReadyErrorFor(response);
385
+ if (notReady) throw notReady;
375
386
  const discovered = await discoverMerchantMcpUrl(merchantUrl);
376
387
  if (!discovered || sameUrl(discovered, merchantUrl)) {
377
388
  throw discoveryMissError(response, merchantUrl, discovered);
@@ -380,6 +391,8 @@ function createToolHandlers(haven) {
380
391
  merchantUrl = discovered;
381
392
  const retryResponse = await attempt();
382
393
  if (!retryResponse.ok) {
394
+ const notReadyAtDiscovered = await merchantNotReadyErrorFor(retryResponse);
395
+ if (notReadyAtDiscovered) throw notReadyAtDiscovered;
383
396
  throw discoveryMissError(retryResponse, merchantUrl, discovered, inputUrl);
384
397
  }
385
398
  response = retryResponse;
@@ -613,12 +626,50 @@ function parseMaybeJson(text) {
613
626
  return text;
614
627
  }
615
628
  }
629
+ var MerchantNotReadyError = class extends Error {
630
+ code = AgentPaymentFailureCode.MerchantNotReady;
631
+ statusCode = 503;
632
+ nextAction = AgentPaymentNextAction.StopAndTellUser;
633
+ // Genuinely retryable — unlike a rejection, nothing about THIS call was
634
+ // wrong; the merchant's own wallet needs to recover first.
635
+ retryWithNewQuote = true;
636
+ constructor(message) {
637
+ super(message);
638
+ this.name = "MerchantNotReadyError";
639
+ }
640
+ };
641
+ async function merchantNotReadyErrorFor(response) {
642
+ if (response.status !== 503) return null;
643
+ let body;
644
+ try {
645
+ body = await response.clone().json();
646
+ } catch {
647
+ return null;
648
+ }
649
+ if (!body || typeof body !== "object" || body.error !== "merchant_not_ready") {
650
+ return null;
651
+ }
652
+ const { reason_code, settlements_remaining, retry_after_s } = body;
653
+ return new MerchantNotReadyError(
654
+ "The merchant refused this call: it cannot settle a payment right now" + (typeof reason_code === "string" ? ` (reason_code: ${reason_code})` : "") + (typeof settlements_remaining === "number" ? `, settlements_remaining: ${settlements_remaining}` : "") + ". No payment was created." + (typeof retry_after_s === "number" ? ` Retry after approximately ${retry_after_s}s.` : " This is often transient; retry later.")
655
+ );
656
+ }
616
657
  function discoveryMissError(response, merchantUrl, discovered, discoveredFromUrl) {
617
658
  const base = discoveredFromUrl ? `Merchant call to ${merchantUrl} failed with HTTP ${response.status} (at the DISCOVERED endpoint ${merchantUrl}, resolved from ${discoveredFromUrl} via the merchant discovery document).` : `Merchant call to ${merchantUrl} failed with HTTP ${response.status}.`;
618
659
  const guidance = discoveredFromUrl ? "" : discovered ? ` Same-origin discovery resolved the same URL (${discovered}), which still did not answer successfully.` : ` No same-origin discovery document was found at /.well-known/haven-demo-merchant or /. If ${merchantUrl} is a base merchant URL, pass the exact MCP endpoint instead (often <origin>/mcp).`;
619
660
  return new HavenApiError(`${base}${guidance}`, response.status || 400);
620
661
  }
621
662
  function normalizeError(err) {
663
+ if (err instanceof MerchantNotReadyError) {
664
+ return {
665
+ success: false,
666
+ code: err.code,
667
+ message: err.message,
668
+ statusCode: err.statusCode,
669
+ nextAction: err.nextAction,
670
+ retry_with_new_quote: err.retryWithNewQuote
671
+ };
672
+ }
622
673
  if (err instanceof HavenPaymentStateError) {
623
674
  return {
624
675
  success: false,
@@ -679,7 +730,7 @@ function computeConsentHash(input) {
679
730
  input.apiKeyPrefix,
680
731
  input.apiUrl ?? "",
681
732
  input.agentId ?? "",
682
- (input.safeAddress ?? "").toLowerCase(),
733
+ (input.accountAddress ?? "").toLowerCase(),
683
734
  (input.delegateAddress ?? "").toLowerCase(),
684
735
  input.chainId ?? ""
685
736
  ].join("|");
@@ -698,7 +749,7 @@ function renderConsentBlock(input, hash) {
698
749
  ];
699
750
  if (input.apiUrl) lines.push(`Haven API: ${input.apiUrl}`);
700
751
  if (input.agentId) lines.push(`Agent ID: ${input.agentId}`);
701
- if (input.safeAddress) lines.push(`Haven wallet (Safe): ${input.safeAddress}`);
752
+ if (input.accountAddress) lines.push(`Haven wallet (Safe): ${input.accountAddress}`);
702
753
  if (input.delegateAddress) lines.push(`Delegate (local signer): ${input.delegateAddress}`);
703
754
  if (typeof input.chainId === "number") lines.push(`Chain ID: ${input.chainId}`);
704
755
  lines.push("");
@@ -805,14 +856,14 @@ async function writeAckFile(path, hash) {
805
856
  }
806
857
  async function consentInputFromClient(haven, seed, toolNames) {
807
858
  let allowanceSummary = seed.allowanceSummary ?? [];
808
- let safeAddress = seed.safeAddress;
859
+ let accountAddress = seed.accountAddress;
809
860
  let delegateAddress = seed.delegateAddress;
810
861
  let chainId = seed.chainId;
811
862
  try {
812
863
  const summary = await haven.getAllowances();
813
864
  const list = isAllowanceSummary(summary) ? summary.allowances : Array.isArray(summary) ? summary : [];
814
865
  if (isAllowanceSummary(summary)) {
815
- safeAddress = summary.accountAddress ?? summary.safeAddress ?? safeAddress;
866
+ accountAddress = summary.accountAddress ?? accountAddress;
816
867
  delegateAddress = summary.delegateAddress;
817
868
  chainId = typeof summary.chainId === "number" ? summary.chainId : chainId;
818
869
  }
@@ -828,7 +879,7 @@ async function consentInputFromClient(haven, seed, toolNames) {
828
879
  apiKeyPrefix: derivePrefix(seed.apiKey),
829
880
  apiUrl: seed.apiUrl,
830
881
  agentId: seed.agentId,
831
- safeAddress,
882
+ accountAddress,
832
883
  delegateAddress,
833
884
  chainId,
834
885
  toolNames,
@@ -870,7 +921,7 @@ async function createHavenMcpServer(options = {}) {
870
921
  return buildMcpServer(haven);
871
922
  }
872
923
  var MCP_NAME = "@haven_ai/mcp";
873
- var MCP_VERSION = "0.2.0-alpha.0";
924
+ var MCP_VERSION = "0.3.0-alpha.0";
874
925
  var MCP_INSTRUCTIONS = [
875
926
  "Haven local MCP server: signs in-process with the delegate key it holds on",
876
927
  "this machine \u2014 the key never leaves this process. Call haven_get_agent",
@@ -943,7 +994,7 @@ async function runConsentGate(haven, credentials, options) {
943
994
  apiKey: credentials.apiKey,
944
995
  apiUrl: credentials.apiUrl,
945
996
  agentId: credentials.agentId,
946
- safeAddress: credentials.accountAddress ?? credentials.safeAddress,
997
+ accountAddress: credentials.accountAddress,
947
998
  delegateAddress: credentials.delegateAddress,
948
999
  chainId: credentials.chainId,
949
1000
  allowanceSummary: credentials.allowanceSummary