@stratabook/mcp 0.2.12 → 0.2.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,29 @@
3
3
  All notable changes to the Strata SDKs (`@stratabook/sdk`, `@stratabook/mcp`,
4
4
  and the `strata-sdk` Rust crate) are recorded here. Versions move together.
5
5
 
6
+ ## 0.2.14
7
+
8
+ - Make `strata-mcp connect` the complete client-neutral trading setup flow:
9
+ choose limits in Strata, sign once, save the secret locally, and return to a
10
+ confirmed connected Control Center without environment variables or config
11
+ editing.
12
+ - Re-running `connect` now rotates an existing local session atomically, and
13
+ saves the new credential only after both activation and old-key revocation
14
+ are confirmed.
15
+
16
+ ## 0.2.13
17
+
18
+ - Add `strata-mcp connect`: generate the session secret locally, open the
19
+ owner-wallet registration page with only its public key, verify activation,
20
+ and save a mode-0600 local credential. No secret copying, chat, config-file,
21
+ or environment-variable setup is required.
22
+ - Add `strata-mcp disconnect` for exact-session on-chain revocation followed
23
+ by local credential removal.
24
+ - Automatically load the private local connection for MCP and `doctor`, while
25
+ preserving explicit environment variables for managed deployments.
26
+ - Keep read-only tools immediate and client-neutral, and document hosted HTTP,
27
+ Cursor, Claude Code, Codex, Windsurf, and generic stdio installation.
28
+
6
29
  ## 0.2.12
7
30
 
8
31
  - Make MCP client-neutral: the primary setup works with any stdio or
package/README.md CHANGED
@@ -22,8 +22,27 @@ Read-only use needs no wallet, key, autonomy setting, or environment variable:
22
22
  npx -y @stratabook/mcp
23
23
  ```
24
24
 
25
- Do not paste a session secret into chat. Session setup is optional and appears
26
- only when the user wants the local MCP to sign trading writes.
25
+ Trading setup is optional. When needed, the local MCP generates its own key,
26
+ opens the owner-wallet page, and saves the secret in a mode-0600 local file.
27
+ The browser and Strata receive only the public key:
28
+
29
+ ```sh
30
+ npx -y @stratabook/mcp connect
31
+ ```
32
+
33
+ This opens the client-neutral Strata limit picker, registers the locally
34
+ generated key with one wallet signature, saves the credential privately, and
35
+ returns to the live Control Center. Run the same command again to replace the
36
+ old key atomically; the old key is revoked in the same signed transaction.
37
+
38
+ There is no secret to paste into chat, no environment-variable screen, and no
39
+ client config to edit after the read-only server is installed. Restart or
40
+ refresh the MCP client after the browser confirms connection. Revoke the exact
41
+ session and delete its local credential with:
42
+
43
+ ```sh
44
+ npx -y @stratabook/mcp disconnect
45
+ ```
27
46
 
28
47
  Generic configuration for Claude Desktop, Cursor, Windsurf, and other
29
48
  JSON-config MCP clients:
@@ -51,6 +70,10 @@ Check the whole read-only connection without placing a trade:
51
70
  npx -y @stratabook/mcp doctor
52
71
  ```
53
72
 
73
+ The private credential defaults to `~/.config/strata/mcp.json` on macOS/Linux
74
+ and `%APPDATA%\Strata\mcp.json` on Windows. Override it with
75
+ `STRATA_MCP_CREDENTIALS_FILE` when a managed secret volume is required.
76
+
54
77
  The compact default exposes the tools ordinary users need:
55
78
 
56
79
  - `strata_markets`, `strata_marks`, `strata_book`, `strata_candles`, `strata_trades`
package/dist/src/cli.js CHANGED
@@ -8,16 +8,26 @@ import { createStrataMcpServer, probeStrataMcpReadiness } from "./server.js";
8
8
  import { sessionAutonomyFromEnv } from "./autonomy.js";
9
9
  import { SERVER_VERSION } from "./version.js";
10
10
  import { friendlyApiError, humanQuoteAmount, parseToolMode } from "./usability.js";
11
+ import { DEFAULT_PAIRING_WEB_BASE, loadTradingEnvironment, runLocalPairing, tradingCredentialsPath, } from "./pairing.js";
11
12
  function parse(argv) {
12
- const command = argv[0] === "doctor" ? "doctor" : "serve";
13
- const args = command === "doctor" ? argv.slice(1) : argv;
13
+ const knownCommands = new Set(["doctor", "connect", "disconnect"]);
14
+ const first = argv[0];
15
+ const command = first && knownCommands.has(first)
16
+ ? first
17
+ : "serve";
18
+ const args = command === "serve" ? argv : argv.slice(1);
14
19
  const values = new Map();
20
+ let openBrowser = true;
15
21
  for (let index = 0; index < args.length; index++) {
16
22
  const token = args[index];
17
23
  if (token === "--help" || token === "-h") {
18
24
  help();
19
25
  process.exit(0);
20
26
  }
27
+ if (token === "--no-open") {
28
+ openBrowser = false;
29
+ continue;
30
+ }
21
31
  if (!token?.startsWith("--"))
22
32
  throw new Error(`unexpected argument: ${token}`);
23
33
  const next = args[index + 1];
@@ -43,6 +53,11 @@ function parse(argv) {
43
53
  timeoutMs,
44
54
  host,
45
55
  port,
56
+ openBrowser,
57
+ webBase: values.get("web-base") ?? process.env.STRATA_MCP_WEB_BASE ?? DEFAULT_PAIRING_WEB_BASE,
58
+ ...(values.get("credentials-file") === undefined
59
+ ? {}
60
+ : { credentialsFile: values.get("credentials-file") }),
46
61
  };
47
62
  }
48
63
  function boundedInteger(raw, name, min, max) {
@@ -58,6 +73,8 @@ function help() {
58
73
  Usage:
59
74
  strata-mcp
60
75
  strata-mcp doctor
76
+ strata-mcp connect
77
+ strata-mcp disconnect
61
78
  strata-mcp --transport http [--host localhost] [--port 8787]
62
79
 
63
80
  Options:
@@ -67,13 +84,17 @@ Options:
67
84
  --timeout-ms N Upstream timeout, 250..60000 (default: 10000)
68
85
  --host HOST HTTP bind host (default: localhost)
69
86
  --port N HTTP port (default: 8787)
87
+ --credentials-file PATH Override the private local trading credential file
88
+ --no-open Print the wallet pairing URL without opening a browser
70
89
 
71
90
  Read-only markets, books, and Sonar quotes work immediately. Run strata-mcp
72
- doctor to check them. Trading setup is only needed for trading writes; connect
73
- it at https://stratabook.app/agents. Strata never asks for seed phrases.
91
+ doctor to check them. Run strata-mcp connect to choose limits and register a
92
+ local session with one owner signature; run it again to replace that session
93
+ atomically. There are no secrets to copy or environment variables to edit.
94
+ Run strata-mcp disconnect to revoke it. Strata never asks for seed phrases.
74
95
  `);
75
96
  }
76
- async function runDoctor(options) {
97
+ async function runDoctor(options, sessionEnv) {
77
98
  const client = new StrataClient({ apiBase: options.apiBase, timeoutMs: options.timeoutMs });
78
99
  process.stdout.write("Strata MCP doctor\n\n");
79
100
  try {
@@ -95,10 +116,10 @@ async function runDoctor(options) {
95
116
  else {
96
117
  process.stdout.write("○ SOL/USDC is not currently listed; quote check skipped\n");
97
118
  }
98
- const sessionConfigured = Boolean(process.env.STRATA_SESSION_SECRET_KEY && process.env.STRATA_OWNER_WALLET);
119
+ const sessionConfigured = Boolean(sessionEnv.STRATA_SESSION_SECRET_KEY && sessionEnv.STRATA_OWNER_WALLET);
99
120
  process.stdout.write(sessionConfigured
100
121
  ? "✓ Trading connection found (no transaction sent)\n"
101
- : "○ Trading is not connected; read-only use is ready. Connect later at https://stratabook.app/agents\n");
122
+ : "○ Trading is not connected; read-only use is ready. Run strata-mcp connect when needed.\n");
102
123
  }
103
124
  catch (error) {
104
125
  if (error instanceof StrataApiError) {
@@ -202,15 +223,27 @@ function safeError(error) {
202
223
  }
203
224
  async function main() {
204
225
  const options = parse(process.argv.slice(2));
226
+ if (options.command === "connect" || options.command === "disconnect") {
227
+ await runLocalPairing({
228
+ action: options.command,
229
+ webBase: options.webBase,
230
+ apiBase: options.apiBase,
231
+ openBrowser: options.openBrowser,
232
+ ...(options.credentialsFile === undefined ? {} : { credentialsFile: options.credentialsFile }),
233
+ });
234
+ return;
235
+ }
236
+ const sessionEnv = await loadTradingEnvironment(process.env);
205
237
  if (options.command === "doctor") {
206
- await runDoctor(options);
238
+ await runDoctor(options, sessionEnv);
207
239
  return;
208
240
  }
209
- const sessionAutonomy = await sessionAutonomyFromEnv(process.env);
241
+ const sessionAutonomy = await sessionAutonomyFromEnv(sessionEnv);
210
242
  const withSession = sessionAutonomy ? { ...options, sessionAutonomy } : options;
211
243
  if (sessionAutonomy) {
212
244
  process.stderr.write(`[strata-mcp] session autonomy: ${sessionAutonomy.config.level} `
213
- + `(wallet ${sessionAutonomy.ownerWallet.slice(0, 6)}…, session ${sessionAutonomy.signer.publicKey.slice(0, 6)}…)\n`);
245
+ + `(wallet ${sessionAutonomy.ownerWallet.slice(0, 6)}…, session ${sessionAutonomy.signer.publicKey.slice(0, 6)}…, `
246
+ + `credentials ${process.env.STRATA_SESSION_SECRET_KEY ? "environment" : tradingCredentialsPath(process.env)})\n`);
214
247
  }
215
248
  if (withSession.transport === "stdio")
216
249
  await runStdio(withSession);
@@ -49,7 +49,7 @@ export declare const STRATA_AGENT_HARNESS: {
49
49
  readonly instruction: "When an owner requests a Vault pause or resume and vault.pause is live, prepare the exact transaction with the official SDK, verify that the wallet and requested state are unchanged, then have the owner-configured signer sign and broadcast it externally. Preparation alone does not change state.";
50
50
  }, {
51
51
  readonly id: "onboard_vault";
52
- readonly instruction: "Onboarding is one owner signature, once: register the external session key with vault.setup (only the wallet and the session key are required; one session then trades every market) or simply name the session key on the first vault.deposit, which registers it in the same transaction. Policy fields — expiry, cadence, tolerance, per-asset limits — are optional. Verify every echoed field and the prepared transaction before external owner signing and broadcast; retain the session key only in the owner's signer.";
52
+ readonly instruction: "Onboarding is one owner signature: register the external session key with vault.setup (only the wallet and the session key are required; one session then trades every market) or simply name the session key on the first vault.deposit, which registers it in the same transaction. Policy fields — expiry, cadence, tolerance, per-asset limits — are optional. Supplying replace_session_public_key atomically revokes the old key while registering the new one. Verify every echoed field and the prepared transaction before external owner signing and broadcast; retain the session key only in the owner's signer.";
53
53
  }, {
54
54
  readonly id: "fund_vault";
55
55
  readonly instruction: "When vault.deposit is live, select an asset from the discovered market and use an exact positive atomic amount. Verify the echoed owner, market, asset, and amount plus the prepared transaction before external owner signing and broadcast.";
@@ -64,7 +64,7 @@ export declare const STRATA_AGENT_HARNESS: {
64
64
  readonly instruction: "When vault.policy.manage is live, use blocked mode with no allowed wallets to freeze withdrawals or restricted mode with one to eight exact destination-owner wallets. Verify the echoed mode and complete wallet list before external owner signing and broadcast.";
65
65
  }, {
66
66
  readonly id: "reconcile_maker_status";
67
- readonly instruction: "When mm.status.read is live, read the maker's products by wallet address (public, no signature) before and after any maker action: resting firm orders, the intent budget, live signed quotes, each Strand and Current with its remaining exposure and expiry, oracle health, and armed dead-man guards. Reconcile against what the agent believes it posted; treat missing, expired, or disabled products as not quoting.";
67
+ readonly instruction: "When mm.status.read is live, read the maker's products by wallet address (public, no signature) before and after any maker action: resting firm orders, live signed quotes, each Strand and Current with its remaining exposure and expiry, oracle health, and armed dead-man guards. Reconcile against what the agent believes it posted; treat missing, expired, or disabled products as not quoting.";
68
68
  }, {
69
69
  readonly id: "stream_maker_fills";
70
70
  readonly instruction: "When mm.fills.stream is live, keep one maker stream open per market through the official SDK by wallet address (public, no signature): start from the maker snapshot, apply only contiguous maker_fill and maker_status events, and recover any gap or reconnect from a fresh snapshot. Reconcile every fill and exposure change against the maker's own state before quoting further.";
@@ -551,4 +551,4 @@ export declare const STRATA_ACTION_GRAPH: {
551
551
  }];
552
552
  };
553
553
  export declare const STRATA_ACTION_GRAPH_URI = "strata://action-graph/v1";
554
- export declare const STRATA_AGENT_HARNESS_INSTRUCTIONS = "Strata read-only tools work immediately with no wallet, approval, session key, or environment setup. Call the requested tool directly: use strata_quote for a quote, strata_markets only when the market is unknown, and strata_portfolio for a public account. Do not begin with capability, graph, status, or market discovery unless the requested tool is unavailable, the objective is advanced or ambiguous, or the user asks what Strata supports. Simple MCP tools accept exact human amounts such as 0.1 SOL, 20 USDC, or $20; advanced and SDK interfaces also accept token atoms. Never request or accept a session secret in chat. A session is needed only when the user asks to sign a trading write; if it is missing, strata_trade returns a read-only quote and the single setup link https://stratabook.app/agents. Revoke, withdraw, pause, and policy changes are owner-wallet actions and never use the session signer. Strata Agent Harness 1.0. The action-graph resources are optional references for advanced integrations. The external agent owner controls permission and signer authority. Strata accepts public keys, detached signatures, and signed transactions, never private keys or seed phrases. Check quote bindings, labelled fees, minimum output, price impact, tolerance, and expiry. When portfolio.read is live, read the owner's live Vault portfolio before sizing a write and treat null USD totals as an incomplete valuation, never as zero. When mm.status.read is live, reconcile the owner's maker products and exposure before and after maker actions. For normal Strand or Current operation, prefer strata_market_making_prepare, sign only its prepared transaction externally, then pass its unchanged preparationToken with the signed transaction to strata_market_making_submit_and_wait. Advanced order, TWAP, and execution integrations may use explicit challenge, prepare, verify, sign, and submit flows with idempotency. Stop on ambiguity, sequence gaps, unavailable capabilities, paused markets, inconsistent bindings, expiry, or missing signer authority.";
554
+ export declare const STRATA_AGENT_HARNESS_INSTRUCTIONS = "Strata read-only tools work immediately with no wallet, approval, session key, or environment setup. Call the requested tool directly: use strata_quote for a quote, strata_markets only when the market is unknown, and strata_portfolio for a public account. Do not begin with capability, graph, status, or market discovery unless the requested tool is unavailable, the objective is advanced or ambiguous, or the user asks what Strata supports. Simple MCP tools accept exact human amounts such as 0.1 SOL, 20 USDC, or $20; advanced and SDK interfaces also accept token atoms. Never request or accept a session secret in chat. A session is needed only when the user asks to sign a trading write; if it is missing, strata_trade returns a read-only quote and the single setup link https://stratabook.app/agents. The user can run npx -y @stratabook/mcp connect to generate the secret locally, choose on-chain limits, and register with one owner signature while the Agents page receives only the public key. Rerunning the command atomically replaces the old session. Revoke, withdraw, pause, and policy changes are owner-wallet actions and never use the session signer. Strata Agent Harness 1.0. The action-graph resources are optional references for advanced integrations. The external agent owner controls permission and signer authority. Strata accepts public keys, detached signatures, and signed transactions, never private keys or seed phrases. Check quote bindings, labelled fees, minimum output, price impact, tolerance, and expiry. When portfolio.read is live, read the owner's live Vault portfolio before sizing a write and treat null USD totals as an incomplete valuation, never as zero. When mm.status.read is live, reconcile the owner's maker products and exposure before and after maker actions. For normal Strand or Current operation, prefer strata_market_making_prepare, sign only its prepared transaction externally, then pass its unchanged preparationToken with the signed transaction to strata_market_making_submit_and_wait. Advanced order, TWAP, and execution integrations may use explicit challenge, prepare, verify, sign, and submit flows with idempotency. Stop on ambiguity, sequence gaps, unavailable capabilities, paused markets, inconsistent bindings, expiry, or missing signer authority.";
@@ -141,7 +141,7 @@ export const STRATA_AGENT_HARNESS = {
141
141
  },
142
142
  {
143
143
  "id": "onboard_vault",
144
- "instruction": "Onboarding is one owner signature, once: register the external session key with vault.setup (only the wallet and the session key are required; one session then trades every market) or simply name the session key on the first vault.deposit, which registers it in the same transaction. Policy fields — expiry, cadence, tolerance, per-asset limits — are optional. Verify every echoed field and the prepared transaction before external owner signing and broadcast; retain the session key only in the owner's signer."
144
+ "instruction": "Onboarding is one owner signature: register the external session key with vault.setup (only the wallet and the session key are required; one session then trades every market) or simply name the session key on the first vault.deposit, which registers it in the same transaction. Policy fields — expiry, cadence, tolerance, per-asset limits — are optional. Supplying replace_session_public_key atomically revokes the old key while registering the new one. Verify every echoed field and the prepared transaction before external owner signing and broadcast; retain the session key only in the owner's signer."
145
145
  },
146
146
  {
147
147
  "id": "fund_vault",
@@ -161,7 +161,7 @@ export const STRATA_AGENT_HARNESS = {
161
161
  },
162
162
  {
163
163
  "id": "reconcile_maker_status",
164
- "instruction": "When mm.status.read is live, read the maker's products by wallet address (public, no signature) before and after any maker action: resting firm orders, the intent budget, live signed quotes, each Strand and Current with its remaining exposure and expiry, oracle health, and armed dead-man guards. Reconcile against what the agent believes it posted; treat missing, expired, or disabled products as not quoting."
164
+ "instruction": "When mm.status.read is live, read the maker's products by wallet address (public, no signature) before and after any maker action: resting firm orders, live signed quotes, each Strand and Current with its remaining exposure and expiry, oracle health, and armed dead-man guards. Reconcile against what the agent believes it posted; treat missing, expired, or disabled products as not quoting."
165
165
  },
166
166
  {
167
167
  "id": "stream_maker_fills",
@@ -789,4 +789,4 @@ export const STRATA_ACTION_GRAPH = {
789
789
  ]
790
790
  };
791
791
  export const STRATA_ACTION_GRAPH_URI = "strata://action-graph/v1";
792
- export const STRATA_AGENT_HARNESS_INSTRUCTIONS = "Strata read-only tools work immediately with no wallet, approval, session key, or environment setup. Call the requested tool directly: use strata_quote for a quote, strata_markets only when the market is unknown, and strata_portfolio for a public account. Do not begin with capability, graph, status, or market discovery unless the requested tool is unavailable, the objective is advanced or ambiguous, or the user asks what Strata supports. Simple MCP tools accept exact human amounts such as 0.1 SOL, 20 USDC, or $20; advanced and SDK interfaces also accept token atoms. Never request or accept a session secret in chat. A session is needed only when the user asks to sign a trading write; if it is missing, strata_trade returns a read-only quote and the single setup link https://stratabook.app/agents. Revoke, withdraw, pause, and policy changes are owner-wallet actions and never use the session signer. Strata Agent Harness 1.0. The action-graph resources are optional references for advanced integrations. The external agent owner controls permission and signer authority. Strata accepts public keys, detached signatures, and signed transactions, never private keys or seed phrases. Check quote bindings, labelled fees, minimum output, price impact, tolerance, and expiry. When portfolio.read is live, read the owner's live Vault portfolio before sizing a write and treat null USD totals as an incomplete valuation, never as zero. When mm.status.read is live, reconcile the owner's maker products and exposure before and after maker actions. For normal Strand or Current operation, prefer strata_market_making_prepare, sign only its prepared transaction externally, then pass its unchanged preparationToken with the signed transaction to strata_market_making_submit_and_wait. Advanced order, TWAP, and execution integrations may use explicit challenge, prepare, verify, sign, and submit flows with idempotency. Stop on ambiguity, sequence gaps, unavailable capabilities, paused markets, inconsistent bindings, expiry, or missing signer authority.";
792
+ export const STRATA_AGENT_HARNESS_INSTRUCTIONS = "Strata read-only tools work immediately with no wallet, approval, session key, or environment setup. Call the requested tool directly: use strata_quote for a quote, strata_markets only when the market is unknown, and strata_portfolio for a public account. Do not begin with capability, graph, status, or market discovery unless the requested tool is unavailable, the objective is advanced or ambiguous, or the user asks what Strata supports. Simple MCP tools accept exact human amounts such as 0.1 SOL, 20 USDC, or $20; advanced and SDK interfaces also accept token atoms. Never request or accept a session secret in chat. A session is needed only when the user asks to sign a trading write; if it is missing, strata_trade returns a read-only quote and the single setup link https://stratabook.app/agents. The user can run npx -y @stratabook/mcp connect to generate the secret locally, choose on-chain limits, and register with one owner signature while the Agents page receives only the public key. Rerunning the command atomically replaces the old session. Revoke, withdraw, pause, and policy changes are owner-wallet actions and never use the session signer. Strata Agent Harness 1.0. The action-graph resources are optional references for advanced integrations. The external agent owner controls permission and signer authority. Strata accepts public keys, detached signatures, and signed transactions, never private keys or seed phrases. Check quote bindings, labelled fees, minimum output, price impact, tolerance, and expiry. When portfolio.read is live, read the owner's live Vault portfolio before sizing a write and treat null USD totals as an incomplete valuation, never as zero. When mm.status.read is live, reconcile the owner's maker products and exposure before and after maker actions. For normal Strand or Current operation, prefer strata_market_making_prepare, sign only its prepared transaction externally, then pass its unchanged preparationToken with the signed transaction to strata_market_making_submit_and_wait. Advanced order, TWAP, and execution integrations may use explicit challenge, prepare, verify, sign, and submit flows with idempotency. Stop on ambiguity, sequence gaps, unavailable capabilities, paused markets, inconsistent bindings, expiry, or missing signer authority.";
@@ -0,0 +1,27 @@
1
+ export declare const DEFAULT_PAIRING_WEB_BASE = "https://stratabook.app";
2
+ export interface StoredTradingConnection {
3
+ readonly schema_version: 1;
4
+ readonly owner_wallet: string;
5
+ readonly session_public_key: string;
6
+ readonly session_secret_key: string;
7
+ readonly autonomy: "ask" | "limits" | "instant";
8
+ readonly connected_at_ms: number;
9
+ }
10
+ export type PairingAction = "connect" | "disconnect";
11
+ export interface PairingOptions {
12
+ readonly action: PairingAction;
13
+ readonly webBase?: string;
14
+ readonly openBrowser?: boolean;
15
+ readonly credentialsFile?: string;
16
+ readonly apiBase?: string;
17
+ readonly env?: Readonly<Record<string, string | undefined>>;
18
+ readonly nowMs?: () => number;
19
+ }
20
+ export declare function tradingCredentialsPath(env?: Readonly<Record<string, string | undefined>>, platform?: NodeJS.Platform, home?: string): string;
21
+ export declare function readTradingConnection(path?: string): Promise<StoredTradingConnection | null>;
22
+ export declare function writeTradingConnection(connection: StoredTradingConnection, path?: string): Promise<void>;
23
+ export declare function removeTradingConnection(path?: string): Promise<void>;
24
+ /** Explicit environment variables win; otherwise load the private local file. */
25
+ export declare function loadTradingEnvironment(env?: Readonly<Record<string, string | undefined>>): Promise<Record<string, string | undefined>>;
26
+ export declare function pairingPageUrl(webBase: string, action: PairingAction, sessionPublicKey: string, callbackUrl: string, existing: Pick<StoredTradingConnection, "owner_wallet" | "session_public_key"> | null): string;
27
+ export declare function runLocalPairing(options: PairingOptions): Promise<void>;
@@ -0,0 +1,300 @@
1
+ import { spawn } from "node:child_process";
2
+ import { randomBytes } from "node:crypto";
3
+ import { chmod, mkdir, readFile, unlink, writeFile } from "node:fs/promises";
4
+ import { createServer } from "node:http";
5
+ import { homedir } from "node:os";
6
+ import { dirname, join, resolve } from "node:path";
7
+ import { DEFAULT_API_BASE, generateSessionKeypair, } from "@stratabook/sdk";
8
+ const PUBLIC_KEY_PATTERN = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
9
+ const SECRET_KEY_PATTERN = /^[1-9A-HJ-NP-Za-km-z]{80,90}$/;
10
+ const PAIRING_TIMEOUT_MS = 10 * 60_000;
11
+ export const DEFAULT_PAIRING_WEB_BASE = "https://stratabook.app";
12
+ function validPublicKey(value) {
13
+ return typeof value === "string" && PUBLIC_KEY_PATTERN.test(value);
14
+ }
15
+ function validSecretKey(value) {
16
+ return typeof value === "string" && SECRET_KEY_PATTERN.test(value);
17
+ }
18
+ export function tradingCredentialsPath(env = process.env, platform = process.platform, home = homedir()) {
19
+ const override = env.STRATA_MCP_CREDENTIALS_FILE?.trim();
20
+ if (override)
21
+ return resolve(override);
22
+ if (platform === "win32") {
23
+ const appData = env.APPDATA?.trim()
24
+ || join(env.USERPROFILE?.trim() || home, "AppData", "Roaming");
25
+ return join(appData, "Strata", "mcp.json");
26
+ }
27
+ const configRoot = env.XDG_CONFIG_HOME?.trim() || join(home, ".config");
28
+ return join(configRoot, "strata", "mcp.json");
29
+ }
30
+ export async function readTradingConnection(path = tradingCredentialsPath()) {
31
+ let raw;
32
+ try {
33
+ raw = await readFile(path, "utf8");
34
+ }
35
+ catch (error) {
36
+ if (error.code === "ENOENT")
37
+ return null;
38
+ throw error;
39
+ }
40
+ let value;
41
+ try {
42
+ value = JSON.parse(raw);
43
+ }
44
+ catch {
45
+ throw new Error(`Strata trading credentials are not valid JSON: ${path}`);
46
+ }
47
+ if (!value || typeof value !== "object") {
48
+ throw new Error(`Strata trading credentials are invalid: ${path}`);
49
+ }
50
+ const candidate = value;
51
+ if (candidate.schema_version !== 1
52
+ || !validPublicKey(candidate.owner_wallet)
53
+ || !validPublicKey(candidate.session_public_key)
54
+ || !validSecretKey(candidate.session_secret_key)
55
+ || !["ask", "limits", "instant"].includes(candidate.autonomy ?? "")
56
+ || !Number.isSafeInteger(candidate.connected_at_ms)) {
57
+ throw new Error(`Strata trading credentials are invalid: ${path}`);
58
+ }
59
+ return candidate;
60
+ }
61
+ export async function writeTradingConnection(connection, path = tradingCredentialsPath()) {
62
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
63
+ await writeFile(path, `${JSON.stringify(connection, null, 2)}\n`, {
64
+ encoding: "utf8",
65
+ mode: 0o600,
66
+ });
67
+ // `mode` is honored on creation. chmod also tightens a pre-existing file.
68
+ if (process.platform !== "win32")
69
+ await chmod(path, 0o600);
70
+ }
71
+ export async function removeTradingConnection(path = tradingCredentialsPath()) {
72
+ try {
73
+ await unlink(path);
74
+ }
75
+ catch (error) {
76
+ if (error.code !== "ENOENT")
77
+ throw error;
78
+ }
79
+ }
80
+ /** Explicit environment variables win; otherwise load the private local file. */
81
+ export async function loadTradingEnvironment(env = process.env) {
82
+ if (env.STRATA_SESSION_SECRET_KEY || env.STRATA_OWNER_WALLET)
83
+ return { ...env };
84
+ const path = tradingCredentialsPath(env);
85
+ const connection = await readTradingConnection(path);
86
+ if (!connection)
87
+ return { ...env };
88
+ return {
89
+ ...env,
90
+ STRATA_OWNER_WALLET: connection.owner_wallet,
91
+ STRATA_SESSION_PUBLIC_KEY: connection.session_public_key,
92
+ STRATA_SESSION_SECRET_KEY: connection.session_secret_key,
93
+ STRATA_AUTONOMY: env.STRATA_AUTONOMY ?? connection.autonomy,
94
+ };
95
+ }
96
+ function pairingWebBase(raw) {
97
+ const url = new URL(raw);
98
+ const local = url.hostname === "localhost" || url.hostname === "127.0.0.1";
99
+ if (url.protocol !== "https:" && !(local && url.protocol === "http:")) {
100
+ throw new Error("pairing web base must use HTTPS (or HTTP on localhost)");
101
+ }
102
+ url.pathname = "";
103
+ url.search = "";
104
+ url.hash = "";
105
+ return url.toString().replace(/\/$/, "");
106
+ }
107
+ function launchBrowser(url) {
108
+ const command = process.platform === "darwin"
109
+ ? { file: "open", args: [url] }
110
+ : process.platform === "win32"
111
+ ? { file: "cmd", args: ["/c", "start", "", url] }
112
+ : { file: "xdg-open", args: [url] };
113
+ const child = spawn(command.file, command.args, { detached: true, stdio: "ignore" });
114
+ child.on("error", () => undefined);
115
+ child.unref();
116
+ }
117
+ export function pairingPageUrl(webBase, action, sessionPublicKey, callbackUrl, existing) {
118
+ const agentUrl = new URL("/agents", pairingWebBase(webBase));
119
+ agentUrl.searchParams.set("pair", action);
120
+ agentUrl.searchParams.set("session_public_key", sessionPublicKey);
121
+ if (existing)
122
+ agentUrl.searchParams.set("owner_wallet", existing.owner_wallet);
123
+ if (action === "connect" && existing) {
124
+ agentUrl.searchParams.set("replace_session_public_key", existing.session_public_key);
125
+ }
126
+ agentUrl.searchParams.set("callback", callbackUrl);
127
+ return agentUrl.toString();
128
+ }
129
+ async function waitForOnChainSession(apiBase, action, ownerWallet, sessionPublicKey, replaceSessionPublicKey) {
130
+ const deadline = Date.now() + 60_000;
131
+ let lastState = "unavailable";
132
+ const stateFor = async (key) => {
133
+ const query = new URLSearchParams({
134
+ wallet_address: ownerWallet,
135
+ session_public_key: key,
136
+ });
137
+ const response = await fetch(`${apiBase.replace(/\/$/, "")}/v2/vault/status?${query.toString()}`, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(10_000) });
138
+ if (!response.ok) {
139
+ lastState = `http_${response.status}`;
140
+ return null;
141
+ }
142
+ const body = await response.json();
143
+ if (body.wallet_address !== ownerWallet)
144
+ return null;
145
+ if (!body.session)
146
+ return "absent";
147
+ if (body.session.session_public_key !== key || typeof body.session.state !== "string")
148
+ return null;
149
+ return body.session.state;
150
+ };
151
+ while (Date.now() < deadline) {
152
+ try {
153
+ const state = await stateFor(sessionPublicKey);
154
+ lastState = state ?? lastState;
155
+ if (action === "disconnect" && state === "absent")
156
+ return;
157
+ if (action === "connect" && state === "active") {
158
+ if (!replaceSessionPublicKey || await stateFor(replaceSessionPublicKey) === "absent")
159
+ return;
160
+ lastState = "old_session_still_active";
161
+ }
162
+ }
163
+ catch (error) {
164
+ lastState = error instanceof Error ? error.name : "unavailable";
165
+ }
166
+ await new Promise((resolveDelay) => setTimeout(resolveDelay, 1_000));
167
+ }
168
+ throw new Error(`Strata could not confirm the ${action === "connect" ? "active" : "revoked"} session on-chain `
169
+ + `(last state: ${lastState}). The local credential was not changed.`);
170
+ }
171
+ async function waitForPairingCallback(sessionPublicKey, state, returnUrl, onComplete) {
172
+ let settle;
173
+ let reject;
174
+ const completion = new Promise((resolvePromise, rejectPromise) => {
175
+ settle = resolvePromise;
176
+ reject = rejectPromise;
177
+ });
178
+ let finished = false;
179
+ const server = createServer(async (request, response) => {
180
+ const requestUrl = new URL(request.url ?? "/", "http://127.0.0.1");
181
+ if (request.method !== "GET" || requestUrl.pathname !== `/complete/${state}`) {
182
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
183
+ response.end("Not found");
184
+ return;
185
+ }
186
+ if (finished) {
187
+ response.writeHead(409, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
188
+ response.end("Pairing already completed");
189
+ return;
190
+ }
191
+ const ownerWallet = requestUrl.searchParams.get("owner_wallet") ?? "";
192
+ const returnedSession = requestUrl.searchParams.get("session_public_key") ?? "";
193
+ if (!validPublicKey(ownerWallet) || returnedSession !== sessionPublicKey) {
194
+ response.writeHead(400, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
195
+ response.end("Invalid Strata pairing callback");
196
+ return;
197
+ }
198
+ finished = true;
199
+ try {
200
+ await onComplete(ownerWallet);
201
+ response.writeHead(303, {
202
+ location: returnUrl,
203
+ "cache-control": "no-store",
204
+ "x-content-type-options": "nosniff",
205
+ "x-frame-options": "DENY",
206
+ });
207
+ response.end();
208
+ settle(ownerWallet);
209
+ }
210
+ catch (error) {
211
+ response.writeHead(500, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" });
212
+ response.end("Could not save the local Strata connection");
213
+ reject(error instanceof Error ? error : new Error(String(error)));
214
+ }
215
+ finally {
216
+ server.close();
217
+ }
218
+ });
219
+ server.on("error", (error) => reject(error));
220
+ await new Promise((resolveListen, rejectListen) => {
221
+ server.once("error", rejectListen);
222
+ server.listen(0, "127.0.0.1", () => {
223
+ server.off("error", rejectListen);
224
+ resolveListen();
225
+ });
226
+ });
227
+ const address = server.address();
228
+ if (!address || typeof address === "string") {
229
+ server.close();
230
+ throw new Error("could not start the local Strata pairing callback");
231
+ }
232
+ const timeout = setTimeout(() => {
233
+ if (finished)
234
+ return;
235
+ finished = true;
236
+ server.close();
237
+ reject(new Error("Strata pairing timed out after 10 minutes"));
238
+ }, PAIRING_TIMEOUT_MS);
239
+ timeout.unref();
240
+ completion.finally(() => clearTimeout(timeout)).catch(() => undefined);
241
+ return {
242
+ callbackUrl: `http://127.0.0.1:${address.port}/complete/${state}`,
243
+ completion,
244
+ };
245
+ }
246
+ export async function runLocalPairing(options) {
247
+ const env = options.env ?? process.env;
248
+ const path = options.credentialsFile ?? tradingCredentialsPath(env);
249
+ const existing = await readTradingConnection(path);
250
+ if (options.action === "disconnect" && !existing) {
251
+ process.stdout.write("Strata trading is not connected. Read-only tools remain ready.\n");
252
+ return;
253
+ }
254
+ let generated;
255
+ if (options.action === "disconnect" && existing) {
256
+ generated = existing;
257
+ }
258
+ else {
259
+ const keypair = await generateSessionKeypair();
260
+ generated = {
261
+ schema_version: 1,
262
+ owner_wallet: "",
263
+ session_public_key: keypair.publicKey,
264
+ session_secret_key: keypair.secretKey,
265
+ autonomy: "instant",
266
+ connected_at_ms: 0,
267
+ };
268
+ }
269
+ const state = randomBytes(24).toString("hex");
270
+ const webBase = pairingWebBase(options.webBase ?? DEFAULT_PAIRING_WEB_BASE);
271
+ const returnUrl = new URL("/agents", webBase);
272
+ returnUrl.searchParams.set("paired", options.action === "connect" ? "connected" : "revoked");
273
+ const replaceSessionPublicKey = options.action === "connect"
274
+ ? existing?.session_public_key ?? null
275
+ : null;
276
+ const callback = await waitForPairingCallback(generated.session_public_key, state, returnUrl.toString(), async (ownerWallet) => {
277
+ await waitForOnChainSession(options.apiBase ?? DEFAULT_API_BASE, options.action, ownerWallet, generated.session_public_key, replaceSessionPublicKey);
278
+ if (options.action === "disconnect") {
279
+ if (existing?.owner_wallet !== ownerWallet) {
280
+ throw new Error("the revoking wallet does not own this local Strata connection");
281
+ }
282
+ await removeTradingConnection(path);
283
+ return;
284
+ }
285
+ await writeTradingConnection({
286
+ ...generated,
287
+ owner_wallet: ownerWallet,
288
+ connected_at_ms: (options.nowMs ?? Date.now)(),
289
+ }, path);
290
+ });
291
+ const agentUrl = pairingPageUrl(webBase, options.action, generated.session_public_key, callback.callbackUrl, existing);
292
+ process.stdout.write(`${options.action === "disconnect" ? "Revoke" : replaceSessionPublicKey ? "Replace" : "Connect"} Strata agent access in your browser:\n${agentUrl}\n\n`);
293
+ if (options.openBrowser !== false)
294
+ launchBrowser(agentUrl);
295
+ process.stdout.write("Waiting for the owner-wallet signature…\n");
296
+ const ownerWallet = await callback.completion;
297
+ process.stdout.write(options.action === "connect"
298
+ ? `✓ Trading connected for ${ownerWallet}. Credentials saved privately at ${path}.\nRestart or refresh your MCP client.\n`
299
+ : `✓ Session revoked for ${ownerWallet}. Local trading credentials removed.\n`);
300
+ }
@@ -524,7 +524,7 @@ export async function createStrataMcpServer(options = {}) {
524
524
  },
525
525
  }, async ({ marketId, walletAddress }) => {
526
526
  const response = await platformClient.marketMaking.status(marketId, walletAddress);
527
- return toolResult(response, `${response.active_products} active maker products; reconcile intent, Strand, Current, signed-quote, and dead-man state before changing exposure.`);
527
+ return toolResult(response, `${response.active_products} active maker products; reconcile Strand, Current, signed-quote, and dead-man state before changing exposure.`);
528
528
  });
529
529
  registerTool("strata_market_making_reputation", {
530
530
  title: "Read Strata maker reputation",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@stratabook/mcp",
3
- "version": "0.2.12",
3
+ "version": "0.2.14",
4
4
  "description": "Connect AI agents to Strata markets and Sonar quotes with MCP.",
5
5
  "type": "module",
6
6
  "license": "MIT OR Apache-2.0",
@@ -45,7 +45,7 @@
45
45
  },
46
46
  "dependencies": {
47
47
  "@modelcontextprotocol/sdk": "1.30.0",
48
- "@stratabook/sdk": "0.2.12",
48
+ "@stratabook/sdk": "0.2.14",
49
49
  "zod": "^3.25.76"
50
50
  },
51
51
  "devDependencies": {