@haven_ai/mcp 0.1.2-alpha → 0.1.4-alpha

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/README.md CHANGED
@@ -3,6 +3,11 @@
3
3
  `@haven_ai/mcp` exposes Haven payment primitives as local MCP tools. It is a
4
4
  thin wrapper around `@haven_ai/sdk`.
5
5
 
6
+ For Codex CLI and Claude Code setup, the Haven app leads with this local stdio
7
+ server so a normal restart can load Haven tools without shell environment
8
+ setup. Hosted MCP plus a separate local edge signer remains a fallback shape for
9
+ other runtimes.
10
+
6
11
  The server is intentionally local-only:
7
12
 
8
13
  - It runs in the agent operator's environment, usually as a stdio subprocess.
@@ -27,6 +32,31 @@ Create a private JSON file from the values in the Haven agent handoff:
27
32
 
28
33
  `delegate_key` is required. Without it the MCP server cannot sign locally.
29
34
 
35
+ The Haven connector may also write split credentials:
36
+
37
+ ```sh
38
+ npx @haven_ai/mcp --identity ~/.haven/agents/<agent-id>/identity.json --signer ~/.haven/agents/<agent-id>/signer.json
39
+ ```
40
+
41
+ `identity.json` holds the local API key and setup metadata. `signer.json` holds
42
+ the delegate key. Both files stay on the user's machine.
43
+
44
+ ### Credential file permissions
45
+
46
+ The credential file contains a private key. Restrict it to your user
47
+ immediately after downloading:
48
+
49
+ - macOS / Linux: `chmod 600 /path/to/haven-agent.json`
50
+ - Windows (PowerShell): `icacls "path\to\haven-agent.json" /inheritance:r /grant:r "$env:UserName:R"`
51
+
52
+ On POSIX systems the MCP server checks the file's mode bits at load time and
53
+ prints a warning to stderr if it's readable beyond the owner (e.g. world-
54
+ or group-readable). It does not refuse to start — some controlled
55
+ deployments intentionally widen access — but unattended warnings are a
56
+ strong signal something needs tightening. Avoid storing credentials in
57
+ cloud-synced folders (iCloud, Dropbox, OneDrive) or shared dotfile
58
+ repositories.
59
+
30
60
  ## Claude Desktop
31
61
 
32
62
  ```json
@@ -107,6 +137,7 @@ Acknowledge in one of two ways:
107
137
  This writes `haven-agent.json.ack.json` next to your credential. Future
108
138
  launches pick it up automatically. When the tool set or your on-chain
109
139
  allowance changes, the hash changes and you'll be re-prompted.
140
+ For split credentials, the sidecar is written next to `identity.json`.
110
141
 
111
142
  - **Environment variable.** Copy the printed hash and set
112
143
  `HAVEN_MCP_ACK=<hash>` in the MCP client's `env` block. Useful for
package/dist/cli.cjs CHANGED
@@ -9,9 +9,18 @@ var v3 = require('zod/v3');
9
9
  var crypto = require('crypto');
10
10
  var path = require('path');
11
11
 
12
- async function loadCredentials(path = process.env.HAVEN_CREDENTIALS) {
13
- if (path) {
14
- return loadCredentialsFromFile(path);
12
+ async function loadCredentials(source = process.env.HAVEN_CREDENTIALS) {
13
+ if (typeof source === "string") {
14
+ return loadCredentialsFromFile(source);
15
+ }
16
+ if (source?.credentialsPath) {
17
+ return loadCredentialsFromFile(source.credentialsPath);
18
+ }
19
+ if (source?.identityPath || source?.signerPath) {
20
+ if (!source.identityPath || !source.signerPath) {
21
+ throw new Error("Haven split credentials require both --identity and --signer paths.");
22
+ }
23
+ return loadCredentialsFromSplitFiles(source.identityPath, source.signerPath);
15
24
  }
16
25
  const envCreds = loadCredentialsFromEnv();
17
26
  if (envCreds) return envCreds;
@@ -26,6 +35,7 @@ async function loadCredentialsFromFile(path) {
26
35
  } catch (err) {
27
36
  throw new Error(`Could not read Haven credentials at ${path}: ${err instanceof Error ? err.message : String(err)}`);
28
37
  }
38
+ await warnIfCredentialFilePermissive(path);
29
39
  let raw;
30
40
  try {
31
41
  raw = JSON.parse(rawText);
@@ -45,10 +55,57 @@ async function loadCredentialsFromFile(path) {
45
55
  delegateKey,
46
56
  agentId: stringField(raw.agent_id ?? raw.agentId),
47
57
  safeAddress: stringField(raw.safe_address ?? raw.safeAddress),
58
+ delegateAddress: stringField(raw.delegate_address ?? raw.delegateAddress),
59
+ chainId: numberField(raw.chain_id ?? raw.chainId),
60
+ network: stringField(raw.network),
48
61
  apiUrl: stringField(raw.api_url ?? raw.apiUrl),
62
+ allowanceSummary: allowanceSummaryField(raw.allowance_summary ?? raw.allowanceSummary ?? raw.agent_budget ?? raw.agentBudget),
49
63
  sourcePath: path
50
64
  };
51
65
  }
66
+ async function loadCredentialsFromSplitFiles(identityPath, signerPath) {
67
+ const identity = await readJsonFile(identityPath, "Haven identity credentials");
68
+ const signer = await readJsonFile(signerPath, "Haven signer credentials");
69
+ await warnIfCredentialFilePermissive(identityPath);
70
+ await warnIfCredentialFilePermissive(signerPath);
71
+ const apiKey = stringField(identity.api_key ?? identity.apiKey);
72
+ const delegateKey = stringField(signer.delegate_key ?? signer.delegateKey);
73
+ if (!apiKey) {
74
+ throw new Error("Haven identity credentials are missing api_key.");
75
+ }
76
+ if (!delegateKey) {
77
+ throw new Error("Haven signer credentials are missing delegate_key.");
78
+ }
79
+ return {
80
+ apiKey,
81
+ delegateKey,
82
+ agentId: stringField(identity.agent_id ?? identity.agentId ?? signer.agent_id ?? signer.agentId),
83
+ safeAddress: stringField(identity.safe_address ?? identity.safeAddress ?? signer.safe_address ?? signer.safeAddress),
84
+ delegateAddress: stringField(signer.delegate_address ?? signer.delegateAddress ?? identity.delegate_address ?? identity.delegateAddress),
85
+ chainId: numberField(identity.chain_id ?? identity.chainId ?? signer.chain_id ?? signer.chainId),
86
+ network: stringField(identity.network ?? signer.network),
87
+ apiUrl: stringField(identity.api_url ?? identity.apiUrl),
88
+ allowanceSummary: allowanceSummaryField(
89
+ identity.allowance_summary ?? identity.allowanceSummary ?? identity.agent_budget ?? identity.agentBudget
90
+ ),
91
+ sourcePath: identityPath,
92
+ identityPath,
93
+ signerPath
94
+ };
95
+ }
96
+ async function readJsonFile(path, label) {
97
+ let rawText;
98
+ try {
99
+ rawText = await promises.readFile(path, "utf8");
100
+ } catch (err) {
101
+ throw new Error(`Could not read ${label} at ${path}: ${err instanceof Error ? err.message : String(err)}`);
102
+ }
103
+ try {
104
+ return JSON.parse(rawText);
105
+ } catch {
106
+ throw new Error(`${label} must be JSON.`);
107
+ }
108
+ }
52
109
  function loadCredentialsFromEnv() {
53
110
  const apiKey = stringField(process.env.HAVEN_API_KEY);
54
111
  const delegateKey = stringField(process.env.HAVEN_DELEGATE_KEY);
@@ -64,12 +121,54 @@ function loadCredentialsFromEnv() {
64
121
  delegateKey,
65
122
  agentId: stringField(process.env.HAVEN_AGENT_ID),
66
123
  safeAddress: stringField(process.env.HAVEN_SAFE_ADDRESS),
124
+ chainId: numberField(process.env.HAVEN_CHAIN_ID),
125
+ network: stringField(process.env.HAVEN_NETWORK),
67
126
  apiUrl: stringField(process.env.HAVEN_API_URL)
68
127
  };
69
128
  }
70
129
  function stringField(value) {
71
130
  return typeof value === "string" && value.trim() ? value.trim() : void 0;
72
131
  }
132
+ function numberField(value) {
133
+ if (typeof value === "number" && Number.isFinite(value)) return value;
134
+ if (typeof value === "string" && value.trim() && /^\d+$/.test(value.trim())) return Number(value.trim());
135
+ return void 0;
136
+ }
137
+ function allowanceSummaryField(value) {
138
+ if (!Array.isArray(value)) return void 0;
139
+ const allowances = value.flatMap((item) => {
140
+ if (!item || typeof item !== "object") return [];
141
+ const raw = item;
142
+ const token = stringField(raw.token ?? raw.token_symbol ?? raw.tokenSymbol);
143
+ const amount = stringField(raw.amount ?? raw.allowance_amount ?? raw.allowanceAmount);
144
+ const reset = raw.resetMinutes ?? raw.reset_minutes ?? raw.reset_period_min ?? raw.resetPeriodMin;
145
+ if (!token || !amount) return [];
146
+ return [{
147
+ token,
148
+ amount,
149
+ resetMinutes: reset === null ? null : numberField(reset) ?? null
150
+ }];
151
+ });
152
+ return allowances.length > 0 ? allowances : void 0;
153
+ }
154
+ async function warnIfCredentialFilePermissive(path, log = (message) => process.stderr.write(`${message}
155
+ `), platform = process.platform) {
156
+ if (platform === "win32") return;
157
+ let mode;
158
+ try {
159
+ const stats = await promises.stat(path);
160
+ mode = stats.mode;
161
+ } catch {
162
+ return;
163
+ }
164
+ const groupOrOther = mode & 63;
165
+ if (groupOrOther !== 0) {
166
+ const octal = (mode & 511).toString(8).padStart(4, "0");
167
+ log(
168
+ `haven-mcp: warning: credential file at ${path} is readable beyond the owner (mode ${octal}). Run: chmod 600 ${path}`
169
+ );
170
+ }
171
+ }
73
172
  var headersSchema = v3.z.record(v3.z.string(), v3.z.string()).optional();
74
173
  var toolSchemas = {
75
174
  haven_quote_x402: {
@@ -116,17 +215,17 @@ var toolSchemas = {
116
215
  }
117
216
  };
118
217
  var toolDescriptions = {
119
- haven_quote_x402: "Inspect an HTTP 402 x402 paid resource without creating a Haven payment, signature, approval, or on-chain transaction.",
120
- haven_pay_x402_quote: "Pay a previously inspected x402 quote. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions. If approval is needed, preserve the returned resume_state and wait for nextAction=retry_original_x402_request before resuming.",
121
- haven_resume_x402_payment: "Resume an x402 payment after the Haven wallet owner approved the funding step. Accepts either resume_state or payment_id. Only use when get status returns nextAction=retry_original_x402_request; do not start a new merchant session.",
122
- haven_quote_mpp: "Inspect a Haven MPP challenge or paid MPP URL without creating a Haven payment, signature, approval, or on-chain transaction.",
123
- haven_pay_mpp_challenge: "Pay a previously inspected MPP challenge. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions. If approval is needed, preserve resume_state or payment_id.",
124
- haven_resume_mpp_payment: "Resume an MPP payment after the Haven wallet owner approved the funding step. Accepts either resume_state or payment_id and retries the original paid resource.",
125
- haven_get_payment_status: "Fetch structured Haven payment status, including phase and nextAction taxonomy for agent recovery.",
126
- haven_get_resume_state: "Rehydrate stored x402/MPP resume_state by payment_id. This returns context only; signing still happens locally when a resume tool is called.",
127
- haven_get_agent: "Return the authenticated agent identity, Haven wallet, delegate address, chain, and status.",
128
- haven_get_allowances: "Return configured and on-chain allowance state for the authenticated agent. On-chain allowance is the real spend gate.",
129
- haven_list_receipts: "List recent machine-payment receipts/evidence for bookkeeping. Proof header values are not returned."
218
+ haven_quote_x402: sdk.composeDescription(sdk.toolDescriptions.quoteX402),
219
+ haven_pay_x402_quote: sdk.composeDescription(sdk.toolDescriptions.payX402),
220
+ haven_resume_x402_payment: sdk.composeDescription(sdk.toolDescriptions.resumeX402),
221
+ haven_quote_mpp: sdk.composeDescription(sdk.toolDescriptions.quoteMpp),
222
+ haven_pay_mpp_challenge: sdk.composeDescription(sdk.toolDescriptions.payMpp),
223
+ haven_resume_mpp_payment: sdk.composeDescription(sdk.toolDescriptions.resumeMpp),
224
+ haven_get_payment_status: sdk.composeDescription(sdk.toolDescriptions.getPaymentStatus),
225
+ haven_get_resume_state: sdk.composeDescription(sdk.toolDescriptions.getResumeState),
226
+ haven_get_agent: sdk.composeDescription(sdk.toolDescriptions.getAgent),
227
+ haven_get_allowances: sdk.composeDescription(sdk.toolDescriptions.getAllowances),
228
+ haven_list_receipts: sdk.composeDescription(sdk.toolDescriptions.listReceipts)
130
229
  };
131
230
  function createToolHandlers(haven) {
132
231
  return {
@@ -422,10 +521,10 @@ async function writeAckFile(path$1, hash) {
422
521
  );
423
522
  }
424
523
  async function consentInputFromClient(haven, seed, toolNames) {
425
- let allowanceSummary = [];
524
+ let allowanceSummary = seed.allowanceSummary ?? [];
426
525
  let safeAddress = seed.safeAddress;
427
- let delegateAddress;
428
- let chainId;
526
+ let delegateAddress = seed.delegateAddress;
527
+ let chainId = seed.chainId;
429
528
  try {
430
529
  const summary = await haven.getAllowances();
431
530
  const list = isAllowanceSummary(summary) ? summary.allowances : Array.isArray(summary) ? summary : [];
@@ -434,11 +533,12 @@ async function consentInputFromClient(haven, seed, toolNames) {
434
533
  delegateAddress = summary.delegateAddress;
435
534
  chainId = typeof summary.chainId === "number" ? summary.chainId : chainId;
436
535
  }
437
- allowanceSummary = list.map((a) => ({
536
+ const liveAllowanceSummary = list.map((a) => ({
438
537
  token: a.tokenSymbol ?? "UNKNOWN",
439
538
  amount: a.onchain?.amount ?? a.configuredAmount ?? "0",
440
539
  resetMinutes: typeof a.onchain?.resetTimeMin === "number" ? a.onchain.resetTimeMin : typeof a.resetPeriodMin === "number" ? a.resetPeriodMin : null
441
540
  }));
541
+ allowanceSummary = liveAllowanceSummary;
442
542
  } catch {
443
543
  }
444
544
  return {
@@ -464,7 +564,12 @@ function registeredToolNames() {
464
564
 
465
565
  // src/server.ts
466
566
  async function resolveHavenClient(options = {}) {
467
- const credentials = options.credentials ?? await loadCredentials(options.credentialsPath);
567
+ const credentialSource = options.credentialsPath || options.identityPath || options.signerPath ? {
568
+ credentialsPath: options.credentialsPath,
569
+ identityPath: options.identityPath,
570
+ signerPath: options.signerPath
571
+ } : void 0;
572
+ const credentials = options.credentials ?? await loadCredentials(credentialSource);
468
573
  const client = new sdk.HavenClient({
469
574
  apiKey: credentials.apiKey,
470
575
  delegateKey: credentials.delegateKey,
@@ -472,10 +577,12 @@ async function resolveHavenClient(options = {}) {
472
577
  });
473
578
  return { client, credentials };
474
579
  }
580
+ var MCP_NAME = "@haven_ai/mcp";
581
+ var MCP_VERSION = "0.1.4-alpha";
475
582
  function buildMcpServer(haven) {
476
583
  const server = new mcp_js.McpServer({
477
- name: "@haven_ai/mcp",
478
- version: "0.1.0-alpha"
584
+ name: MCP_NAME,
585
+ version: MCP_VERSION
479
586
  });
480
587
  const handlers = createToolHandlers(haven);
481
588
  const registerTool = server.tool.bind(server);
@@ -515,11 +622,14 @@ async function runConsentGate(haven, credentials, options) {
515
622
  apiKey: credentials.apiKey,
516
623
  apiUrl: credentials.apiUrl,
517
624
  agentId: credentials.agentId,
518
- safeAddress: credentials.safeAddress
625
+ safeAddress: credentials.safeAddress,
626
+ delegateAddress: credentials.delegateAddress,
627
+ chainId: credentials.chainId,
628
+ allowanceSummary: credentials.allowanceSummary
519
629
  },
520
630
  toolNames
521
631
  );
522
- const credentialsPath = options.credentialsPath ?? credentials.sourcePath;
632
+ const credentialsPath = options.identityPath ?? options.credentialsPath ?? credentials.sourcePath;
523
633
  return ensureConsent(input, {
524
634
  credentialsPath,
525
635
  writeAck: options.writeAck
@@ -545,6 +655,12 @@ function parseArgs(argv) {
545
655
  if (arg === "--credentials" || arg === "--credentials-path") {
546
656
  options.credentialsPath = argv[i + 1];
547
657
  i += 1;
658
+ } else if (arg === "--identity") {
659
+ options.identityPath = argv[i + 1];
660
+ i += 1;
661
+ } else if (arg === "--signer") {
662
+ options.signerPath = argv[i + 1];
663
+ i += 1;
548
664
  } else if (arg === "--transport") {
549
665
  const transport = argv[i + 1];
550
666
  i += 1;
@@ -559,9 +675,12 @@ function parseArgs(argv) {
559
675
  "",
560
676
  "Usage:",
561
677
  " npx @haven_ai/mcp --credentials /path/to/agent.json",
678
+ " npx @haven_ai/mcp --identity /path/to/identity.json --signer /path/to/signer.json",
562
679
  "",
563
680
  "Options:",
564
681
  " --credentials <path> Haven credential JSON file. Also supported: HAVEN_CREDENTIALS.",
682
+ " --identity <path> Haven identity JSON file written by @haven_ai/connect.",
683
+ " --signer <path> Haven signer JSON file written by @haven_ai/connect.",
565
684
  " --transport stdio Local stdio transport. This is the only supported mode.",
566
685
  " --ack Acknowledge the first-launch consent block and write",
567
686
  " a sidecar acknowledgement file next to the credential.",
package/dist/cli.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/credentials.ts","../src/tools.ts","../src/consent.ts","../src/server.ts","../src/cli.ts"],"names":["readFile","z","HavenApiError","HavenPaymentStateError","HavenSigningError","AgentPaymentNextAction","HavenError","createHash","resolve","path","mkdir","dirname","writeFile","HavenClient","McpServer","StdioServerTransport"],"mappings":";;;;;;;;;;;AAgDA,eAAsB,eAAA,CACpB,IAAA,GAA2B,OAAA,CAAQ,GAAA,CAAI,iBAAA,EACT;AAC9B,EAAA,IAAI,IAAA,EAAM;AACR,IAAA,OAAO,wBAAwB,IAAI,CAAA;AAAA,EACrC;AAEA,EAAA,MAAM,WAAW,sBAAA,EAAuB;AACxC,EAAA,IAAI,UAAU,OAAO,QAAA;AAErB,EAAA,MAAM,IAAI,KAAA;AAAA,IACR;AAAA,GAEF;AACF;AAEA,eAAe,wBAAwB,IAAA,EAA4C;AACjF,EAAA,IAAI,OAAA;AACJ,EAAA,I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AAA,IAAW,GAAA,KAAQ,QAAA,IAAY,GAAA,KAAQ,IAAA,EAAM;AAC3C,MAAA,OAAA,CAAQ,OAAO,KAAA,CAAM;AAAA,QACnB,kBAAA;AAAA,QACA,EAAA;AAAA,QACA,QAAA;AAAA,QACA,uDAAA;AAAA,QACA,EAAA;AAAA,QACA,UAAA;AAAA,QACA,6FAAA;AAAA,QACA,sFAAA;AAAA,QACA,mFAAA;AAAA,QACA,qFAAA;AAAA,QACA,EAAA;AAAA,QACA,UAAA;AAAA,QACA,oEAAA;AAAA,QACA,0EAAA;AAAA,QACA,8EAAA;AAAA,QACA;AAAA,OACF,CAAE,IAAA,CAAK,IAAI,CAAC,CAAA;AACZ,MAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAAA,IAChB;AAAA,EACF;AACA,EAAA,OAAO,OAAA;AACT;AAEA,eAAe,IAAA,GAAsB;AACnC,EAAA,MAAM,eAAe,SAAA,CAAU,OAAA,CAAQ,KAAK,KAAA,CAAM,CAAC,CAAC,CAAC,CAAA;AACvD;AAEA,IAAA,EAAK,CAAE,KAAA,CAAM,CAAC,GAAA,KAAQ;AACpB,EAAA,OAAA,CAAQ,MAAA,CAAO,MAAM,CAAA,EAAG,GAAA,YAAe,QAAQ,GAAA,CAAI,OAAA,GAAU,MAAA,CAAO,GAAG,CAAC;AAAA,CAAI,CAAA;AAC5E,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA","file":"cli.cjs","sourcesContent":["import { readFile } from 'node:fs/promises'\n\nexport interface HavenCredentialFile {\n apiKey: string\n delegateKey: string\n agentId?: string\n safeAddress?: string\n apiUrl?: string\n /**\n * Absolute path the credentials were loaded from, if any. Set when the\n * caller pointed at a JSON file via `--credentials` or `HAVEN_CREDENTIALS`;\n * left undefined when credentials came purely from environment variables.\n * The MCP server uses this to locate the consent sidecar\n * (`<sourcePath>.ack.json`) so `--ack` works regardless of how the\n * credential path was supplied.\n */\n sourcePath?: string\n}\n\ninterface RawCredentialFile {\n api_key?: unknown\n apiKey?: unknown\n delegate_key?: unknown\n delegateKey?: unknown\n agent_id?: unknown\n agentId?: unknown\n safe_address?: unknown\n safeAddress?: unknown\n api_url?: unknown\n apiUrl?: unknown\n}\n\n/**\n * Load Haven agent credentials for the MCP server.\n *\n * Resolution order — earlier sources win, later sources are fallbacks:\n *\n * 1. Explicit `path` argument (typically from `--credentials <path>`).\n * 2. `HAVEN_CREDENTIALS` env var pointing at a credential JSON file.\n * 3. Inline env vars: `HAVEN_API_KEY` + `HAVEN_DELEGATE_KEY` (+ optional\n * `HAVEN_AGENT_ID`, `HAVEN_SAFE_ADDRESS`, `HAVEN_API_URL`).\n *\n * The inline-env path exists so that runtime config snippets emitted by the\n * Haven dashboard (Claude Desktop / Cursor / generic MCP configs) can be a\n * single self-contained block — paste the snippet, restart the runtime, done.\n * The values still live only in the agent operator's process environment;\n * Haven's backend never sees the delegate key either way.\n */\nexport async function loadCredentials(\n path: string | undefined = process.env.HAVEN_CREDENTIALS,\n): Promise<HavenCredentialFile> {\n if (path) {\n return loadCredentialsFromFile(path)\n }\n\n const envCreds = loadCredentialsFromEnv()\n if (envCreds) return envCreds\n\n throw new Error(\n 'No Haven credentials found. Set HAVEN_CREDENTIALS to a Haven agent credential JSON file, ' +\n 'pass --credentials <path>, or set HAVEN_API_KEY and HAVEN_DELEGATE_KEY environment variables.',\n )\n}\n\nasync function loadCredentialsFromFile(path: string): Promise<HavenCredentialFile> {\n let rawText: string\n try {\n rawText = await readFile(path, 'utf8')\n } catch (err) {\n throw new Error(`Could not read Haven credentials at ${path}: ${err instanceof Error ? err.message : String(err)}`)\n }\n\n let raw: RawCredentialFile\n try {\n raw = JSON.parse(rawText) as RawCredentialFile\n } catch {\n throw new Error('Haven credentials must be JSON with api_key and delegate_key fields.')\n }\n\n const apiKey = stringField(raw.api_key ?? raw.apiKey)\n const delegateKey = stringField(raw.delegate_key ?? raw.delegateKey)\n\n if (!apiKey) {\n throw new Error('Haven credentials are missing api_key.')\n }\n if (!delegateKey) {\n throw new Error('Haven MCP requires delegate_key so payments can be signed locally.')\n }\n\n return {\n apiKey,\n delegateKey,\n agentId: stringField(raw.agent_id ?? raw.agentId),\n safeAddress: stringField(raw.safe_address ?? raw.safeAddress),\n apiUrl: stringField(raw.api_url ?? raw.apiUrl),\n sourcePath: path,\n }\n}\n\nfunction loadCredentialsFromEnv(): HavenCredentialFile | null {\n const apiKey = stringField(process.env.HAVEN_API_KEY)\n const delegateKey = stringField(process.env.HAVEN_DELEGATE_KEY)\n\n if (!apiKey && !delegateKey) return null\n\n if (!apiKey) {\n throw new Error('HAVEN_DELEGATE_KEY is set but HAVEN_API_KEY is missing.')\n }\n if (!delegateKey) {\n throw new Error('HAVEN_API_KEY is set but HAVEN_DELEGATE_KEY is missing. Haven MCP requires a delegate key so payments can be signed locally.')\n }\n\n return {\n apiKey,\n delegateKey,\n agentId: stringField(process.env.HAVEN_AGENT_ID),\n safeAddress: stringField(process.env.HAVEN_SAFE_ADDRESS),\n apiUrl: stringField(process.env.HAVEN_API_URL),\n }\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n","import {\n AgentPaymentNextAction,\n HavenApiError,\n HavenClient,\n HavenError,\n HavenPaymentStateError,\n HavenSigningError,\n type MachinePaymentChallenge,\n type MppQuote,\n type MppResumeState,\n type X402Quote,\n type X402ResumeState,\n} from '@haven_ai/sdk'\nimport { z } from 'zod/v3'\n\nconst headersSchema = z.record(z.string(), z.string()).optional()\n\nexport type HavenMcpToolName =\n | 'haven_quote_x402'\n | 'haven_pay_x402_quote'\n | 'haven_resume_x402_payment'\n | 'haven_quote_mpp'\n | 'haven_pay_mpp_challenge'\n | 'haven_resume_mpp_payment'\n | 'haven_get_payment_status'\n | 'haven_get_resume_state'\n | 'haven_get_agent'\n | 'haven_get_allowances'\n | 'haven_list_receipts'\n\nexport const toolSchemas: Record<HavenMcpToolName, z.ZodRawShape> = {\n haven_quote_x402: {\n url: z.string().url(),\n method: z.string().optional(),\n headers: headersSchema,\n body: z.string().optional(),\n idempotencyKey: z.string().optional(),\n },\n haven_pay_x402_quote: {\n quote: z.unknown(),\n idempotencyKey: z.string().optional(),\n },\n haven_resume_x402_payment: {\n payment_id: z.string().optional(),\n resume_state: z.unknown().optional(),\n },\n haven_quote_mpp: {\n url: z.string().url().optional(),\n challenge: z.unknown().optional(),\n method: z.string().optional(),\n headers: headersSchema,\n body: z.string().optional(),\n idempotencyKey: z.string().optional(),\n },\n haven_pay_mpp_challenge: {\n quote: z.unknown(),\n idempotencyKey: z.string().optional(),\n },\n haven_resume_mpp_payment: {\n payment_id: z.string().optional(),\n resume_state: z.unknown().optional(),\n },\n haven_get_payment_status: {\n payment_id: z.string(),\n },\n haven_get_resume_state: {\n payment_id: z.string(),\n },\n haven_get_agent: {},\n haven_get_allowances: {},\n haven_list_receipts: {\n limit: z.number().int().min(1).max(100).optional(),\n },\n}\n\nexport const toolDescriptions: Record<HavenMcpToolName, string> = {\n haven_quote_x402:\n 'Inspect an HTTP 402 x402 paid resource without creating a Haven payment, signature, approval, or on-chain transaction.',\n haven_pay_x402_quote:\n 'Pay a previously inspected x402 quote. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions. If approval is needed, preserve the returned resume_state and wait for nextAction=retry_original_x402_request before resuming.',\n haven_resume_x402_payment:\n 'Resume an x402 payment after the Haven wallet owner approved the funding step. Accepts either resume_state or payment_id. Only use when get status returns nextAction=retry_original_x402_request; do not start a new merchant session.',\n haven_quote_mpp:\n 'Inspect a Haven MPP challenge or paid MPP URL without creating a Haven payment, signature, approval, or on-chain transaction.',\n haven_pay_mpp_challenge:\n 'Pay a previously inspected MPP challenge. The delegate key signs locally; Haven only validates and relays signed, on-chain-constrained payment transactions. If approval is needed, preserve resume_state or payment_id.',\n haven_resume_mpp_payment:\n 'Resume an MPP payment after the Haven wallet owner approved the funding step. Accepts either resume_state or payment_id and retries the original paid resource.',\n haven_get_payment_status:\n 'Fetch structured Haven payment status, including phase and nextAction taxonomy for agent recovery.',\n haven_get_resume_state:\n 'Rehydrate stored x402/MPP resume_state by payment_id. This returns context only; signing still happens locally when a resume tool is called.',\n haven_get_agent:\n 'Return the authenticated agent identity, Haven wallet, delegate address, chain, and status.',\n haven_get_allowances:\n 'Return configured and on-chain allowance state for the authenticated agent. On-chain allowance is the real spend gate.',\n haven_list_receipts:\n 'List recent machine-payment receipts/evidence for bookkeeping. Proof header values are not returned.',\n}\n\nexport interface ToolSuccess<T> {\n success: true\n data: T\n}\n\nexport interface ToolFailure {\n success: false\n code: string\n message: string\n statusCode?: number\n paymentId?: string\n status?: string\n phase?: string\n nextAction?: string\n resume_state?: unknown\n body?: unknown\n}\n\nexport type ToolPayload<T = unknown> = ToolSuccess<T> | ToolFailure\n\nexport function createToolHandlers(haven: HavenClient): Record<HavenMcpToolName, (input: unknown) => Promise<ToolPayload>> {\n return {\n haven_quote_x402: async (input) => {\n const args = objectInput('haven_quote_x402', input)\n return runTool(async () => haven.quoteX402(args.url, requestInit(args), { idempotencyKey: args.idempotencyKey }))\n },\n\n haven_pay_x402_quote: async (input) => {\n const args = objectInput('haven_pay_x402_quote', input)\n return runTool(async () => {\n const response = await haven.payX402Quote(args.quote as X402Quote, { idempotencyKey: args.idempotencyKey })\n return responsePayload(response)\n })\n },\n\n haven_resume_x402_payment: async (input) => {\n const args = objectInput('haven_resume_x402_payment', input)\n return runTool(async () => {\n const state = await resumeState(args, 'x402')\n const response = await haven.resumeX402Payment(state)\n return responsePayload(response)\n })\n },\n\n haven_quote_mpp: async (input) => {\n const args = objectInput('haven_quote_mpp', input)\n return runTool(async () => {\n if (args.challenge) {\n return haven.quoteMpp(args.challenge as MachinePaymentChallenge, requestInit(args), {\n idempotencyKey: args.idempotencyKey,\n })\n }\n if (!args.url) {\n throw new HavenApiError('haven_quote_mpp requires either url or challenge.', 400)\n }\n return haven.quoteMpp(args.url, requestInit(args), { idempotencyKey: args.idempotencyKey })\n })\n },\n\n haven_pay_mpp_challenge: async (input) => {\n const args = objectInput('haven_pay_mpp_challenge', input)\n return runTool(async () => {\n const response = await haven.payMppChallenge(args.quote as MppQuote, { idempotencyKey: args.idempotencyKey })\n return responsePayload(response)\n })\n },\n\n haven_resume_mpp_payment: async (input) => {\n const args = objectInput('haven_resume_mpp_payment', input)\n return runTool(async () => {\n const state = await resumeState(args, 'mpp')\n const response = await haven.resumeMppPayment(state)\n return responsePayload(response)\n })\n },\n\n haven_get_payment_status: async (input) => {\n const args = objectInput('haven_get_payment_status', input)\n return runTool(async () => haven.getPaymentStatus(args.payment_id))\n },\n\n haven_get_resume_state: async (input) => {\n const args = objectInput('haven_get_resume_state', input)\n return runTool(async () => haven.getResumeState(args.payment_id))\n },\n\n haven_get_agent: async () => runTool(async () => haven.getAgent()),\n haven_get_allowances: async () => runTool(async () => haven.getAllowances()),\n haven_list_receipts: async (input) => {\n const args = objectInput('haven_list_receipts', input)\n return runTool(async () => haven.listReceipts({ limit: args.limit }))\n },\n }\n\n async function resumeState(\n args: { payment_id?: string; resume_state?: unknown },\n rail: 'x402' | 'mpp',\n ): Promise<X402ResumeState | MppResumeState> {\n const state =\n args.resume_state ??\n (args.payment_id ? await haven.getResumeState(args.payment_id) : undefined)\n\n if (!state || typeof state !== 'object') {\n throw new HavenApiError(`haven_resume_${rail}_payment requires resume_state or payment_id.`, 400)\n }\n\n if ((state as { rail?: unknown }).rail !== rail) {\n throw new HavenApiError(`Resume state is not for the ${rail} rail.`, 409, state)\n }\n\n return state as X402ResumeState | MppResumeState\n }\n}\n\nfunction objectInput<TName extends HavenMcpToolName>(\n name: TName,\n input: unknown,\n): Record<string, any> {\n return z.object(toolSchemas[name]).parse(input ?? {})\n}\n\nfunction requestInit(input: { method?: string; headers?: Record<string, string>; body?: string }): RequestInit | undefined {\n if (!input.method && !input.headers && input.body === undefined) return undefined\n return {\n method: input.method,\n headers: input.headers,\n body: input.body,\n }\n}\n\nasync function runTool<T>(fn: () => Promise<T>): Promise<ToolPayload<T>> {\n try {\n return { success: true, data: await fn() }\n } catch (err) {\n return normalizeError(err)\n }\n}\n\nasync function responsePayload(response: Response): Promise<Record<string, unknown>> {\n const text = await response.text()\n return {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n body: parseMaybeJson(text),\n }\n}\n\nfunction parseMaybeJson(text: string): unknown {\n if (!text) return null\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\nfunction normalizeError(err: unknown): ToolFailure {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n code: err.code,\n message: err.message,\n statusCode: err.statusCode,\n paymentId: err.paymentId,\n status: err.status,\n phase: err.phase,\n nextAction: err.nextAction,\n resume_state: err.resumeState,\n body: err.body,\n }\n }\n\n if (err instanceof HavenSigningError) {\n return {\n success: false,\n code: err.code,\n message: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n const body = err.body as Record<string, unknown> | undefined\n return {\n success: false,\n code: err.code,\n message: err.message,\n statusCode: err.statusCode,\n paymentId: err.paymentId,\n phase: stringOrUndefined(body?.phase),\n nextAction:\n stringOrUndefined(body?.nextAction) ??\n stringOrUndefined(body?.next_action) ??\n AgentPaymentNextAction.StopAndTellUser,\n body: err.body,\n }\n }\n\n if (err instanceof HavenError) {\n return {\n success: false,\n code: err.code,\n message: err.message,\n statusCode: err.statusCode,\n paymentId: err.paymentId,\n }\n }\n\n return {\n success: false,\n code: 'UNKNOWN_ERROR',\n message: err instanceof Error ? err.message : String(err),\n nextAction: AgentPaymentNextAction.StopAndTellUser,\n }\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n","import { createHash } from 'node:crypto'\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport type { HavenAllowance, HavenAllowanceSummary, HavenClient } from '@haven_ai/sdk'\nimport { toolDescriptions, toolSchemas, type HavenMcpToolName } from './tools.js'\n\n/**\n * First-launch consent gate for the Haven MCP server.\n *\n * Why this exists (option A of issue #163): an agent runtime that loads a\n * Haven credential file is about to expose Haven payment tools to a model.\n * Before the server starts taking JSON-RPC calls we want the operator to\n * acknowledge — exactly once per credential + tool set — what those tools\n * can do and what the on-chain allowance cap actually is. The on-chain\n * AllowanceModule remains the policy primitive; this gate is informational\n * rather than enforcement.\n *\n * Resolution:\n * - `HAVEN_MCP_ACK=<hash>` env var matching the current consent hash → pass.\n * - `HAVEN_MCP_ACK=skip` → pass (intended for CI / scripted setups).\n * - sidecar file `<credentials>.ack.json` containing `{ ack: <hash> }` → pass.\n * - `--ack` CLI flag → write the sidecar file, print the consent block, pass.\n * - otherwise → print the consent block to stderr and exit non-zero.\n *\n * The hash binds the api-key prefix to the registered tool set and the\n * agent's current allowance summary, so a configuration change re-triggers\n * the prompt.\n */\n\nexport interface ConsentInput {\n apiKeyPrefix: string\n /** Haven API base URL the credential will hit. */\n apiUrl?: string\n /** Agent identity from the credential file, when present. */\n agentId?: string\n /** Haven wallet (Safe) the agent spends from. */\n safeAddress?: string\n /** Agent's delegate EOA — the local signer. */\n delegateAddress?: string\n /** Chain the agent operates on. */\n chainId?: number\n toolNames: readonly HavenMcpToolName[]\n allowanceSummary: readonly { token: string; amount: string; resetMinutes: number | null }[]\n}\n\nexport interface ConsentDecision {\n /** True if the gate is satisfied and the server may start. */\n ok: boolean\n /** Hash representing the current consent surface. */\n hash: string\n /** Reason the gate accepted (or rejected) the run. */\n reason:\n | 'env_var_match'\n | 'env_var_skip'\n | 'ack_file_match'\n | 'wrote_ack_file'\n | 'env_var_mismatch'\n | 'no_acknowledgement'\n}\n\nexport interface ConsentOptions {\n /** Path to the credential file; used to locate the sidecar `<path>.ack.json`. */\n credentialsPath?: string\n /** When true, write the sidecar file with the current hash and accept. */\n writeAck?: boolean\n /** Override the environment lookup (testing). */\n env?: Record<string, string | undefined>\n /** Override the writable stream the consent block is printed to (testing). */\n out?: { write: (chunk: string) => unknown }\n}\n\nexport function computeConsentHash(input: ConsentInput): string {\n const allowanceCanonical = [...input.allowanceSummary]\n .map((a) => `${a.token}:${a.amount}:${a.resetMinutes ?? 'none'}`)\n .sort()\n .join('|')\n const toolCanonical = [...input.toolNames].sort().join(',')\n // Identity fields are included in the hash so swapping the credential\n // to a different Haven wallet / delegate / chain — even one with an\n // identical allowance set — invalidates the prior sidecar and re-prompts\n // the operator. Addresses are normalised to lowercase so casing changes\n // in the credential file don't gratuitously re-prompt.\n const identity = [\n input.apiKeyPrefix,\n input.apiUrl ?? '',\n input.agentId ?? '',\n (input.safeAddress ?? '').toLowerCase(),\n (input.delegateAddress ?? '').toLowerCase(),\n input.chainId ?? '',\n ].join('|')\n return createHash('sha256')\n .update(`${identity}\\n${toolCanonical}\\n${allowanceCanonical}`)\n .digest('hex')\n .slice(0, 16)\n}\n\nexport function renderConsentBlock(input: ConsentInput, hash: string): string {\n const lines: string[] = [\n '',\n '────────────────────────────────────────────────────────────',\n 'Haven MCP server — first-launch consent',\n '────────────────────────────────────────────────────────────',\n '',\n `Credential: ${input.apiKeyPrefix}…`,\n ]\n if (input.apiUrl) lines.push(`Haven API: ${input.apiUrl}`)\n if (input.agentId) lines.push(`Agent ID: ${input.agentId}`)\n if (input.safeAddress) lines.push(`Haven wallet (Safe): ${input.safeAddress}`)\n if (input.delegateAddress) lines.push(`Delegate (local signer): ${input.delegateAddress}`)\n if (typeof input.chainId === 'number') lines.push(`Chain ID: ${input.chainId}`)\n lines.push('')\n lines.push('Confirm these match the Haven wallet and chain you intend the')\n lines.push('agent runtime to use. The delegate above is the only key that')\n lines.push('signs payments — it lives in this process, not on Haven\\'s backend.')\n lines.push('')\n lines.push('Tools this server will expose to your agent runtime:')\n for (const name of input.toolNames) {\n lines.push(` • ${name}`)\n lines.push(` ${toolDescriptions[name]}`)\n }\n lines.push('')\n if (input.allowanceSummary.length === 0) {\n lines.push('On-chain allowance: none configured.')\n lines.push(' Any payment will queue for manual approval. The on-chain')\n lines.push(' Safe AllowanceModule is the real spend gate.')\n } else {\n lines.push('On-chain allowance (the real spend gate, Safe AllowanceModule):')\n for (const a of input.allowanceSummary) {\n const reset = a.resetMinutes ? ` per ${a.resetMinutes} min` : ' (no reset)'\n lines.push(` • up to ${a.amount} ${a.token}${reset}`)\n }\n }\n lines.push('')\n lines.push('Anything above the on-chain allowance pauses for owner approval')\n lines.push('in the Haven dashboard. Revoking the agent on-chain disables')\n lines.push('every MCP tool that would spend.')\n lines.push('')\n lines.push(`Consent hash: ${hash}`)\n lines.push('')\n lines.push('To acknowledge, EITHER:')\n lines.push(` • set HAVEN_MCP_ACK=${hash} in this process\\'s environment, OR`)\n lines.push(' • re-run with --ack to write the acknowledgement next to your')\n lines.push(' credential file (sidecar <credentials>.ack.json).')\n lines.push('')\n lines.push('────────────────────────────────────────────────────────────')\n lines.push('')\n return lines.join('\\n')\n}\n\n/** Resolve the consent gate. Does not exit the process; the caller decides. */\nexport async function ensureConsent(\n input: ConsentInput,\n options: ConsentOptions = {},\n): Promise<ConsentDecision> {\n const env = options.env ?? process.env\n const out = options.out ?? process.stderr\n const hash = computeConsentHash(input)\n\n // 1) Explicit skip — for CI and scripted environments.\n if (env.HAVEN_MCP_ACK === 'skip') {\n return { ok: true, hash, reason: 'env_var_skip' }\n }\n\n // 2) Env var hash match.\n if (typeof env.HAVEN_MCP_ACK === 'string' && env.HAVEN_MCP_ACK.length > 0) {\n if (env.HAVEN_MCP_ACK === hash) {\n return { ok: true, hash, reason: 'env_var_match' }\n }\n out.write(renderConsentBlock(input, hash))\n out.write(\n `HAVEN_MCP_ACK was set but did not match the current consent hash.\\n` +\n `Expected: ${hash}\\n` +\n `Got: ${env.HAVEN_MCP_ACK}\\n` +\n `Re-acknowledge with the new hash above, or run with --ack.\\n\\n`,\n )\n return { ok: false, hash, reason: 'env_var_mismatch' }\n }\n\n // 3) Sidecar ack file (only meaningful when we loaded from a file).\n const ackPath = sidecarPath(options.credentialsPath)\n if (ackPath) {\n const stored = await readAckFile(ackPath)\n if (stored?.ack === hash) {\n return { ok: true, hash, reason: 'ack_file_match' }\n }\n }\n\n // 4) --ack: write the sidecar and accept.\n if (options.writeAck && ackPath) {\n out.write(renderConsentBlock(input, hash))\n await writeAckFile(ackPath, hash)\n out.write(`Wrote acknowledgement to ${ackPath}\\n\\n`)\n return { ok: true, hash, reason: 'wrote_ack_file' }\n }\n\n // 5) Otherwise: print and refuse.\n out.write(renderConsentBlock(input, hash))\n return { ok: false, hash, reason: 'no_acknowledgement' }\n}\n\nfunction sidecarPath(credentialsPath?: string): string | null {\n if (!credentialsPath) return null\n return resolve(`${credentialsPath}.ack.json`)\n}\n\nasync function readAckFile(path: string): Promise<{ ack?: string } | null> {\n try {\n const raw = await readFile(path, 'utf8')\n const parsed = JSON.parse(raw) as { ack?: unknown }\n return { ack: typeof parsed.ack === 'string' ? parsed.ack : undefined }\n } catch {\n return null\n }\n}\n\nasync function writeAckFile(path: string, hash: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(\n path,\n JSON.stringify({ ack: hash, at: new Date().toISOString() }, null, 2),\n 'utf8',\n )\n}\n\nexport interface CredentialIdentitySeed {\n apiKey: string\n apiUrl?: string\n agentId?: string\n /** Safe address from the credential file, used as a fallback. */\n safeAddress?: string\n}\n\n/**\n * Build the consent input from credential identity plus a live allowance\n * lookup. The on-chain (or configured) allowance is what the operator\n * actually cares about — that's the real spend ceiling — but we also bind\n * the hash to the Haven wallet / delegate / chain so a credential swap\n * cannot quietly reuse a prior sidecar acknowledgement.\n *\n * If `getAllowances()` fails (e.g. backend unreachable on first launch) we\n * fall through to whatever identity fields the credential file provided,\n * so the operator at least sees the tool list and the api-key prefix.\n */\nexport async function consentInputFromClient(\n haven: HavenClient,\n seed: CredentialIdentitySeed,\n toolNames: readonly HavenMcpToolName[],\n): Promise<ConsentInput> {\n let allowanceSummary: ConsentInput['allowanceSummary'] = []\n let safeAddress = seed.safeAddress\n let delegateAddress: string | undefined\n let chainId: number | undefined\n\n try {\n const summary = await haven.getAllowances()\n const list: HavenAllowance[] = isAllowanceSummary(summary)\n ? summary.allowances\n : Array.isArray(summary)\n ? (summary as HavenAllowance[])\n : []\n if (isAllowanceSummary(summary)) {\n safeAddress = summary.safeAddress ?? safeAddress\n delegateAddress = summary.delegateAddress\n chainId = typeof summary.chainId === 'number' ? summary.chainId : chainId\n }\n allowanceSummary = list.map((a) => ({\n token: a.tokenSymbol ?? 'UNKNOWN',\n amount: a.onchain?.amount ?? a.configuredAmount ?? '0',\n resetMinutes:\n typeof a.onchain?.resetTimeMin === 'number'\n ? a.onchain.resetTimeMin\n : typeof a.resetPeriodMin === 'number'\n ? a.resetPeriodMin\n : null,\n }))\n } catch {\n // Identity falls back to what the credential file gave us.\n }\n\n return {\n apiKeyPrefix: derivePrefix(seed.apiKey),\n apiUrl: seed.apiUrl,\n agentId: seed.agentId,\n safeAddress,\n delegateAddress,\n chainId,\n toolNames,\n allowanceSummary,\n }\n}\n\nfunction isAllowanceSummary(value: unknown): value is HavenAllowanceSummary {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'allowances' in value &&\n Array.isArray((value as { allowances: unknown }).allowances)\n )\n}\n\n/**\n * Use the leading characters of the api key (which already begins with the\n * non-secret `sk_agent_` prefix) as a stable, low-information identifier.\n * Twelve characters is enough to disambiguate credentials in front of a\n * human but not enough to reveal the secret.\n */\nfunction derivePrefix(apiKey: string): string {\n return apiKey.slice(0, 12)\n}\n\n/** Convenience: the canonical tool list registered by the server. */\nexport function registeredToolNames(): HavenMcpToolName[] {\n return Object.keys(toolSchemas) as HavenMcpToolName[]\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { HavenClient } from '@haven_ai/sdk'\nimport { loadCredentials, type HavenCredentialFile } from './credentials.js'\nimport {\n createToolHandlers,\n toolDescriptions,\n toolSchemas,\n type HavenMcpToolName,\n type ToolPayload,\n} from './tools.js'\nimport {\n consentInputFromClient,\n ensureConsent,\n registeredToolNames,\n type ConsentDecision,\n} from './consent.js'\n\nexport interface HavenMcpServerOptions {\n credentialsPath?: string\n credentials?: HavenCredentialFile\n /**\n * When true, write the consent sidecar file (`<credentials>.ack.json`)\n * with the current consent hash and proceed. Surfaced via the `--ack`\n * CLI flag.\n */\n writeAck?: boolean\n /**\n * When true, skip the consent gate entirely. Reserved for tests and\n * controlled embedding — production CLIs should not set this.\n */\n skipConsent?: boolean\n}\n\nexport interface ResolvedHavenClient {\n client: HavenClient\n credentials: HavenCredentialFile\n}\n\nexport async function createHavenClient(options: HavenMcpServerOptions = {}): Promise<HavenClient> {\n const { client } = await resolveHavenClient(options)\n return client\n}\n\nexport async function resolveHavenClient(options: HavenMcpServerOptions = {}): Promise<ResolvedHavenClient> {\n const credentials = options.credentials ?? await loadCredentials(options.credentialsPath)\n const client = new HavenClient({\n apiKey: credentials.apiKey,\n delegateKey: credentials.delegateKey,\n baseUrl: credentials.apiUrl,\n })\n return { client, credentials }\n}\n\nexport async function createHavenMcpServer(options: HavenMcpServerOptions = {}): Promise<McpServer> {\n const haven = await createHavenClient(options)\n return buildMcpServer(haven)\n}\n\n/**\n * Build an MCP server bound to the supplied Haven client.\n *\n * Each tool dispatch is wrapped in `haven.withRequestContext` so every\n * Haven API request the dispatch issues carries `X-Haven-MCP-Tool: <name>`\n * — and *only* that dispatch's requests see the header. The SDK uses an\n * `AsyncLocalStorage` for the context, so two tool calls running\n * concurrently cannot leak headers into each other and the backend\n * `agent_tool_invocations` rows are always attributed to the right tool.\n */\nexport function buildMcpServer(haven: HavenClient): McpServer {\n const server = new McpServer({\n name: '@haven_ai/mcp',\n version: '0.1.0-alpha',\n })\n\n const handlers = createToolHandlers(haven)\n const registerTool = (server as any).tool.bind(server)\n for (const name of Object.keys(toolSchemas) as HavenMcpToolName[]) {\n registerTool(\n name,\n toolDescriptions[name],\n toolSchemas[name],\n async (args: unknown) =>\n haven.withRequestContext({ 'X-Haven-MCP-Tool': name }, async () =>\n toMcpResult(await handlers[name](args)),\n ),\n )\n }\n\n return server\n}\n\nexport async function runStdioServer(options: HavenMcpServerOptions = {}): Promise<void> {\n const { client: haven, credentials } = await resolveHavenClient(options)\n\n if (!options.skipConsent) {\n const decision = await runConsentGate(haven, credentials, options)\n if (!decision.ok) {\n // The consent block has already been printed by `ensureConsent`.\n const err: NodeJS.ErrnoException = new Error(\n decision.reason === 'env_var_mismatch'\n ? 'Haven MCP consent acknowledgement does not match the current configuration.'\n : 'Haven MCP server requires a one-time consent acknowledgement before starting.',\n )\n err.code = 'HAVEN_MCP_NO_CONSENT'\n throw err\n }\n }\n\n const server = buildMcpServer(haven)\n await server.connect(new StdioServerTransport())\n}\n\nexport async function runConsentGate(\n haven: HavenClient,\n credentials: HavenCredentialFile,\n options: HavenMcpServerOptions,\n): Promise<ConsentDecision> {\n const toolNames = registeredToolNames()\n const input = await consentInputFromClient(\n haven,\n {\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n agentId: credentials.agentId,\n safeAddress: credentials.safeAddress,\n },\n toolNames,\n )\n // Prefer the path actually used to load credentials (covers\n // HAVEN_CREDENTIALS as well as --credentials). If neither file path is\n // available the operator must use HAVEN_MCP_ACK; --ack has nowhere to\n // write a sidecar in that case.\n const credentialsPath = options.credentialsPath ?? credentials.sourcePath\n return ensureConsent(input, {\n credentialsPath,\n writeAck: options.writeAck,\n })\n}\n\nfunction toMcpResult(payload: ToolPayload) {\n return {\n isError: !payload.success,\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(payload, null, 2),\n },\n ],\n }\n}\n","#!/usr/bin/env node\n\nimport { runStdioServer, type HavenMcpServerOptions } from './server.js'\n\nfunction parseArgs(argv: string[]): HavenMcpServerOptions {\n const options: HavenMcpServerOptions = {}\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i]\n if (arg === '--credentials' || arg === '--credentials-path') {\n options.credentialsPath = argv[i + 1]\n i += 1\n } else if (arg === '--transport') {\n const transport = argv[i + 1]\n i += 1\n if (transport !== 'stdio') {\n throw new Error('Only local stdio transport is supported. Haven does not provide a remote MCP signer mode.')\n }\n } else if (arg === '--ack') {\n // Write the consent-gate acknowledgement next to the credential file\n // and proceed. Used on first-launch to opt the operator in once.\n options.writeAck = true\n } else if (arg === '--help' || arg === '-h') {\n process.stdout.write([\n 'Haven MCP server',\n '',\n 'Usage:',\n ' npx @haven_ai/mcp --credentials /path/to/agent.json',\n '',\n 'Options:',\n ' --credentials <path> Haven credential JSON file. Also supported: HAVEN_CREDENTIALS.',\n ' --transport stdio Local stdio transport. This is the only supported mode.',\n ' --ack Acknowledge the first-launch consent block and write',\n ' a sidecar acknowledgement file next to the credential.',\n '',\n 'Consent:',\n ' On first launch the server prints the tool list and the on-chain',\n ' allowance summary, then refuses to start unless you have acknowledged.',\n ' Acknowledge with EITHER --ack OR HAVEN_MCP_ACK=<hash> in your environment.',\n '',\n ].join('\\n'))\n process.exit(0)\n }\n }\n return options\n}\n\nasync function main(): Promise<void> {\n await runStdioServer(parseArgs(process.argv.slice(2)))\n}\n\nmain().catch((err) => {\n process.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`)\n process.exit(1)\n})\n"]}
1
+ {"version":3,"sources":["../src/credentials.ts","../src/tools.ts","../src/consent.ts","../src/server.ts","../src/cli.ts"],"names":["readFile","stat","z","composeDescription","sharedDescriptions","HavenApiError","HavenPaymentStateError","HavenSigningError","AgentPaymentNextAction","HavenError","createHash","resolve","path","mkdir","dirname","writeFile","HavenClient","McpServer","StdioServerTransport"],"mappings":";;;;;;;;;;;AA6EA,eAAsB,eAAA,CACpB,MAAA,GAAqD,OAAA,CAAQ,GAAA,CAAI,iBAAA,EACnC;AAC9B,EAAA,IAAI,OAAO,WAAW,QAAA,EAAU;AAC9B,IAAA,OAAO,wBAAwB,MAAM,CAAA;AAAA,EACvC;AACA,EAAA,IAAI,QAAQ,eAAA,EAAiB;AAC3B,IAAA,OAAO,uBAAA,CAAwB,OAAO,eAAe,CAAA;AAAA,EACvD;AACA,EA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File, stat } from 'node:fs/promises'\n\nexport interface HavenCredentialFile {\n apiKey: string\n delegateKey: string\n agentId?: string\n safeAddress?: string\n delegateAddress?: string\n chainId?: number\n network?: string\n apiUrl?: string\n allowanceSummary?: readonly HavenCredentialAllowance[]\n /**\n * Absolute path the credentials were loaded from, if any. Set when the\n * caller pointed at a JSON file via `--credentials` or `HAVEN_CREDENTIALS`;\n * left undefined when credentials came purely from environment variables.\n * The MCP server uses this to locate the consent sidecar\n * (`<sourcePath>.ack.json`) so `--ack` works regardless of how the\n * credential path was supplied.\n */\n sourcePath?: string\n identityPath?: string\n signerPath?: string\n}\n\nexport interface HavenCredentialAllowance {\n token: string\n amount: string\n resetMinutes: number | null\n}\n\nexport interface HavenCredentialSource {\n credentialsPath?: string\n identityPath?: string\n signerPath?: string\n}\n\ninterface RawCredentialFile {\n api_key?: unknown\n apiKey?: unknown\n delegate_key?: unknown\n delegateKey?: unknown\n delegate_address?: unknown\n delegateAddress?: unknown\n agent_id?: unknown\n agentId?: unknown\n safe_address?: unknown\n safeAddress?: unknown\n chain_id?: unknown\n chainId?: unknown\n network?: unknown\n api_url?: unknown\n apiUrl?: unknown\n hosted_mcp_url?: unknown\n hostedMcpUrl?: unknown\n allowance_summary?: unknown\n allowanceSummary?: unknown\n agent_budget?: unknown\n agentBudget?: unknown\n}\n\n/**\n * Load Haven agent credentials for the MCP server.\n *\n * Resolution order — earlier sources win, later sources are fallbacks:\n *\n * 1. Explicit `path` argument (typically from `--credentials <path>`).\n * 2. `HAVEN_CREDENTIALS` env var pointing at a credential JSON file.\n * 3. Inline env vars: `HAVEN_API_KEY` + `HAVEN_DELEGATE_KEY` (+ optional\n * `HAVEN_AGENT_ID`, `HAVEN_SAFE_ADDRESS`, `HAVEN_API_URL`).\n *\n * The inline-env path exists so that runtime config snippets emitted by the\n * Haven dashboard (Claude Desktop / Cursor / generic MCP configs) can be a\n * single self-contained block — paste the snippet, restart the runtime, done.\n * The values still live only in the agent operator's process environment;\n * Haven's backend never sees the delegate key either way.\n */\nexport async function loadCredentials(\n source: string | HavenCredentialSource | undefined = process.env.HAVEN_CREDENTIALS,\n): Promise<HavenCredentialFile> {\n if (typeof source === 'string') {\n return loadCredentialsFromFile(source)\n }\n if (source?.credentialsPath) {\n return loadCredentialsFromFile(source.credentialsPath)\n }\n if (source?.identityPath || source?.signerPath) {\n if (!source.identityPath || !source.signerPath) {\n throw new Error('Haven split credentials require both --identity and --signer paths.')\n }\n return loadCredentialsFromSplitFiles(source.identityPath, source.signerPath)\n }\n\n const envCreds = loadCredentialsFromEnv()\n if (envCreds) return envCreds\n\n throw new Error(\n 'No Haven credentials found. Set HAVEN_CREDENTIALS to a Haven agent credential JSON file, ' +\n 'pass --credentials <path>, or set HAVEN_API_KEY and HAVEN_DELEGATE_KEY environment variables.',\n )\n}\n\nasync function loadCredentialsFromFile(path: string): Promise<HavenCredentialFile> {\n let rawText: string\n try {\n rawText = await readFile(path, 'utf8')\n } catch (err) {\n throw new Error(`Could not read Haven credentials at ${path}: ${err instanceof Error ? err.message : String(err)}`)\n }\n\n await warnIfCredentialFilePermissive(path)\n\n let raw: RawCredentialFile\n try {\n raw = JSON.parse(rawText) as RawCredentialFile\n } catch {\n throw new Error('Haven credentials must be JSON with api_key and delegate_key fields.')\n }\n\n const apiKey = stringField(raw.api_key ?? raw.apiKey)\n const delegateKey = stringField(raw.delegate_key ?? raw.delegateKey)\n\n if (!apiKey) {\n throw new Error('Haven credentials are missing api_key.')\n }\n if (!delegateKey) {\n throw new Error('Haven MCP requires delegate_key so payments can be signed locally.')\n }\n\n return {\n apiKey,\n delegateKey,\n agentId: stringField(raw.agent_id ?? raw.agentId),\n safeAddress: stringField(raw.safe_address ?? raw.safeAddress),\n delegateAddress: stringField(raw.delegate_address ?? raw.delegateAddress),\n chainId: numberField(raw.chain_id ?? raw.chainId),\n network: stringField(raw.network),\n apiUrl: stringField(raw.api_url ?? raw.apiUrl),\n allowanceSummary: allowanceSummaryField(raw.allowance_summary ?? raw.allowanceSummary ?? raw.agent_budget ?? raw.agentBudget),\n sourcePath: path,\n }\n}\n\nasync function loadCredentialsFromSplitFiles(identityPath: string, signerPath: string): Promise<HavenCredentialFile> {\n const identity = await readJsonFile(identityPath, 'Haven identity credentials')\n const signer = await readJsonFile(signerPath, 'Haven signer credentials')\n\n await warnIfCredentialFilePermissive(identityPath)\n await warnIfCredentialFilePermissive(signerPath)\n\n const apiKey = stringField(identity.api_key ?? identity.apiKey)\n const delegateKey = stringField(signer.delegate_key ?? signer.delegateKey)\n\n if (!apiKey) {\n throw new Error('Haven identity credentials are missing api_key.')\n }\n if (!delegateKey) {\n throw new Error('Haven signer credentials are missing delegate_key.')\n }\n\n return {\n apiKey,\n delegateKey,\n agentId: stringField(identity.agent_id ?? identity.agentId ?? signer.agent_id ?? signer.agentId),\n safeAddress: stringField(identity.safe_address ?? identity.safeAddress ?? signer.safe_address ?? signer.safeAddress),\n delegateAddress: stringField(signer.delegate_address ?? signer.delegateAddress ?? identity.delegate_address ?? identity.delegateAddress),\n chainId: numberField(identity.chain_id ?? identity.chainId ?? signer.chain_id ?? signer.chainId),\n network: stringField(identity.network ?? signer.network),\n apiUrl: stringField(identity.api_url ?? identity.apiUrl),\n allowanceSummary: allowanceSummaryField(\n identity.allowance_summary ??\n identity.allowanceSummary ??\n identity.agent_budget ??\n identity.agentBudget,\n ),\n sourcePath: identityPath,\n identityPath,\n signerPath,\n }\n}\n\nasync function readJsonFile(path: string, label: string): Promise<RawCredentialFile> {\n let rawText: string\n try {\n rawText = await readFile(path, 'utf8')\n } catch (err) {\n throw new Error(`Could not read ${label} at ${path}: ${err instanceof Error ? err.message : String(err)}`)\n }\n\n try {\n return JSON.parse(rawText) as RawCredentialFile\n } catch {\n throw new Error(`${label} must be JSON.`)\n }\n}\n\nfunction loadCredentialsFromEnv(): HavenCredentialFile | null {\n const apiKey = stringField(process.env.HAVEN_API_KEY)\n const delegateKey = stringField(process.env.HAVEN_DELEGATE_KEY)\n\n if (!apiKey && !delegateKey) return null\n\n if (!apiKey) {\n throw new Error('HAVEN_DELEGATE_KEY is set but HAVEN_API_KEY is missing.')\n }\n if (!delegateKey) {\n throw new Error('HAVEN_API_KEY is set but HAVEN_DELEGATE_KEY is missing. Haven MCP requires a delegate key so payments can be signed locally.')\n }\n\n return {\n apiKey,\n delegateKey,\n agentId: stringField(process.env.HAVEN_AGENT_ID),\n safeAddress: stringField(process.env.HAVEN_SAFE_ADDRESS),\n chainId: numberField(process.env.HAVEN_CHAIN_ID),\n network: stringField(process.env.HAVEN_NETWORK),\n apiUrl: stringField(process.env.HAVEN_API_URL),\n }\n}\n\nfunction stringField(value: unknown): string | undefined {\n return typeof value === 'string' && value.trim() ? value.trim() : undefined\n}\n\nfunction numberField(value: unknown): number | undefined {\n if (typeof value === 'number' && Number.isFinite(value)) return value\n if (typeof value === 'string' && value.trim() && /^\\d+$/.test(value.trim())) return Number(value.trim())\n return undefined\n}\n\nfunction allowanceSummaryField(value: unknown): HavenCredentialAllowance[] | undefined {\n if (!Array.isArray(value)) return undefined\n const allowances = value.flatMap((item) => {\n if (!item || typeof item !== 'object') return []\n const raw = item as Record<string, unknown>\n const token = stringField(raw.token ?? raw.token_symbol ?? raw.tokenSymbol)\n const amount = stringField(raw.amount ?? raw.allowance_amount ?? raw.allowanceAmount)\n const reset = raw.resetMinutes ?? raw.reset_minutes ?? raw.reset_period_min ?? raw.resetPeriodMin\n if (!token || !amount) return []\n return [{\n token,\n amount,\n resetMinutes: reset === null ? null : numberField(reset) ?? null,\n }]\n })\n return allowances.length > 0 ? allowances : undefined\n}\n\n/**\n * Warn (but do not block) when the credential file is readable by users\n * other than the owner. The check is best-effort: it only runs on POSIX\n * filesystems where the stat mode bits map cleanly. Windows ACLs require\n * `icacls`-style introspection that doesn't fit a single stat call, so we\n * skip the check there and the dashboard handoff text guides the user\n * separately.\n *\n * Exported for testing.\n */\nexport async function warnIfCredentialFilePermissive(\n path: string,\n log: (message: string) => void = (message) => process.stderr.write(`${message}\\n`),\n platform: NodeJS.Platform = process.platform,\n): Promise<void> {\n if (platform === 'win32') return\n\n let mode: number\n try {\n const stats = await stat(path)\n mode = stats.mode\n } catch {\n // The credential read already failed cleanly above if the file is\n // unreadable. A stat failure here is not worth blocking on.\n return\n }\n\n const groupOrOther = mode & 0o077\n if (groupOrOther !== 0) {\n const octal = (mode & 0o777).toString(8).padStart(4, '0')\n log(\n `haven-mcp: warning: credential file at ${path} is readable beyond the owner ` +\n `(mode ${octal}). Run: chmod 600 ${path}`,\n )\n }\n}\n","import {\n AgentPaymentNextAction,\n HavenApiError,\n HavenClient,\n HavenError,\n HavenPaymentStateError,\n HavenSigningError,\n composeDescription,\n toolDescriptions as sharedDescriptions,\n type MachinePaymentChallenge,\n type MppQuote,\n type MppResumeState,\n type X402Quote,\n type X402ResumeState,\n} from '@haven_ai/sdk'\nimport { z } from 'zod/v3'\n\nconst headersSchema = z.record(z.string(), z.string()).optional()\n\nexport type HavenMcpToolName =\n | 'haven_quote_x402'\n | 'haven_pay_x402_quote'\n | 'haven_resume_x402_payment'\n | 'haven_quote_mpp'\n | 'haven_pay_mpp_challenge'\n | 'haven_resume_mpp_payment'\n | 'haven_get_payment_status'\n | 'haven_get_resume_state'\n | 'haven_get_agent'\n | 'haven_get_allowances'\n | 'haven_list_receipts'\n\nexport const toolSchemas: Record<HavenMcpToolName, z.ZodRawShape> = {\n haven_quote_x402: {\n url: z.string().url(),\n method: z.string().optional(),\n headers: headersSchema,\n body: z.string().optional(),\n idempotencyKey: z.string().optional(),\n },\n haven_pay_x402_quote: {\n quote: z.unknown(),\n idempotencyKey: z.string().optional(),\n },\n haven_resume_x402_payment: {\n payment_id: z.string().optional(),\n resume_state: z.unknown().optional(),\n },\n haven_quote_mpp: {\n url: z.string().url().optional(),\n challenge: z.unknown().optional(),\n method: z.string().optional(),\n headers: headersSchema,\n body: z.string().optional(),\n idempotencyKey: z.string().optional(),\n },\n haven_pay_mpp_challenge: {\n quote: z.unknown(),\n idempotencyKey: z.string().optional(),\n },\n haven_resume_mpp_payment: {\n payment_id: z.string().optional(),\n resume_state: z.unknown().optional(),\n },\n haven_get_payment_status: {\n payment_id: z.string(),\n },\n haven_get_resume_state: {\n payment_id: z.string(),\n },\n haven_get_agent: {},\n haven_get_allowances: {},\n haven_list_receipts: {\n limit: z.number().int().min(1).max(100).optional(),\n },\n}\n\n/**\n * MCP tool descriptions, composed from the shared semantic source in\n * `@haven_ai/sdk`'s `tool-descriptions.ts`. Keeping both the SDK tool-calling\n * surface and the MCP surface pointed at the same prose source means new\n * guidance lands in both places at once and a parity test can catch drift.\n */\nexport const toolDescriptions: Record<HavenMcpToolName, string> = {\n haven_quote_x402: composeDescription(sharedDescriptions.quoteX402),\n haven_pay_x402_quote: composeDescription(sharedDescriptions.payX402),\n haven_resume_x402_payment: composeDescription(sharedDescriptions.resumeX402),\n haven_quote_mpp: composeDescription(sharedDescriptions.quoteMpp),\n haven_pay_mpp_challenge: composeDescription(sharedDescriptions.payMpp),\n haven_resume_mpp_payment: composeDescription(sharedDescriptions.resumeMpp),\n haven_get_payment_status: composeDescription(sharedDescriptions.getPaymentStatus),\n haven_get_resume_state: composeDescription(sharedDescriptions.getResumeState),\n haven_get_agent: composeDescription(sharedDescriptions.getAgent),\n haven_get_allowances: composeDescription(sharedDescriptions.getAllowances),\n haven_list_receipts: composeDescription(sharedDescriptions.listReceipts),\n}\n\nexport interface ToolSuccess<T> {\n success: true\n data: T\n}\n\nexport interface ToolFailure {\n success: false\n code: string\n message: string\n statusCode?: number\n paymentId?: string\n status?: string\n phase?: string\n nextAction?: string\n resume_state?: unknown\n body?: unknown\n}\n\nexport type ToolPayload<T = unknown> = ToolSuccess<T> | ToolFailure\n\nexport function createToolHandlers(haven: HavenClient): Record<HavenMcpToolName, (input: unknown) => Promise<ToolPayload>> {\n return {\n haven_quote_x402: async (input) => {\n const args = objectInput('haven_quote_x402', input)\n return runTool(async () => haven.quoteX402(args.url, requestInit(args), { idempotencyKey: args.idempotencyKey }))\n },\n\n haven_pay_x402_quote: async (input) => {\n const args = objectInput('haven_pay_x402_quote', input)\n return runTool(async () => {\n const response = await haven.payX402Quote(args.quote as X402Quote, { idempotencyKey: args.idempotencyKey })\n return responsePayload(response)\n })\n },\n\n haven_resume_x402_payment: async (input) => {\n const args = objectInput('haven_resume_x402_payment', input)\n return runTool(async () => {\n const state = await resumeState(args, 'x402')\n const response = await haven.resumeX402Payment(state)\n return responsePayload(response)\n })\n },\n\n haven_quote_mpp: async (input) => {\n const args = objectInput('haven_quote_mpp', input)\n return runTool(async () => {\n if (args.challenge) {\n return haven.quoteMpp(args.challenge as MachinePaymentChallenge, requestInit(args), {\n idempotencyKey: args.idempotencyKey,\n })\n }\n if (!args.url) {\n throw new HavenApiError('haven_quote_mpp requires either url or challenge.', 400)\n }\n return haven.quoteMpp(args.url, requestInit(args), { idempotencyKey: args.idempotencyKey })\n })\n },\n\n haven_pay_mpp_challenge: async (input) => {\n const args = objectInput('haven_pay_mpp_challenge', input)\n return runTool(async () => {\n const response = await haven.payMppChallenge(args.quote as MppQuote, { idempotencyKey: args.idempotencyKey })\n return responsePayload(response)\n })\n },\n\n haven_resume_mpp_payment: async (input) => {\n const args = objectInput('haven_resume_mpp_payment', input)\n return runTool(async () => {\n const state = await resumeState(args, 'mpp')\n const response = await haven.resumeMppPayment(state)\n return responsePayload(response)\n })\n },\n\n haven_get_payment_status: async (input) => {\n const args = objectInput('haven_get_payment_status', input)\n return runTool(async () => haven.getPaymentStatus(args.payment_id))\n },\n\n haven_get_resume_state: async (input) => {\n const args = objectInput('haven_get_resume_state', input)\n return runTool(async () => haven.getResumeState(args.payment_id))\n },\n\n haven_get_agent: async () => runTool(async () => haven.getAgent()),\n haven_get_allowances: async () => runTool(async () => haven.getAllowances()),\n haven_list_receipts: async (input) => {\n const args = objectInput('haven_list_receipts', input)\n return runTool(async () => haven.listReceipts({ limit: args.limit }))\n },\n }\n\n async function resumeState(\n args: { payment_id?: string; resume_state?: unknown },\n rail: 'x402' | 'mpp',\n ): Promise<X402ResumeState | MppResumeState> {\n const state =\n args.resume_state ??\n (args.payment_id ? await haven.getResumeState(args.payment_id) : undefined)\n\n if (!state || typeof state !== 'object') {\n throw new HavenApiError(`haven_resume_${rail}_payment requires resume_state or payment_id.`, 400)\n }\n\n if ((state as { rail?: unknown }).rail !== rail) {\n throw new HavenApiError(`Resume state is not for the ${rail} rail.`, 409, state)\n }\n\n return state as X402ResumeState | MppResumeState\n }\n}\n\nfunction objectInput<TName extends HavenMcpToolName>(\n name: TName,\n input: unknown,\n): Record<string, any> {\n return z.object(toolSchemas[name]).parse(input ?? {})\n}\n\nfunction requestInit(input: { method?: string; headers?: Record<string, string>; body?: string }): RequestInit | undefined {\n if (!input.method && !input.headers && input.body === undefined) return undefined\n return {\n method: input.method,\n headers: input.headers,\n body: input.body,\n }\n}\n\nasync function runTool<T>(fn: () => Promise<T>): Promise<ToolPayload<T>> {\n try {\n return { success: true, data: await fn() }\n } catch (err) {\n return normalizeError(err)\n }\n}\n\nasync function responsePayload(response: Response): Promise<Record<string, unknown>> {\n const text = await response.text()\n return {\n status: response.status,\n statusText: response.statusText,\n headers: Object.fromEntries(response.headers.entries()),\n body: parseMaybeJson(text),\n }\n}\n\nfunction parseMaybeJson(text: string): unknown {\n if (!text) return null\n try {\n return JSON.parse(text)\n } catch {\n return text\n }\n}\n\nfunction normalizeError(err: unknown): ToolFailure {\n if (err instanceof HavenPaymentStateError) {\n return {\n success: false,\n code: err.code,\n message: err.message,\n statusCode: err.statusCode,\n paymentId: err.paymentId,\n status: err.status,\n phase: err.phase,\n nextAction: err.nextAction,\n resume_state: err.resumeState,\n body: err.body,\n }\n }\n\n if (err instanceof HavenSigningError) {\n return {\n success: false,\n code: err.code,\n message: err.message,\n }\n }\n\n if (err instanceof HavenApiError) {\n const body = err.body as Record<string, unknown> | undefined\n return {\n success: false,\n code: err.code,\n message: err.message,\n statusCode: err.statusCode,\n paymentId: err.paymentId,\n phase: stringOrUndefined(body?.phase),\n nextAction:\n stringOrUndefined(body?.nextAction) ??\n stringOrUndefined(body?.next_action) ??\n AgentPaymentNextAction.StopAndTellUser,\n body: err.body,\n }\n }\n\n if (err instanceof HavenError) {\n return {\n success: false,\n code: err.code,\n message: err.message,\n statusCode: err.statusCode,\n paymentId: err.paymentId,\n }\n }\n\n return {\n success: false,\n code: 'UNKNOWN_ERROR',\n message: err instanceof Error ? err.message : String(err),\n nextAction: AgentPaymentNextAction.StopAndTellUser,\n }\n}\n\nfunction stringOrUndefined(value: unknown): string | undefined {\n return typeof value === 'string' ? value : undefined\n}\n","import { createHash } from 'node:crypto'\nimport { mkdir, readFile, writeFile } from 'node:fs/promises'\nimport { dirname, resolve } from 'node:path'\nimport type { HavenAllowance, HavenAllowanceSummary, HavenClient } from '@haven_ai/sdk'\nimport { toolDescriptions, toolSchemas, type HavenMcpToolName } from './tools.js'\n\n/**\n * First-launch consent gate for the Haven MCP server.\n *\n * Why this exists (option A of issue #163): an agent runtime that loads a\n * Haven credential file is about to expose Haven payment tools to a model.\n * Before the server starts taking JSON-RPC calls we want the operator to\n * acknowledge — exactly once per credential + tool set — what those tools\n * can do and what the on-chain allowance cap actually is. The on-chain\n * AllowanceModule remains the policy primitive; this gate is informational\n * rather than enforcement.\n *\n * Resolution:\n * - `HAVEN_MCP_ACK=<hash>` env var matching the current consent hash → pass.\n * - `HAVEN_MCP_ACK=skip` → pass (intended for CI / scripted setups).\n * - sidecar file `<credentials>.ack.json` containing `{ ack: <hash> }` → pass.\n * - `--ack` CLI flag → write the sidecar file, print the consent block, pass.\n * - otherwise → print the consent block to stderr and exit non-zero.\n *\n * The hash binds the api-key prefix to the registered tool set and the\n * agent's current allowance summary, so a configuration change re-triggers\n * the prompt.\n */\n\nexport interface ConsentInput {\n apiKeyPrefix: string\n /** Haven API base URL the credential will hit. */\n apiUrl?: string\n /** Agent identity from the credential file, when present. */\n agentId?: string\n /** Haven wallet (Safe) the agent spends from. */\n safeAddress?: string\n /** Agent's delegate EOA — the local signer. */\n delegateAddress?: string\n /** Chain the agent operates on. */\n chainId?: number\n toolNames: readonly HavenMcpToolName[]\n allowanceSummary: readonly { token: string; amount: string; resetMinutes: number | null }[]\n}\n\nexport interface ConsentDecision {\n /** True if the gate is satisfied and the server may start. */\n ok: boolean\n /** Hash representing the current consent surface. */\n hash: string\n /** Reason the gate accepted (or rejected) the run. */\n reason:\n | 'env_var_match'\n | 'env_var_skip'\n | 'ack_file_match'\n | 'wrote_ack_file'\n | 'env_var_mismatch'\n | 'no_acknowledgement'\n}\n\nexport interface ConsentOptions {\n /** Path to the credential file; used to locate the sidecar `<path>.ack.json`. */\n credentialsPath?: string\n /** When true, write the sidecar file with the current hash and accept. */\n writeAck?: boolean\n /** Override the environment lookup (testing). */\n env?: Record<string, string | undefined>\n /** Override the writable stream the consent block is printed to (testing). */\n out?: { write: (chunk: string) => unknown }\n}\n\nexport function computeConsentHash(input: ConsentInput): string {\n const allowanceCanonical = [...input.allowanceSummary]\n .map((a) => `${a.token}:${a.amount}:${a.resetMinutes ?? 'none'}`)\n .sort()\n .join('|')\n const toolCanonical = [...input.toolNames].sort().join(',')\n // Identity fields are included in the hash so swapping the credential\n // to a different Haven wallet / delegate / chain — even one with an\n // identical allowance set — invalidates the prior sidecar and re-prompts\n // the operator. Addresses are normalised to lowercase so casing changes\n // in the credential file don't gratuitously re-prompt.\n const identity = [\n input.apiKeyPrefix,\n input.apiUrl ?? '',\n input.agentId ?? '',\n (input.safeAddress ?? '').toLowerCase(),\n (input.delegateAddress ?? '').toLowerCase(),\n input.chainId ?? '',\n ].join('|')\n return createHash('sha256')\n .update(`${identity}\\n${toolCanonical}\\n${allowanceCanonical}`)\n .digest('hex')\n .slice(0, 16)\n}\n\nexport function renderConsentBlock(input: ConsentInput, hash: string): string {\n const lines: string[] = [\n '',\n '────────────────────────────────────────────────────────────',\n 'Haven MCP server — first-launch consent',\n '────────────────────────────────────────────────────────────',\n '',\n `Credential: ${input.apiKeyPrefix}…`,\n ]\n if (input.apiUrl) lines.push(`Haven API: ${input.apiUrl}`)\n if (input.agentId) lines.push(`Agent ID: ${input.agentId}`)\n if (input.safeAddress) lines.push(`Haven wallet (Safe): ${input.safeAddress}`)\n if (input.delegateAddress) lines.push(`Delegate (local signer): ${input.delegateAddress}`)\n if (typeof input.chainId === 'number') lines.push(`Chain ID: ${input.chainId}`)\n lines.push('')\n lines.push('Confirm these match the Haven wallet and chain you intend the')\n lines.push('agent runtime to use. The delegate above is the only key that')\n lines.push('signs payments — it lives in this process, not on Haven\\'s backend.')\n lines.push('')\n lines.push('Tools this server will expose to your agent runtime:')\n for (const name of input.toolNames) {\n lines.push(` • ${name}`)\n lines.push(` ${toolDescriptions[name]}`)\n }\n lines.push('')\n if (input.allowanceSummary.length === 0) {\n lines.push('On-chain allowance: none configured.')\n lines.push(' Any payment will queue for manual approval. The on-chain')\n lines.push(' Safe AllowanceModule is the real spend gate.')\n } else {\n lines.push('On-chain allowance (the real spend gate, Safe AllowanceModule):')\n for (const a of input.allowanceSummary) {\n const reset = a.resetMinutes ? ` per ${a.resetMinutes} min` : ' (no reset)'\n lines.push(` • up to ${a.amount} ${a.token}${reset}`)\n }\n }\n lines.push('')\n lines.push('Anything above the on-chain allowance pauses for owner approval')\n lines.push('in the Haven dashboard. Revoking the agent on-chain disables')\n lines.push('every MCP tool that would spend.')\n lines.push('')\n lines.push(`Consent hash: ${hash}`)\n lines.push('')\n lines.push('To acknowledge, EITHER:')\n lines.push(` • set HAVEN_MCP_ACK=${hash} in this process\\'s environment, OR`)\n lines.push(' • re-run with --ack to write the acknowledgement next to your')\n lines.push(' credential file (sidecar <credentials>.ack.json).')\n lines.push('')\n lines.push('────────────────────────────────────────────────────────────')\n lines.push('')\n return lines.join('\\n')\n}\n\n/** Resolve the consent gate. Does not exit the process; the caller decides. */\nexport async function ensureConsent(\n input: ConsentInput,\n options: ConsentOptions = {},\n): Promise<ConsentDecision> {\n const env = options.env ?? process.env\n const out = options.out ?? process.stderr\n const hash = computeConsentHash(input)\n\n // 1) Explicit skip — for CI and scripted environments.\n if (env.HAVEN_MCP_ACK === 'skip') {\n return { ok: true, hash, reason: 'env_var_skip' }\n }\n\n // 2) Env var hash match.\n if (typeof env.HAVEN_MCP_ACK === 'string' && env.HAVEN_MCP_ACK.length > 0) {\n if (env.HAVEN_MCP_ACK === hash) {\n return { ok: true, hash, reason: 'env_var_match' }\n }\n out.write(renderConsentBlock(input, hash))\n out.write(\n `HAVEN_MCP_ACK was set but did not match the current consent hash.\\n` +\n `Expected: ${hash}\\n` +\n `Got: ${env.HAVEN_MCP_ACK}\\n` +\n `Re-acknowledge with the new hash above, or run with --ack.\\n\\n`,\n )\n return { ok: false, hash, reason: 'env_var_mismatch' }\n }\n\n // 3) Sidecar ack file (only meaningful when we loaded from a file).\n const ackPath = sidecarPath(options.credentialsPath)\n if (ackPath) {\n const stored = await readAckFile(ackPath)\n if (stored?.ack === hash) {\n return { ok: true, hash, reason: 'ack_file_match' }\n }\n }\n\n // 4) --ack: write the sidecar and accept.\n if (options.writeAck && ackPath) {\n out.write(renderConsentBlock(input, hash))\n await writeAckFile(ackPath, hash)\n out.write(`Wrote acknowledgement to ${ackPath}\\n\\n`)\n return { ok: true, hash, reason: 'wrote_ack_file' }\n }\n\n // 5) Otherwise: print and refuse.\n out.write(renderConsentBlock(input, hash))\n return { ok: false, hash, reason: 'no_acknowledgement' }\n}\n\nfunction sidecarPath(credentialsPath?: string): string | null {\n if (!credentialsPath) return null\n return resolve(`${credentialsPath}.ack.json`)\n}\n\nasync function readAckFile(path: string): Promise<{ ack?: string } | null> {\n try {\n const raw = await readFile(path, 'utf8')\n const parsed = JSON.parse(raw) as { ack?: unknown }\n return { ack: typeof parsed.ack === 'string' ? parsed.ack : undefined }\n } catch {\n return null\n }\n}\n\nasync function writeAckFile(path: string, hash: string): Promise<void> {\n await mkdir(dirname(path), { recursive: true })\n await writeFile(\n path,\n JSON.stringify({ ack: hash, at: new Date().toISOString() }, null, 2),\n 'utf8',\n )\n}\n\nexport interface CredentialIdentitySeed {\n apiKey: string\n apiUrl?: string\n agentId?: string\n /** Safe address from the credential file, used as a fallback. */\n safeAddress?: string\n /** Delegate address from the credential file, used before live allowance metadata is available. */\n delegateAddress?: string\n /** Chain from the credential file, used as a fallback. */\n chainId?: number\n /** Intended agent budget from the setup flow, used before on-chain approval is visible. */\n allowanceSummary?: readonly { token: string; amount: string; resetMinutes: number | null }[]\n}\n\n/**\n * Build the consent input from credential identity plus a live allowance\n * lookup. The on-chain (or configured) allowance is what the operator\n * actually cares about — that's the real spend ceiling — but we also bind\n * the hash to the Haven wallet / delegate / chain so a credential swap\n * cannot quietly reuse a prior sidecar acknowledgement.\n *\n * If `getAllowances()` fails (e.g. backend unreachable on first launch) we\n * fall through to whatever identity fields the credential file provided,\n * so the operator at least sees the tool list and the api-key prefix.\n */\nexport async function consentInputFromClient(\n haven: HavenClient,\n seed: CredentialIdentitySeed,\n toolNames: readonly HavenMcpToolName[],\n): Promise<ConsentInput> {\n let allowanceSummary: ConsentInput['allowanceSummary'] = seed.allowanceSummary ?? []\n let safeAddress = seed.safeAddress\n let delegateAddress: string | undefined = seed.delegateAddress\n let chainId: number | undefined = seed.chainId\n\n try {\n const summary = await haven.getAllowances()\n const list: HavenAllowance[] = isAllowanceSummary(summary)\n ? summary.allowances\n : Array.isArray(summary)\n ? (summary as HavenAllowance[])\n : []\n if (isAllowanceSummary(summary)) {\n safeAddress = summary.safeAddress ?? safeAddress\n delegateAddress = summary.delegateAddress\n chainId = typeof summary.chainId === 'number' ? summary.chainId : chainId\n }\n const liveAllowanceSummary = list.map((a) => ({\n token: a.tokenSymbol ?? 'UNKNOWN',\n amount: a.onchain?.amount ?? a.configuredAmount ?? '0',\n resetMinutes:\n typeof a.onchain?.resetTimeMin === 'number'\n ? a.onchain.resetTimeMin\n : typeof a.resetPeriodMin === 'number'\n ? a.resetPeriodMin\n : null,\n }))\n allowanceSummary = liveAllowanceSummary\n } catch {\n // Identity falls back to what the credential file gave us.\n }\n\n return {\n apiKeyPrefix: derivePrefix(seed.apiKey),\n apiUrl: seed.apiUrl,\n agentId: seed.agentId,\n safeAddress,\n delegateAddress,\n chainId,\n toolNames,\n allowanceSummary,\n }\n}\n\nfunction isAllowanceSummary(value: unknown): value is HavenAllowanceSummary {\n return (\n typeof value === 'object' &&\n value !== null &&\n 'allowances' in value &&\n Array.isArray((value as { allowances: unknown }).allowances)\n )\n}\n\n/**\n * Use the leading characters of the api key (which already begins with the\n * non-secret `sk_agent_` prefix) as a stable, low-information identifier.\n * Twelve characters is enough to disambiguate credentials in front of a\n * human but not enough to reveal the secret.\n */\nfunction derivePrefix(apiKey: string): string {\n return apiKey.slice(0, 12)\n}\n\n/** Convenience: the canonical tool list registered by the server. */\nexport function registeredToolNames(): HavenMcpToolName[] {\n return Object.keys(toolSchemas) as HavenMcpToolName[]\n}\n","import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'\nimport { HavenClient } from '@haven_ai/sdk'\nimport { loadCredentials, type HavenCredentialFile } from './credentials.js'\nimport {\n createToolHandlers,\n toolDescriptions,\n toolSchemas,\n type HavenMcpToolName,\n type ToolPayload,\n} from './tools.js'\nimport {\n consentInputFromClient,\n ensureConsent,\n registeredToolNames,\n type ConsentDecision,\n} from './consent.js'\n\nexport interface HavenMcpServerOptions {\n credentialsPath?: string\n identityPath?: string\n signerPath?: string\n credentials?: HavenCredentialFile\n /**\n * When true, write the consent sidecar file (`<credentials>.ack.json`)\n * with the current consent hash and proceed. Surfaced via the `--ack`\n * CLI flag.\n */\n writeAck?: boolean\n /**\n * When true, skip the consent gate entirely. Reserved for tests and\n * controlled embedding — production CLIs should not set this.\n */\n skipConsent?: boolean\n}\n\nexport interface ResolvedHavenClient {\n client: HavenClient\n credentials: HavenCredentialFile\n}\n\nexport async function createHavenClient(options: HavenMcpServerOptions = {}): Promise<HavenClient> {\n const { client } = await resolveHavenClient(options)\n return client\n}\n\nexport async function resolveHavenClient(options: HavenMcpServerOptions = {}): Promise<ResolvedHavenClient> {\n const credentialSource = options.credentialsPath || options.identityPath || options.signerPath\n ? {\n credentialsPath: options.credentialsPath,\n identityPath: options.identityPath,\n signerPath: options.signerPath,\n }\n : undefined\n const credentials = options.credentials ?? await loadCredentials(credentialSource)\n const client = new HavenClient({\n apiKey: credentials.apiKey,\n delegateKey: credentials.delegateKey,\n baseUrl: credentials.apiUrl,\n })\n return { client, credentials }\n}\n\nexport async function createHavenMcpServer(options: HavenMcpServerOptions = {}): Promise<McpServer> {\n const haven = await createHavenClient(options)\n return buildMcpServer(haven)\n}\n\n/**\n * Build an MCP server bound to the supplied Haven client.\n *\n * Each tool dispatch is wrapped in `haven.withRequestContext` so every\n * Haven API request the dispatch issues carries `X-Haven-MCP-Tool: <name>`\n * — and *only* that dispatch's requests see the header. The SDK uses an\n * `AsyncLocalStorage` for the context, so two tool calls running\n * concurrently cannot leak headers into each other and the backend\n * `agent_tool_invocations` rows are always attributed to the right tool.\n */\nexport const MCP_NAME = '@haven_ai/mcp'\nexport const MCP_VERSION = '0.1.4-alpha'\n\nexport function buildMcpServer(haven: HavenClient): McpServer {\n const server = new McpServer({\n name: MCP_NAME,\n version: MCP_VERSION,\n })\n\n const handlers = createToolHandlers(haven)\n const registerTool = (server as any).tool.bind(server)\n for (const name of Object.keys(toolSchemas) as HavenMcpToolName[]) {\n registerTool(\n name,\n toolDescriptions[name],\n toolSchemas[name],\n async (args: unknown) =>\n haven.withRequestContext({ 'X-Haven-MCP-Tool': name }, async () =>\n toMcpResult(await handlers[name](args)),\n ),\n )\n }\n\n return server\n}\n\nexport async function runStdioServer(options: HavenMcpServerOptions = {}): Promise<void> {\n const { client: haven, credentials } = await resolveHavenClient(options)\n\n if (!options.skipConsent) {\n const decision = await runConsentGate(haven, credentials, options)\n if (!decision.ok) {\n // The consent block has already been printed by `ensureConsent`.\n const err: NodeJS.ErrnoException = new Error(\n decision.reason === 'env_var_mismatch'\n ? 'Haven MCP consent acknowledgement does not match the current configuration.'\n : 'Haven MCP server requires a one-time consent acknowledgement before starting.',\n )\n err.code = 'HAVEN_MCP_NO_CONSENT'\n throw err\n }\n }\n\n const server = buildMcpServer(haven)\n await server.connect(new StdioServerTransport())\n}\n\nexport async function runConsentGate(\n haven: HavenClient,\n credentials: HavenCredentialFile,\n options: HavenMcpServerOptions,\n): Promise<ConsentDecision> {\n const toolNames = registeredToolNames()\n const input = await consentInputFromClient(\n haven,\n {\n apiKey: credentials.apiKey,\n apiUrl: credentials.apiUrl,\n agentId: credentials.agentId,\n safeAddress: credentials.safeAddress,\n delegateAddress: credentials.delegateAddress,\n chainId: credentials.chainId,\n allowanceSummary: credentials.allowanceSummary,\n },\n toolNames,\n )\n // Prefer the path actually used to load credentials (covers\n // HAVEN_CREDENTIALS as well as --credentials). If neither file path is\n // available the operator must use HAVEN_MCP_ACK; --ack has nowhere to\n // write a sidecar in that case.\n const credentialsPath = options.identityPath ?? options.credentialsPath ?? credentials.sourcePath\n return ensureConsent(input, {\n credentialsPath,\n writeAck: options.writeAck,\n })\n}\n\nfunction toMcpResult(payload: ToolPayload) {\n return {\n isError: !payload.success,\n content: [\n {\n type: 'text' as const,\n text: JSON.stringify(payload, null, 2),\n },\n ],\n }\n}\n","#!/usr/bin/env node\n\nimport { runStdioServer, type HavenMcpServerOptions } from './server.js'\n\nfunction parseArgs(argv: string[]): HavenMcpServerOptions {\n const options: HavenMcpServerOptions = {}\n for (let i = 0; i < argv.length; i += 1) {\n const arg = argv[i]\n if (arg === '--credentials' || arg === '--credentials-path') {\n options.credentialsPath = argv[i + 1]\n i += 1\n } else if (arg === '--identity') {\n options.identityPath = argv[i + 1]\n i += 1\n } else if (arg === '--signer') {\n options.signerPath = argv[i + 1]\n i += 1\n } else if (arg === '--transport') {\n const transport = argv[i + 1]\n i += 1\n if (transport !== 'stdio') {\n throw new Error('Only local stdio transport is supported. Haven does not provide a remote MCP signer mode.')\n }\n } else if (arg === '--ack') {\n // Write the consent-gate acknowledgement next to the credential file\n // and proceed. Used on first-launch to opt the operator in once.\n options.writeAck = true\n } else if (arg === '--help' || arg === '-h') {\n process.stdout.write([\n 'Haven MCP server',\n '',\n 'Usage:',\n ' npx @haven_ai/mcp --credentials /path/to/agent.json',\n ' npx @haven_ai/mcp --identity /path/to/identity.json --signer /path/to/signer.json',\n '',\n 'Options:',\n ' --credentials <path> Haven credential JSON file. Also supported: HAVEN_CREDENTIALS.',\n ' --identity <path> Haven identity JSON file written by @haven_ai/connect.',\n ' --signer <path> Haven signer JSON file written by @haven_ai/connect.',\n ' --transport stdio Local stdio transport. This is the only supported mode.',\n ' --ack Acknowledge the first-launch consent block and write',\n ' a sidecar acknowledgement file next to the credential.',\n '',\n 'Consent:',\n ' On first launch the server prints the tool list and the on-chain',\n ' allowance summary, then refuses to start unless you have acknowledged.',\n ' Acknowledge with EITHER --ack OR HAVEN_MCP_ACK=<hash> in your environment.',\n '',\n ].join('\\n'))\n process.exit(0)\n }\n }\n return options\n}\n\nasync function main(): Promise<void> {\n await runStdioServer(parseArgs(process.argv.slice(2)))\n}\n\nmain().catch((err) => {\n process.stderr.write(`${err instanceof Error ? err.message : String(err)}\\n`)\n process.exit(1)\n})\n"]}