@mysten-incubation/suipay-mcp 0.3.0-dev.35 → 0.3.0-dev.36

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
@@ -5,7 +5,7 @@ buyer-funded spend account. The buyer owns the account. The agent holds the
5
5
  delegate key and can spend only under the on-chain grant (recipient bind,
6
6
  per-payment cap, budget).
7
7
 
8
- Pin `@mysten-incubation/suipay-mcp@0.3.0-dev.35` in MCP config for the `latest` dist-tag.
8
+ Pin `@mysten-incubation/suipay-mcp@0.3.0-dev.36` in MCP config for the `latest` dist-tag.
9
9
  `npx -y @mysten-incubation/suipay-mcp@dev` tracks the `dev` prerelease line.
10
10
  `1.0.1` remains on the registry as a historical release; do not install it
11
11
  for new agents.
@@ -13,11 +13,11 @@ for new agents.
13
13
  ## Install
14
14
 
15
15
  ```bash
16
- claude mcp add --scope user suipay -- npx -y @mysten-incubation/suipay-mcp@0.3.0-dev.35
16
+ claude mcp add --scope user suipay -- npx -y @mysten-incubation/suipay-mcp@0.3.0-dev.36
17
17
  ```
18
18
 
19
19
  `@dev` installs the staging gateway/console defaults. A workspace
20
- checkout still defaults to localhost. `SUIPAY_GATEWAY_URL` and
20
+ checkout uses the local gateway at `http://127.0.0.1:4340`. `SUIPAY_GATEWAY_URL` and
21
21
  `SUIPAY_CONSOLE_URL` always override.
22
22
 
23
23
  No wallet secret belongs in this command or MCP config. There is no
@@ -159,12 +159,15 @@ Default is GKE **staging**. Start with `--local` for the laptop stack.
159
159
  | `dev` (default) | `https://suipay-staging.mystenlabs.com` | `https://suipay-gateway-staging.mystenlabs.com` | no flag, or `--dev` |
160
160
  | `local` | `http://localhost:3000` | `http://127.0.0.1:4340` | `--local` / `-local` |
161
161
 
162
+ Use `http://127.0.0.1:4340` for local paid resource URLs. Signed requests bind
163
+ the gateway origin, including the host spelling.
164
+
162
165
  ```bash
163
166
  # Staging (default)
164
- npx @mysten-incubation/suipay-mcp@0.3.0-dev.35
167
+ npx @mysten-incubation/suipay-mcp@0.3.0-dev.36
165
168
 
166
169
  # Laptop stack
167
- npx @mysten-incubation/suipay-mcp@0.3.0-dev.35 --local
170
+ npx @mysten-incubation/suipay-mcp@0.3.0-dev.36 --local
168
171
  ```
169
172
 
170
173
  `SUIPAY_MCP_TARGET=local|dev` selects the same preset. Explicit
@@ -1,10 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  main
4
- } from "../chunk-CHTRG5KH.js";
4
+ } from "../chunk-CEZ3NFAR.js";
5
5
  import {
6
6
  logError
7
- } from "../chunk-OBRKF6BI.js";
7
+ } from "../chunk-FUMH3XYC.js";
8
8
 
9
9
  // src/bin/suipay.ts
10
10
  main().catch((err) => {
@@ -5,7 +5,7 @@ import {
5
5
  loadMcpConfig,
6
6
  loadPaymentProfile,
7
7
  logError
8
- } from "./chunk-OBRKF6BI.js";
8
+ } from "./chunk-FUMH3XYC.js";
9
9
 
10
10
  // src/index.ts
11
11
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
@@ -1,5 +1,6 @@
1
1
  // src/http.ts
2
2
  import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
3
+ import { ErrorCode } from "@modelcontextprotocol/sdk/types.js";
3
4
 
4
5
  // src/server.ts
5
6
  import { Server } from "@modelcontextprotocol/sdk/server/index.js";
@@ -258,6 +259,19 @@ var ACCOUNT_CODES = {
258
259
  message: "This deposit would put your vault over the Mainnet Beta cap. Deposit less, or withdraw first."
259
260
  }
260
261
  },
262
+ "account.deposits_paused": {
263
+ surfaces: ["gateway", "sdk", "browser"],
264
+ status: 403,
265
+ title: "Deposits are paused",
266
+ paymentState: "not_charged",
267
+ retry: "after_delay",
268
+ retryAfterSeconds: 30,
269
+ nextAction: "retry_later",
270
+ user: {
271
+ title: "Deposits paused",
272
+ message: "New deposits are paused right now. Withdrawals and spending still work. Try again after deposits resume."
273
+ }
274
+ },
261
275
  "account.finalize_mismatch": {
262
276
  surfaces: ["gateway"],
263
277
  status: 409,
@@ -2328,7 +2342,7 @@ var SERVICE_CODES = {
2328
2342
  // Also `browser`: a directory page that only got a pass/fail boolean off
2329
2343
  // a server-side fetch restates this exact condition locally — the user
2330
2344
  // copy is equally true regardless of which layer noticed.
2331
- surfaces: ["gateway", "console_server", "mcp_hosted", "browser"],
2345
+ surfaces: ["gateway", "seller", "console_server", "mcp_hosted", "browser"],
2332
2346
  status: 503,
2333
2347
  title: "Service temporarily unavailable",
2334
2348
  paymentState: "not_charged",
@@ -3046,7 +3060,14 @@ function parseErrorPayload(input) {
3046
3060
  return null;
3047
3061
  }
3048
3062
  var DEFINITE_PRE_BROADCAST_REFUSALS = /* @__PURE__ */ new Set([
3049
- "auth.spend_not_whitelisted"
3063
+ "auth.spend_not_whitelisted",
3064
+ // Confirmed operator spend pause: gateway refuses before broadcast after
3065
+ // first-use bind or a chain_failed + ESpendPaused abort. Generic
3066
+ // `service.unavailable` stays out — session-revocation and other pre-check
3067
+ // paths can emit it after a lost execute may already have broadcast.
3068
+ "service.halted",
3069
+ // Confirmed operator deposit pause on dry-run / chain_failed + EDepositPaused.
3070
+ "account.deposits_paused"
3050
3071
  ]);
3051
3072
  function isValidatedProblemRefusal(parsed, allowedCodes) {
3052
3073
  return parsed !== null && parsed.source === "problem" && parsed.paymentState === "not_charged" && isErrorCode(parsed.code) && allowedCodes.has(parsed.code) && definitionOf(parsed.code).status === parsed.status;
@@ -3257,6 +3278,8 @@ var CONTEXT_ALLOWLIST = /* @__PURE__ */ new Set([
3257
3278
  "sessionDecision",
3258
3279
  "settleCode",
3259
3280
  "signedRequest",
3281
+ // ADR-0103: v1/v2 dual-accept drain counter on verified delegate/bootstrap lines.
3282
+ "protocolVersion",
3260
3283
  "signerCode",
3261
3284
  "consentCode",
3262
3285
  "publicReason",
@@ -5638,6 +5661,8 @@ function addressBalanceGasExpiration(input) {
5638
5661
  // ../sdk/dist/delegated-signer/pay-gas.js
5639
5662
  var DEFAULT_GAS_BUDGET = 10000000n;
5640
5663
  var DEFAULT_GAS_PRICE = 1000n;
5664
+ var MAX_SPONSOR_GAS_BUDGET = 50000000n;
5665
+ var MAX_SPONSOR_GAS_PRICE = 10000n;
5641
5666
  var X402_EXPIRATION_EPOCHS = 32n;
5642
5667
  async function readChainBound(read) {
5643
5668
  try {
@@ -5680,8 +5705,16 @@ function assertPayGas(data, delegate, policy = {}) {
5680
5705
  if (policy.mode === "agent") {
5681
5706
  if (!pinned)
5682
5707
  throw new Error("agent gas requires caller-owned gas inputs");
5683
- } else if (owner === agent) {
5684
- throw new Error("sponsored transaction gas owner must not be the delegate");
5708
+ } else {
5709
+ if (owner === agent) {
5710
+ throw new Error("sponsored transaction gas owner must not be the delegate");
5711
+ }
5712
+ if (actual.budget == null || actual.price == null) {
5713
+ throw new Error("sponsored transaction gas budget and price must be pinned");
5714
+ }
5715
+ if (BigInt(actual.budget) > MAX_SPONSOR_GAS_BUDGET || BigInt(actual.price) > MAX_SPONSOR_GAS_PRICE) {
5716
+ throw new Error("sponsored transaction gas budget or price exceeds the cap");
5717
+ }
5685
5718
  }
5686
5719
  if (pinned) {
5687
5720
  const expectedOwner = normalizeSuiAddress3(pinned.owner ?? delegate);
@@ -6564,6 +6597,8 @@ var X402_ERROR_REASON = {
6564
6597
  INSUFFICIENT_FUNDS: "insufficient_funds",
6565
6598
  PAYER_MISMATCH: "invalid_payload",
6566
6599
  SETTLEMENT_REJECTED: "invalid_transaction_state",
6600
+ SPEND_PAUSED: "unexpected_settle_error",
6601
+ SPEND_PAUSE_UNAVAILABLE: "unexpected_settle_error",
6567
6602
  SETTLEMENT_MISMATCH: "unexpected_settle_error",
6568
6603
  AMBIGUOUS: "settlement_pending",
6569
6604
  VERSION_UNSUPPORTED: "invalid_x402_version",
@@ -7913,6 +7948,12 @@ async function signSponsorPersonalMessagePayload(input) {
7913
7948
  return input.signPersonalMessage(encoded);
7914
7949
  }
7915
7950
 
7951
+ // ../sdk/dist/protocol/redirect.js
7952
+ var NO_REDIRECT = { redirect: "manual" };
7953
+ function isRedirectResponse(res) {
7954
+ return res.type === "opaqueredirect" || res.status >= 300 && res.status < 400;
7955
+ }
7956
+
7916
7957
  // ../sdk/dist/protocol/offer-keys.js
7917
7958
  var SUIPAY_OFFER_KEYS_PATH = "/.well-known/suipay-offer-keys.json";
7918
7959
  var DEFAULT_OFFER_KEY_CACHE_TTL_MS = 5 * 60 * 1e3;
@@ -7961,10 +8002,13 @@ async function fetchGatewayOfferKeys(gatewayUrl, options = {}) {
7961
8002
  const targetUrl = `${normalizedBase}${SUIPAY_OFFER_KEYS_PATH}`;
7962
8003
  let response;
7963
8004
  try {
7964
- response = await fetchImpl(targetUrl);
8005
+ response = await fetchImpl(targetUrl, NO_REDIRECT);
7965
8006
  } catch (err) {
7966
8007
  throw new OfferKeysFetchError(`failed to fetch gateway offer keys: ${err instanceof Error ? err.message : String(err)}`);
7967
8008
  }
8009
+ if (isRedirectResponse(response)) {
8010
+ throw new OfferKeysFetchError("failed to fetch gateway offer keys: redirect refused", response.status);
8011
+ }
7968
8012
  if (response.status === 404) {
7969
8013
  throw new OfferKeysGatewayUnavailableError();
7970
8014
  }
@@ -8066,6 +8110,29 @@ import { isValidPersonalMessageSignature as isValidPersonalMessageSignature2, ve
8066
8110
  import { normalizeSuiAddress as normalizeSuiAddress6 } from "@mysten/sui/utils";
8067
8111
  var SIGNED_REQUEST_DOMAIN = "suipay:signed-request:v1";
8068
8112
  var BOOTSTRAP_REQUEST_DOMAIN = "suipay:bootstrap-request:v1";
8113
+ var SIGNED_REQUEST_DOMAIN_V2 = "suipay:signed-request:v2";
8114
+ var BOOTSTRAP_REQUEST_DOMAIN_V2 = "suipay:bootstrap-request:v2";
8115
+ function canonicalOrigin(urlOrOrigin) {
8116
+ if (typeof urlOrOrigin !== "string" || urlOrOrigin.trim() === "") {
8117
+ throw new Error("origin must be a non-empty http(s) URL");
8118
+ }
8119
+ let url;
8120
+ try {
8121
+ url = new URL(urlOrOrigin.trim());
8122
+ } catch {
8123
+ throw new Error("origin must be an absolute http(s) URL");
8124
+ }
8125
+ if (url.protocol !== "https:" && url.protocol !== "http:") {
8126
+ throw new Error("origin must use http or https");
8127
+ }
8128
+ if (url.username !== "" || url.password !== "") {
8129
+ throw new Error("origin must not carry userinfo");
8130
+ }
8131
+ if (url.hostname === "" || url.origin === "null") {
8132
+ throw new Error("origin must name a host");
8133
+ }
8134
+ return url.origin;
8135
+ }
8069
8136
  var SIGNED_REQUEST_MAX_AGE_MS = 3e5;
8070
8137
  var SIGNED_REQUEST_MAX_FUTURE_SKEW_MS = 3e4;
8071
8138
  var SIGNED_REQUEST_NONCE_TTL_MS = SIGNED_REQUEST_MAX_AGE_MS + 2 * SIGNED_REQUEST_MAX_FUTURE_SKEW_MS;
@@ -8090,6 +8157,61 @@ function hexToBytes32(hex) {
8090
8157
  }
8091
8158
  return Uint8Array.from(Buffer.from(h, "hex"));
8092
8159
  }
8160
+ var utf8VecBytes = (s) => bcs4.vector(bcs4.u8()).serialize([...Buffer.from(s, "utf8")]).toBytes();
8161
+ var addressBytes = (a) => bcs4.Address.serialize(normalizeSuiAddress6(a)).toBytes();
8162
+ function assertCanonicalOrigin(origin) {
8163
+ if (typeof origin !== "string" || canonicalOrigin(origin) !== origin) {
8164
+ throw new Error("origin must be a canonical http(s) origin");
8165
+ }
8166
+ return origin;
8167
+ }
8168
+ function encodeSignedRequestV2(payload) {
8169
+ if (payload.domain !== SIGNED_REQUEST_DOMAIN_V2) {
8170
+ throw new Error(`domain must be ${SIGNED_REQUEST_DOMAIN_V2}`);
8171
+ }
8172
+ const origin = assertCanonicalOrigin(payload.origin);
8173
+ const parts = [
8174
+ utf8VecBytes(payload.domain),
8175
+ utf8VecBytes(payload.network),
8176
+ addressBytes(payload.packageId),
8177
+ utf8VecBytes(origin),
8178
+ addressBytes(payload.grantObjectId),
8179
+ addressBytes(payload.delegate),
8180
+ utf8VecBytes(payload.method),
8181
+ utf8VecBytes(payload.path),
8182
+ utf8VecBytes(payload.query),
8183
+ bcs4.vector(bcs4.u8()).serialize([...hexToBytes32(payload.bodyHash)]).toBytes(),
8184
+ bcs4.u64().serialize(BigInt(payload.timestampMs)).toBytes(),
8185
+ utf8VecBytes(payload.nonce)
8186
+ ];
8187
+ return Buffer.concat(parts.map((p) => Buffer.from(p)));
8188
+ }
8189
+ function encodeBootstrapRequestV2(payload) {
8190
+ if (payload.domain !== BOOTSTRAP_REQUEST_DOMAIN_V2) {
8191
+ throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN_V2}`);
8192
+ }
8193
+ const origin = assertCanonicalOrigin(payload.origin);
8194
+ const parts = [
8195
+ utf8VecBytes(payload.domain),
8196
+ utf8VecBytes(payload.network),
8197
+ addressBytes(payload.packageId),
8198
+ utf8VecBytes(origin),
8199
+ addressBytes(payload.delegate),
8200
+ utf8VecBytes(payload.method),
8201
+ utf8VecBytes(payload.path),
8202
+ utf8VecBytes(payload.query),
8203
+ bcs4.vector(bcs4.u8()).serialize([...hexToBytes32(payload.bodyHash)]).toBytes(),
8204
+ bcs4.u64().serialize(BigInt(payload.timestampMs)).toBytes(),
8205
+ utf8VecBytes(payload.nonce)
8206
+ ];
8207
+ return Buffer.concat(parts.map((p) => Buffer.from(p)));
8208
+ }
8209
+ function encodeAnySignedRequest(payload) {
8210
+ return payload.domain === SIGNED_REQUEST_DOMAIN_V2 ? encodeSignedRequestV2(payload) : encodeSignedRequest(payload);
8211
+ }
8212
+ function encodeAnyBootstrapRequest(payload) {
8213
+ return payload.domain === BOOTSTRAP_REQUEST_DOMAIN_V2 ? encodeBootstrapRequestV2(payload) : encodeBootstrapRequest(payload);
8214
+ }
8093
8215
  function encodeBootstrapRequest(payload) {
8094
8216
  if (payload.domain !== BOOTSTRAP_REQUEST_DOMAIN) {
8095
8217
  throw new Error(`domain must be ${BOOTSTRAP_REQUEST_DOMAIN}`);
@@ -8222,10 +8344,10 @@ function validateNonceFormat(nonce) {
8222
8344
  return bytes >= SIGNED_REQUEST_NONCE_MIN_ENTROPY_BYTES;
8223
8345
  }
8224
8346
  async function signSignedRequest(input) {
8225
- return input.signPersonalMessage(encodeSignedRequest(input.payload));
8347
+ return input.signPersonalMessage(encodeAnySignedRequest(input.payload));
8226
8348
  }
8227
8349
  async function signBootstrapRequest(input) {
8228
- return input.signPersonalMessage(encodeBootstrapRequest(input.payload));
8350
+ return input.signPersonalMessage(encodeAnyBootstrapRequest(input.payload));
8229
8351
  }
8230
8352
 
8231
8353
  // ../sdk/dist/agent-sdk/signed-headers.js
@@ -8251,6 +8373,17 @@ function splitPathAndQuery(target) {
8251
8373
  return { path: noFragment.slice(0, q), query: noFragment.slice(q + 1) };
8252
8374
  }
8253
8375
  }
8376
+ function assertTargetOrigin(url, signedOrigin) {
8377
+ let target;
8378
+ try {
8379
+ target = new URL(url);
8380
+ } catch {
8381
+ return;
8382
+ }
8383
+ if (canonicalOrigin(target.href) !== canonicalOrigin(signedOrigin)) {
8384
+ throw new Error("request URL origin does not match the signed origin");
8385
+ }
8386
+ }
8254
8387
  function buildSignedRequestPayload(context, request, fields) {
8255
8388
  if (!validateNonceFormat(fields.nonce)) {
8256
8389
  throw new Error("nonce must be base64url with at least 128 bits of entropy");
@@ -8259,9 +8392,10 @@ function buildSignedRequestPayload(context, request, fields) {
8259
8392
  throw new Error("timestampMs must be a positive integer (epoch ms)");
8260
8393
  }
8261
8394
  return {
8262
- domain: SIGNED_REQUEST_DOMAIN,
8395
+ domain: SIGNED_REQUEST_DOMAIN_V2,
8263
8396
  network: context.network,
8264
8397
  packageId: context.packageId,
8398
+ origin: canonicalOrigin(context.origin),
8265
8399
  grantObjectId: context.grantObjectId,
8266
8400
  delegate: context.delegateAddress,
8267
8401
  method: request.method.toUpperCase(),
@@ -8298,6 +8432,7 @@ async function signSessionRequest(input) {
8298
8432
  };
8299
8433
  }
8300
8434
  async function signSessionRequestForUrl(input) {
8435
+ assertTargetOrigin(input.url, input.context.origin);
8301
8436
  const { path, query } = splitPathAndQuery(input.url);
8302
8437
  return signSessionRequest({
8303
8438
  context: input.context,
@@ -8319,9 +8454,10 @@ function buildBootstrapRequestPayload(context, request, fields) {
8319
8454
  throw new Error("timestampMs must be a positive integer (epoch ms)");
8320
8455
  }
8321
8456
  return {
8322
- domain: BOOTSTRAP_REQUEST_DOMAIN,
8457
+ domain: BOOTSTRAP_REQUEST_DOMAIN_V2,
8323
8458
  network: context.network,
8324
8459
  packageId: context.packageId,
8460
+ origin: canonicalOrigin(context.origin),
8325
8461
  delegate: context.delegateAddress,
8326
8462
  method: request.method.toUpperCase(),
8327
8463
  path: canonicalizePath(request.path),
@@ -8357,6 +8493,7 @@ async function signBootstrapSessionRequest(input) {
8357
8493
  };
8358
8494
  }
8359
8495
  async function signBootstrapSessionRequestForUrl(input) {
8496
+ assertTargetOrigin(input.url, input.context.origin);
8360
8497
  const { path, query } = splitPathAndQuery(input.url);
8361
8498
  return signBootstrapSessionRequest({
8362
8499
  context: input.context,
@@ -8375,6 +8512,9 @@ async function signBootstrapSessionRequestForUrl(input) {
8375
8512
  function classifyReadFailure(status) {
8376
8513
  return status >= 500 ? "unavailable" : "rejected";
8377
8514
  }
8515
+ function redirectRefused() {
8516
+ return { ok: false, status: 0, error: "unavailable", code: "request.redirect_refused" };
8517
+ }
8378
8518
  function joinUrl(gatewayUrl, basePath, suffix) {
8379
8519
  const origin = gatewayUrl.replace(/\/$/, "");
8380
8520
  let base = basePath.replace(/\/$/, "");
@@ -8409,7 +8549,7 @@ function createReader(options) {
8409
8549
  let signed;
8410
8550
  try {
8411
8551
  signed = await signSessionRequestForUrl({
8412
- context: options.context,
8552
+ context: { ...options.context, origin: canonicalOrigin(options.gatewayUrl) },
8413
8553
  method: "GET",
8414
8554
  url,
8415
8555
  signPersonalMessage: options.signPersonalMessage,
@@ -8422,11 +8562,14 @@ function createReader(options) {
8422
8562
  try {
8423
8563
  res = await fetchImpl(url, {
8424
8564
  method: "GET",
8425
- headers: { ...signed.headers, accept: "application/json" }
8565
+ headers: { ...signed.headers, accept: "application/json" },
8566
+ ...NO_REDIRECT
8426
8567
  });
8427
8568
  } catch {
8428
8569
  return { ok: false, status: 0, error: "unavailable" };
8429
8570
  }
8571
+ if (isRedirectResponse(res))
8572
+ return redirectRefused();
8430
8573
  const body = await readJsonBody(res);
8431
8574
  if (res.status >= 200 && res.status < 300) {
8432
8575
  return { ok: true, status: res.status, data: body };
@@ -8521,7 +8664,7 @@ async function bootstrapPayerSessions(options) {
8521
8664
  let signed;
8522
8665
  try {
8523
8666
  signed = await signBootstrapSessionRequestForUrl({
8524
- context: options.context,
8667
+ context: { ...options.context, origin: canonicalOrigin(options.gatewayUrl) },
8525
8668
  method: "GET",
8526
8669
  url,
8527
8670
  signPersonalMessage: options.signPersonalMessage,
@@ -8534,11 +8677,14 @@ async function bootstrapPayerSessions(options) {
8534
8677
  try {
8535
8678
  res = await fetchImpl(url, {
8536
8679
  method: "GET",
8537
- headers: { ...signed.headers, accept: "application/json" }
8680
+ headers: { ...signed.headers, accept: "application/json" },
8681
+ ...NO_REDIRECT
8538
8682
  });
8539
8683
  } catch {
8540
8684
  return { ok: false, status: 0, error: "unavailable" };
8541
8685
  }
8686
+ if (isRedirectResponse(res))
8687
+ return redirectRefused();
8542
8688
  const body = await readJsonBody(res);
8543
8689
  if (res.status >= 200 && res.status < 300) {
8544
8690
  return { ok: true, status: res.status, data: body };
@@ -8835,9 +8981,29 @@ function gatewayFailure(answer, local, extras) {
8835
8981
  txDigest: error.txDigest ?? extras.txDigest
8836
8982
  });
8837
8983
  }
8838
- var PRE_SIGN_SPONSOR_CREATE_REFUSALS = /* @__PURE__ */ new Set([
8984
+ var PRE_SIGN_SPONSOR_REFUSALS = /* @__PURE__ */ new Set([
8839
8985
  ...DEFINITE_PRE_BROADCAST_REFUSALS,
8840
- "limit.rate_limited"
8986
+ "auth.spend_daily_limit_reached",
8987
+ // Unreadable pause / other pre-sign unavailability: safe on challenge and
8988
+ // sponsor create only. Execute keeps this ambiguous (see DEFINITE set).
8989
+ "service.unavailable",
8990
+ "limit.rate_limited",
8991
+ "limit.gas_quota_exceeded",
8992
+ "sponsor.would_abort",
8993
+ "sponsor.kind_rejected",
8994
+ "sponsor.target_not_allowed",
8995
+ "account.grant_revoked",
8996
+ "account.grant_paused",
8997
+ "account.grant_expired",
8998
+ "account.grant_not_active"
8999
+ ]);
9000
+ function isPreSignSponsorRefusal(parsed) {
9001
+ return isValidatedProblemRefusal(parsed, PRE_SIGN_SPONSOR_REFUSALS);
9002
+ }
9003
+ var BYO_SPONSOR_EXECUTE_PRE_BROADCAST_REFUSALS = /* @__PURE__ */ new Set([
9004
+ "auth.spend_daily_limit_reached",
9005
+ "sponsor.sponsorship_not_found",
9006
+ "sponsor.unavailable"
8841
9007
  ]);
8842
9008
  async function sponsorProblemRefusal(response, paymentId, admit) {
8843
9009
  const parsed = parseErrorPayload(await readGatewayAnswer(response));
@@ -9499,6 +9665,11 @@ async function payDelegatedSpendAccount(args) {
9499
9665
  detail: "the gateway could not be reached; nothing was signed"
9500
9666
  });
9501
9667
  }
9668
+ if (isRedirectResponse(first)) {
9669
+ return resultError("request.redirect_refused", "not_charged", {
9670
+ detail: "the gateway answered with a redirect; nothing was signed"
9671
+ });
9672
+ }
9502
9673
  if (first.status !== 402) {
9503
9674
  let body2;
9504
9675
  try {
@@ -9938,9 +10109,18 @@ async function payDelegatedSpendAccount(args) {
9938
10109
  grantId: resolved.grantObjectId,
9939
10110
  network: session.network,
9940
10111
  packageId: session.packageId
9941
- })
10112
+ }),
10113
+ ...NO_REDIRECT
9942
10114
  });
10115
+ if (isRedirectResponse(challengeRes)) {
10116
+ return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
10117
+ }
9943
10118
  if (!challengeRes.ok) {
10119
+ const refused = await sponsorProblemRefusal(challengeRes, paymentId, isPreSignSponsorRefusal);
10120
+ if (refused) {
10121
+ await releaseReservation(ledger, ownedPaymentId, log);
10122
+ return refused;
10123
+ }
9944
10124
  return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
9945
10125
  }
9946
10126
  const body2 = await challengeRes.json();
@@ -10008,10 +10188,14 @@ async function payDelegatedSpendAccount(args) {
10008
10188
  packageId: challenge.packageId,
10009
10189
  requestId: paymentId
10010
10190
  }
10011
- })
10191
+ }),
10192
+ ...NO_REDIRECT
10012
10193
  });
10194
+ if (isRedirectResponse(createRes)) {
10195
+ return abortBeforeSign("SPONSOR_UNAVAILABLE", PUBLIC_DETAIL.SPONSOR_UNAVAILABLE);
10196
+ }
10013
10197
  if (!createRes.ok) {
10014
- const refused = await sponsorProblemRefusal(createRes, paymentId, (parsed) => isValidatedProblemRefusal(parsed, PRE_SIGN_SPONSOR_CREATE_REFUSALS));
10198
+ const refused = await sponsorProblemRefusal(createRes, paymentId, isPreSignSponsorRefusal);
10015
10199
  if (refused) {
10016
10200
  await releaseReservation(ledger, ownedPaymentId, log);
10017
10201
  return refused;
@@ -10105,10 +10289,11 @@ async function payDelegatedSpendAccount(args) {
10105
10289
  signature,
10106
10290
  executeToken: sponsoredExecuteToken,
10107
10291
  ...sponsoredBackendToken ? { sponsorBackendToken: sponsoredBackendToken } : {}
10108
- })
10292
+ }),
10293
+ ...NO_REDIRECT
10109
10294
  });
10110
10295
  if (!execRes.ok) {
10111
- const refused = await sponsorProblemRefusal(execRes, paymentId, isDefinitePreBroadcastRefusal);
10296
+ const refused = isRedirectResponse(execRes) ? null : await sponsorProblemRefusal(execRes, paymentId, (parsed) => isDefinitePreBroadcastRefusal(parsed) || isValidatedProblemRefusal(parsed, BYO_SPONSOR_EXECUTE_PRE_BROADCAST_REFUSALS));
10112
10297
  if (refused) {
10113
10298
  await releaseReservation(ledger, ownedPaymentId, log);
10114
10299
  return refused;
@@ -10217,6 +10402,8 @@ async function payDelegatedSpendAccount(args) {
10217
10402
  let second;
10218
10403
  try {
10219
10404
  second = await fetchImpl(resourceUrl, paidRequestInit(request, { [MPP_CREDENTIAL_HEADER]: proof }));
10405
+ if (isRedirectResponse(second))
10406
+ throw new Error("proof presentation refused a redirect");
10220
10407
  } catch (err) {
10221
10408
  logInternal(log, { code: "client.gateway_unreachable", msg: "proof presentation failed" }, err);
10222
10409
  return completeAttempt(ledger, paymentId, ambiguous("PROOF_PRESENTATION_FAILED", PUBLIC_DETAIL.PROOF_PRESENTATION_FAILED, {
@@ -10398,6 +10585,9 @@ async function presentX402Credential(ctx, header) {
10398
10585
  let response;
10399
10586
  try {
10400
10587
  response = await ctx.fetchImpl(ctx.resourceUrl, paidRequestInit(ctx.request, { [X402_PAYMENT_HEADER]: header }));
10588
+ if (isRedirectResponse(response)) {
10589
+ throw new Error("x402 credential presentation refused a redirect");
10590
+ }
10401
10591
  } catch (err) {
10402
10592
  logInternal(ctx.deps.log, { code: "client.gateway_unreachable", msg: "x402 credential presentation failed" }, err);
10403
10593
  return { kind: "unresolved", txDigest };
@@ -10424,7 +10614,8 @@ async function presentX402Credential(ctx, header) {
10424
10614
  const settledReceipt = receipt && receipt.challengeId === ctx.offer.challengeId ? receipt : null;
10425
10615
  const pending = decoded !== null && isX402Failure(decoded) && decoded.errorReason === "settlement_pending";
10426
10616
  const answer = await readGatewayAnswer(response);
10427
- const stated = parseErrorPayload(answer)?.paymentState;
10617
+ const parsed = parseErrorPayload(answer);
10618
+ const stated = parsed?.paymentState;
10428
10619
  if (settledReceipt || pending || stated === "charged" || stated === "unknown") {
10429
10620
  return {
10430
10621
  kind: "undelivered",
@@ -10433,6 +10624,12 @@ async function presentX402Credential(ctx, header) {
10433
10624
  txDigest: settledReceipt?.txDigest ?? txDigest
10434
10625
  };
10435
10626
  }
10627
+ if (parsed?.source === "problem" && (parsed.code === "service.halted" || parsed.code === "service.unavailable") && answer.body.paymentState === "not_charged" && decoded && isX402Failure(decoded) && decoded.errorReason === "unexpected_settle_error") {
10628
+ txDigest = parsed.txDigest ?? txDigest;
10629
+ if (attempt === 1 && !txDigest)
10630
+ return { kind: "refused", answer };
10631
+ return { kind: "unresolved", txDigest };
10632
+ }
10436
10633
  if (attempt < attempts)
10437
10634
  await sleep(X402_PRESENT_DELAY_MS);
10438
10635
  }
@@ -10648,6 +10845,17 @@ function preparedSharedObjectId(input) {
10648
10845
  return null;
10649
10846
  }
10650
10847
  }
10848
+ function preparedMoveCallInput(data, args, position) {
10849
+ const index = preparedInputIndex(args[position]);
10850
+ return index === null ? void 0 : data.inputs?.[index];
10851
+ }
10852
+ function readPreparedSettlementPayment(data, args, accessMode) {
10853
+ return {
10854
+ poolObjectId: preparedSharedObjectId(preparedMoveCallInput(data, args, 2)),
10855
+ grantObjectId: preparedSharedObjectId(preparedMoveCallInput(data, args, 3)),
10856
+ amount: preparedPureU64(preparedMoveCallInput(data, args, accessMode === "open" ? 5 : 6))
10857
+ };
10858
+ }
10651
10859
  async function verifyPreparedSettlementKind(input) {
10652
10860
  const accessMode = input.expected.accessMode ?? "open";
10653
10861
  if (accessMode !== "scoped" && accessMode !== "open") {
@@ -10672,20 +10880,13 @@ async function verifyPreparedSettlementKind(input) {
10672
10880
  throw new Error(`prepared Move target is ${got}, expected ${wanted}`);
10673
10881
  }
10674
10882
  const args = cmd.MoveCall.arguments ?? [];
10675
- const inputs = data.inputs ?? [];
10676
- const resolve2 = (argIdx) => {
10677
- const idx = preparedInputIndex(args[argIdx]);
10678
- if (idx === null || idx < 0 || idx >= inputs.length)
10679
- return void 0;
10680
- return inputs[idx];
10681
- };
10682
- const poolObjectId = preparedSharedObjectId(resolve2(2));
10883
+ const resolve2 = (argIdx) => preparedMoveCallInput(data, args, argIdx);
10884
+ const { poolObjectId, grantObjectId, amount } = readPreparedSettlementPayment(data, args, accessMode);
10683
10885
  if (input.expected.poolObjectId) {
10684
10886
  if (!poolObjectId || !sameAddress2(poolObjectId, input.expected.poolObjectId)) {
10685
10887
  throw new Error(`prepared pool ${poolObjectId ?? "(missing)"} does not match expected pool ${input.expected.poolObjectId}`);
10686
10888
  }
10687
10889
  }
10688
- const grantObjectId = preparedSharedObjectId(resolve2(3));
10689
10890
  if (!grantObjectId) {
10690
10891
  throw new Error("prepared transaction does not name a grant object");
10691
10892
  }
@@ -10697,7 +10898,6 @@ async function verifyPreparedSettlementKind(input) {
10697
10898
  if (!recipient || !sameAddress2(recipient, input.expected.recipient)) {
10698
10899
  throw new Error(`prepared recipient ${recipient ?? "(missing)"} does not match the requested recipient`);
10699
10900
  }
10700
- const amount = preparedPureU64(resolve2(5));
10701
10901
  let expectedAmount;
10702
10902
  try {
10703
10903
  expectedAmount = BigInt(input.expected.amount);
@@ -10722,7 +10922,6 @@ async function verifyPreparedSettlementKind(input) {
10722
10922
  throw new Error("prepared target_hash does not match expected targetHash");
10723
10923
  }
10724
10924
  }
10725
- const amount = preparedPureU64(resolve2(6));
10726
10925
  let expectedAmount;
10727
10926
  try {
10728
10927
  expectedAmount = BigInt(input.expected.amount);
@@ -10938,8 +11137,10 @@ var MCP_TARGET_PRESETS = {
10938
11137
  gatewayUrl: MCP_DEV_GATEWAY_URL
10939
11138
  },
10940
11139
  local: {
10941
- consoleUrl: "https://suipay-staging.mystenlabs.com",
10942
- gatewayUrl: "http://127.0.0.1:4340"
11140
+ // Assemble so the npm release bake (string-replace of contiguous local
11141
+ // origins across bundled dist) cannot rewrite `--local` onto a hosted pair.
11142
+ consoleUrl: ["http://localhost", 3e3].join(":"),
11143
+ gatewayUrl: ["http://127.0.0.1", 4340].join(":")
10943
11144
  }
10944
11145
  };
10945
11146
  var PACKAGE_ID_ENV_NAMES = [
@@ -12570,7 +12771,8 @@ async function fetchGatewayDeployment(options) {
12570
12771
  try {
12571
12772
  res = await fetchImpl(`${origin}${base}/deployment`, {
12572
12773
  method: "GET",
12573
- headers: { accept: "application/json" }
12774
+ headers: { accept: "application/json" },
12775
+ ...NO_REDIRECT
12574
12776
  });
12575
12777
  } catch {
12576
12778
  return {
@@ -12578,6 +12780,12 @@ async function fetchGatewayDeployment(options) {
12578
12780
  error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, "gateway deployment identity could not be reached", "client.gateway_unreachable")
12579
12781
  };
12580
12782
  }
12783
+ if (isRedirectResponse(res)) {
12784
+ return {
12785
+ ok: false,
12786
+ error: manifestError(MANIFEST_ERROR_CODES.MALFORMED_MANIFEST, "gateway deployment identity refused a redirect", "request.redirect_refused")
12787
+ };
12788
+ }
12581
12789
  if (res.status < 200 || res.status >= 300) {
12582
12790
  return {
12583
12791
  ok: false,
@@ -13557,7 +13765,7 @@ function verifySpendAccountPayReconstructs(bytes, expected) {
13557
13765
  const auth = defaultAuthorityForRail("delegate", expected.packageId);
13558
13766
  const wanted = `${normalizeSuiAddress17(auth.packageId)}::${auth.module}::${auth.payFunction}`;
13559
13767
  const cmd = data.commands[0];
13560
- if (cmd.$kind !== "MoveCall" || !cmd.MoveCall) {
13768
+ if (cmd?.$kind !== "MoveCall") {
13561
13769
  throw new Error("sponsored transaction is not a MoveCall");
13562
13770
  }
13563
13771
  const got = `${normalizeSuiAddress17(String(cmd.MoveCall.package))}::${cmd.MoveCall.module}::${cmd.MoveCall.function}`;
@@ -13578,9 +13786,20 @@ function verifySpendAccountPayReconstructs(bytes, expected) {
13578
13786
  "sponsored transaction inputs do not match the intended payment (pool/grant/amount/target tampered)"
13579
13787
  );
13580
13788
  }
13581
- void expected.poolObjectId;
13582
- void expected.grantObjectId;
13583
- void expected.amount;
13789
+ const payment = readPreparedSettlementPayment(data, cmd.MoveCall.arguments, "scoped");
13790
+ if (payment.poolObjectId !== normalizeSuiAddress17(expected.poolObjectId)) {
13791
+ throw new Error("sponsored transaction pool object does not match the intended payment");
13792
+ }
13793
+ if (payment.grantObjectId !== normalizeSuiAddress17(expected.grantObjectId)) {
13794
+ throw new Error("sponsored transaction grant object does not match the intended payment");
13795
+ }
13796
+ if (payment.amount !== BigInt(expected.amount)) {
13797
+ throw new Error("sponsored transaction amount does not match the intended payment");
13798
+ }
13799
+ assertPayGas(data, expected.delegate, {
13800
+ mode: "sponsored",
13801
+ ...expected.expiration ? { expiration: expected.expiration } : {}
13802
+ });
13584
13803
  }
13585
13804
  async function prepareSpendAccountPayment(args) {
13586
13805
  const { session, cfg } = args;
@@ -14536,12 +14755,13 @@ async function delegateProofHeaders(resourceUrl, method, key, fetchImpl) {
14536
14755
  res = await fetchImpl(new URL("/v1/delegate-control/challenges", resourceUrl), {
14537
14756
  method: "POST",
14538
14757
  headers: { "content-type": "application/json" },
14539
- body: JSON.stringify({ delegateAddress: key.address })
14758
+ body: JSON.stringify({ delegateAddress: key.address }),
14759
+ ...NO_REDIRECT
14540
14760
  });
14541
14761
  } catch {
14542
14762
  return null;
14543
14763
  }
14544
- if (!res.ok)
14764
+ if (isRedirectResponse(res) || !res.ok)
14545
14765
  return null;
14546
14766
  let issued;
14547
14767
  try {
@@ -14592,12 +14812,12 @@ async function quote(resourceUrl, probeBody, options = {}) {
14592
14812
  try {
14593
14813
  res = await doFetch(resourceUrl, {
14594
14814
  ...probeInit(method, probeBody, proofHeaders),
14595
- redirect: "manual"
14815
+ ...NO_REDIRECT
14596
14816
  });
14597
14817
  } catch {
14598
14818
  throw refuse("client.gateway_unreachable", `cannot reach ${resourceUrl.host}`);
14599
14819
  }
14600
- if (res.type === "opaqueredirect" || res.status >= 300 && res.status < 400) {
14820
+ if (isRedirectResponse(res)) {
14601
14821
  throw refuse("request.redirect_refused", "quote refused a redirect");
14602
14822
  }
14603
14823
  if (res.status !== 402) {
@@ -14935,8 +15155,11 @@ async function pay(args, cfg, deps = {}) {
14935
15155
  if (!local) return mcpFailure("auth.login_required", AUTH_REQUIRED);
14936
15156
  return payStdioWithLocalKey({ request, intent, cfg, deps });
14937
15157
  }
14938
- function stdioGatewayUrl(cfg) {
14939
- return loadLocalSigningKeyRecord()?.gatewayUrl ?? cfg.gatewayUrl;
15158
+ function stdioGatewayUrl(cfg, storedUrl = loadLocalSigningKeyRecord()?.gatewayUrl) {
15159
+ if (storedUrl?.replace(/\/+$/, "") === "http://localhost:4340" && cfg.gatewayUrl.replace(/\/+$/, "") === MCP_TARGET_PRESETS.local.gatewayUrl) {
15160
+ return cfg.gatewayUrl;
15161
+ }
15162
+ return storedUrl ?? cfg.gatewayUrl;
14940
15163
  }
14941
15164
  function isExpiredBootstrapGrant(expiresAtMs, nowMs) {
14942
15165
  if (expiresAtMs === void 0 || expiresAtMs === null || expiresAtMs === "" || expiresAtMs === "0" || expiresAtMs === 0) {
@@ -15005,7 +15228,13 @@ async function payStdioWithLocalKey(args) {
15005
15228
  );
15006
15229
  }
15007
15230
  const resource = new URL(request.url);
15008
- if (resource.username || resource.password || !sameMcpGateway(resource.href, stdioGatewayUrl(cfg))) {
15231
+ const gatewayUrl = stdioGatewayUrl(cfg);
15232
+ let gatewayOrigin;
15233
+ try {
15234
+ gatewayOrigin = new URL(gatewayUrl).origin;
15235
+ } catch {
15236
+ }
15237
+ if (resource.username || resource.password || resource.origin !== gatewayOrigin) {
15009
15238
  return mcpFailure("account.policy_rejected", "pay URL must use the configured gateway; nothing was signed");
15010
15239
  }
15011
15240
  const built = await stdioPayerAndReader(cfg, deps);
@@ -15422,7 +15651,7 @@ async function suipayLogin(args, cfg, deps = {}) {
15422
15651
  }
15423
15652
  const endpoints = {
15424
15653
  consoleUrl: cfg.consoleUrl,
15425
- gatewayUrl: stored?.gatewayUrl ?? cfg.gatewayUrl
15654
+ gatewayUrl: stdioGatewayUrl(cfg, stored?.gatewayUrl ?? cfg.gatewayUrl)
15426
15655
  };
15427
15656
  if (local) {
15428
15657
  const live = await checkLiveDelegateGrant({
@@ -15447,7 +15676,7 @@ async function suipayLogin(args, cfg, deps = {}) {
15447
15676
  reused: true,
15448
15677
  target: target ?? cfg.target,
15449
15678
  delegateAddress: identity.delegateAddress,
15450
- gatewayUrl: loadLocalSigningKeyRecord()?.gatewayUrl ?? endpoints.gatewayUrl,
15679
+ gatewayUrl: endpoints.gatewayUrl,
15451
15680
  grantObjectId: live.grantObjectId,
15452
15681
  message: "Existing spend-account grant is live for this key. No browser round-trip."
15453
15682
  });
@@ -15548,8 +15777,7 @@ async function suipayLoginStatus(_args = {}, cfg, deps = {}) {
15548
15777
  });
15549
15778
  }
15550
15779
  const delegateAddress = keypair.toSuiAddress();
15551
- const stored = loadLocalSigningKeyRecord();
15552
- const gatewayUrl = stored?.gatewayUrl ?? cfg.gatewayUrl;
15780
+ const gatewayUrl = stdioGatewayUrl(cfg);
15553
15781
  const cacheKey = `${gatewayUrl}:${delegateAddress}`;
15554
15782
  const now = Date.now();
15555
15783
  const cacheTtlMs = deps.cacheTtlMs ?? DEFAULT_LOGIN_STATUS_CACHE_TTL_MS;
@@ -15931,7 +16159,7 @@ var EMPTY_ENVELOPE = {
15931
16159
  requestId: null,
15932
16160
  clientName: null
15933
16161
  };
15934
- var DEFAULT_MAX_OBSERVED_BYTES = 64 * 1024;
16162
+ var DEFAULT_MAX_OBSERVED_BYTES = 1024 * 1024;
15935
16163
  var DEFAULT_RUN_SETUP_TIMEOUT_MS = 500;
15936
16164
  function canonicalMcpRequestId(id) {
15937
16165
  if (typeof id === "number") {
@@ -16382,7 +16610,41 @@ async function traceMcpHttpRequest(input) {
16382
16610
  }
16383
16611
 
16384
16612
  // src/http.ts
16613
+ async function countMcpToolCalls(req) {
16614
+ if (req.method !== "POST") return 0;
16615
+ let text2;
16616
+ try {
16617
+ text2 = await req.clone().text();
16618
+ } catch {
16619
+ return 0;
16620
+ }
16621
+ let parsed;
16622
+ try {
16623
+ parsed = JSON.parse(text2);
16624
+ } catch {
16625
+ return 0;
16626
+ }
16627
+ const messages = Array.isArray(parsed) ? parsed : [parsed];
16628
+ let count = 0;
16629
+ for (const message of messages) {
16630
+ if (message && typeof message === "object" && message.method === "tools/call") {
16631
+ count += 1;
16632
+ }
16633
+ }
16634
+ return count;
16635
+ }
16636
+ function tooManyToolCalls() {
16637
+ return new Response(
16638
+ JSON.stringify({
16639
+ jsonrpc: "2.0",
16640
+ id: null,
16641
+ error: { code: ErrorCode.InvalidRequest, message: "a request may contain at most one tools/call" }
16642
+ }),
16643
+ { status: 400, headers: { "content-type": "application/json" } }
16644
+ );
16645
+ }
16385
16646
  async function handleSuipayMcpHttpRequest(req, cfg, auth, trace, options) {
16647
+ if (await countMcpToolCalls(req) > 1) return tooManyToolCalls();
16386
16648
  return traceMcpHttpRequest({
16387
16649
  request: req,
16388
16650
  runtime: trace ?? null,
@@ -16427,5 +16689,7 @@ export {
16427
16689
  canonicalMcpRequestId,
16428
16690
  inspectMcpEnvelope,
16429
16691
  traceMcpHttpRequest,
16692
+ countMcpToolCalls,
16693
+ tooManyToolCalls,
16430
16694
  handleSuipayMcpHttpRequest
16431
16695
  };
@@ -649,7 +649,7 @@ interface DelegatePoliciesDTO {
649
649
  * Agent signing helper — emit the four `x-suipay-*` signed-request headers.
650
650
  *
651
651
  * A delegate agent proves identity on every private, grant-scoped request by
652
- * signing the canonical `SignedRequestV1` payload with a Sui personal-message
652
+ * signing the canonical `SignedRequestV2` payload with a Sui personal-message
653
653
  * signature. This helper is the client-side counterpart to the gateway verifier:
654
654
  * it canonicalizes the path/query and hashes the body EXACTLY as the verifier
655
655
  * will (reusing the P0 codec's `canonicalizePath` / `canonicalizeQuery` /
@@ -661,24 +661,30 @@ interface DelegatePoliciesDTO {
661
661
  * bound via {@link personalMessageSigner}). Money never moves on this signature;
662
662
  * it authorizes only the grant-scoped reads the epic defines.
663
663
  *
664
- * Byte-for-byte parity with P0 is locked by the golden vector in
665
- * `tests/agent-sdk-signed-headers.test.ts`, which reproduces the exact
666
- * signature the cross-language vector (`tests/parity/signed-request-golden.test.ts`)
667
- * pins.
664
+ * The signed bytes are pinned by the v2 vector in
665
+ * `tests/agent-sdk-signed-headers.test.ts`, built from the same field values
666
+ * as the v1 cross-language vector (`tests/parity/signed-request-golden.test.ts`).
668
667
  */
669
668
 
670
669
  /** Sui personal-message signer: returns the serialized signature (base64). */
671
670
  type SignPersonalMessage = (message: Uint8Array) => Promise<string>;
672
671
  /**
673
- * The deployment + grant identity every signed request binds. `network` and
674
- * `packageId` MUST equal the gateway's server-authoritative config; `delegate`
675
- * MUST equal the grant's registered on-chain delegate (the signer's address).
672
+ * The deployment + grant identity every signed request binds. `network`,
673
+ * `packageId`, and `origin` MUST equal the gateway's server-authoritative
674
+ * config; `delegate` MUST equal the grant's registered on-chain delegate (the
675
+ * signer's address).
676
676
  */
677
677
  interface SessionSignerContext {
678
678
  /** e.g. `sui:testnet` — must equal the gateway config. */
679
679
  network: string;
680
680
  /** Deployed package id — must equal the gateway config. */
681
681
  packageId: string;
682
+ /**
683
+ * The gateway the request is sent to — any http(s) URL on it; only its
684
+ * {@link canonicalOrigin} is signed. Must equal the gateway's configured base
685
+ * URL origin, so the signature cannot be replayed at another gateway.
686
+ */
687
+ origin: string;
682
688
  /** On-chain grant object id — the authorization scope. */
683
689
  grantObjectId: string;
684
690
  /** Registered delegate Sui address (the signer). */
@@ -748,8 +754,11 @@ type PayerReadResult<T> = {
748
754
  interface PayerReadClientOptions {
749
755
  /** Gateway origin, e.g. `https://gateway.suipay.dev` (no trailing slash needed). */
750
756
  gatewayUrl: string;
751
- /** Deployment + grant identity every signed read binds. */
752
- context: SessionSignerContext;
757
+ /**
758
+ * Deployment + grant identity every signed read binds. The signed origin is
759
+ * always `gatewayUrl`'s: a read binds the gateway it is sent to.
760
+ */
761
+ context: Omit<SessionSignerContext, 'origin'>;
753
762
  /** Local personal-message signer; the key never leaves it. */
754
763
  signPersonalMessage: SignPersonalMessage;
755
764
  /** Injectable fetch (tests / custom transports). Defaults to global `fetch`. */
@@ -781,6 +790,12 @@ declare function createReader(options: PayerReadClientOptions): PayerReadClient;
781
790
  */
782
791
  type GetObjectJson = (objectId: string) => Promise<Record<string, unknown> | null | undefined>;
783
792
 
793
+ interface PayExpirationPolicy {
794
+ currentEpoch: bigint;
795
+ chainIdentifier?: string;
796
+ requireBounded?: boolean;
797
+ }
798
+
784
799
  interface OfferJWK {
785
800
  kty: 'OKP' | string;
786
801
  crv?: 'Ed25519' | string;
@@ -1245,7 +1260,7 @@ declare const ERRORS: {
1245
1260
  };
1246
1261
  };
1247
1262
  readonly 'service.unavailable': {
1248
- readonly surfaces: readonly ["gateway", "console_server", "mcp_hosted", "browser"];
1263
+ readonly surfaces: readonly ["gateway", "seller", "console_server", "mcp_hosted", "browser"];
1249
1264
  readonly status: 503;
1250
1265
  readonly title: "Service temporarily unavailable";
1251
1266
  readonly paymentState: "not_charged";
@@ -2526,6 +2541,19 @@ declare const ERRORS: {
2526
2541
  readonly message: "This deposit would put your vault over the Mainnet Beta cap. Deposit less, or withdraw first.";
2527
2542
  };
2528
2543
  };
2544
+ readonly 'account.deposits_paused': {
2545
+ readonly surfaces: readonly ["gateway", "sdk", "browser"];
2546
+ readonly status: 403;
2547
+ readonly title: "Deposits are paused";
2548
+ readonly paymentState: "not_charged";
2549
+ readonly retry: "after_delay";
2550
+ readonly retryAfterSeconds: 30;
2551
+ readonly nextAction: "retry_later";
2552
+ readonly user: {
2553
+ readonly title: "Deposits paused";
2554
+ readonly message: "New deposits are paused right now. Withdrawals and spending still work. Try again after deposits resume.";
2555
+ };
2556
+ };
2529
2557
  readonly 'account.finalize_mismatch': {
2530
2558
  readonly surfaces: readonly ["gateway"];
2531
2559
  readonly status: 409;
@@ -4897,6 +4925,8 @@ declare function verifySpendAccountPayReconstructs(bytes: string, expected: {
4897
4925
  poolObjectId: string;
4898
4926
  grantObjectId: string;
4899
4927
  amount: string;
4928
+ /** Trusted epoch bound; without it only a coin-gas transaction with no expiration passes. */
4929
+ expiration?: PayExpirationPolicy;
4900
4930
  }): void;
4901
4931
  /**
4902
4932
  * Prepare a delegate payment WITHOUT signing. Reads the 402 offer, binds it,
@@ -5094,6 +5124,16 @@ declare function createServer(cfg: McpConfig, auth?: McpAuthContext, trace?: Mcp
5094
5124
  * Handle one MCP Streamable HTTP request (initialize, tools/list, tools/call, …).
5095
5125
  * Creates a fresh transport+server pair per request (stateless mode).
5096
5126
  */
5127
+ /**
5128
+ * How many `tools/call` messages this request contains.
5129
+ *
5130
+ * Clones the body, so the transport can still read it. A body that is not
5131
+ * JSON counts as zero and the transport answers the parse error. The read is
5132
+ * not capped: a truncated read would report zero and let a large batch through.
5133
+ */
5134
+ declare function countMcpToolCalls(req: Request): Promise<number>;
5135
+ /** JSON-RPC Invalid Request (-32600). A batch of tool calls is not one metered call. */
5136
+ declare function tooManyToolCalls(): Response;
5097
5137
  declare function handleSuipayMcpHttpRequest(req: Request, cfg: McpConfig, auth?: McpAuthContext, trace?: McpTraceRuntime | null, options?: McpServerOptions): Promise<Response>;
5098
5138
 
5099
- export { type AgentHeldResolver as A, type SpendAccountPrepareSession as B, type CodeFor as C, type DelegatedKeySigner as D, buildSpendAccountPayKind as E, canonicalMcpRequestId as F, type GetObjectJson as G, createServer as H, handleSuipayMcpHttpRequest as I, inspectMcpEnvelope as J, loadMcpConfig as K, parseMcpTargetFlag as L, type McpConfig as M, type NextAction as N, type OfferPublicKeySource as O, type PaidHttpRequest as P, prepareSpendAccountPayment as Q, resetAgentHeldProcessLedger as R, type SpendAccountSigningRequest as S, TOOLS as T, resolveAgentHeldSettlement as U, resolveGrantTarget as V, resolveMcpTarget as W, type X402PayProgress as X, sameMcpGateway as Y, traceMcpHttpRequest as Z, verifySpendAccountPayReconstructs as _, type DelegatedPayerSession as a, type DelegatedPayerConfig as b, type DelegatedPayerDeps as c, type SpendIntent as d, type DelegatedPayResult as e, type DelegationScope as f, type GrantPolicyBinding as g, type PaymentAttemptLedger as h, type DelegatedPayerLog as i, type PreparedSettlementTerms as j, type Offer as k, type McpAuthContext as l, type McpTraceHooks as m, type SpendAccountPayDeps as n, createReader as o, type AgentHeldSettlement as p, MCP_TARGET_PRESETS as q, type McpEnvelope as r, type McpEnvelopeEntry as s, type McpServerOptions as t, type McpTarget as u, type McpTraceContext as v, type McpTraceRuntime as w, PACKAGE_NAME as x, type PreparedPayment as y, type SpendAccountPrepareResult as z };
5139
+ export { verifySpendAccountPayReconstructs as $, type AgentHeldResolver as A, type SpendAccountPrepareSession as B, type CodeFor as C, type DelegatedKeySigner as D, buildSpendAccountPayKind as E, canonicalMcpRequestId as F, type GetObjectJson as G, countMcpToolCalls as H, createServer as I, handleSuipayMcpHttpRequest as J, inspectMcpEnvelope as K, loadMcpConfig as L, type McpConfig as M, type NextAction as N, type OfferPublicKeySource as O, type PaidHttpRequest as P, parseMcpTargetFlag as Q, prepareSpendAccountPayment as R, type SpendAccountSigningRequest as S, TOOLS as T, resetAgentHeldProcessLedger as U, resolveAgentHeldSettlement as V, resolveGrantTarget as W, type X402PayProgress as X, resolveMcpTarget as Y, sameMcpGateway as Z, traceMcpHttpRequest as _, type DelegatedPayerSession as a, tooManyToolCalls as a0, type DelegatedPayerConfig as b, type DelegatedPayerDeps as c, type SpendIntent as d, type DelegatedPayResult as e, type DelegationScope as f, type GrantPolicyBinding as g, type PaymentAttemptLedger as h, type DelegatedPayerLog as i, type PreparedSettlementTerms as j, type Offer as k, type McpAuthContext as l, type McpTraceHooks as m, type SpendAccountPayDeps as n, createReader as o, type AgentHeldSettlement as p, MCP_TARGET_PRESETS as q, type McpEnvelope as r, type McpEnvelopeEntry as s, type McpServerOptions as t, type McpTarget as u, type McpTraceContext as v, type McpTraceRuntime as w, PACKAGE_NAME as x, type PreparedPayment as y, type SpendAccountPrepareResult as z };
package/dist/http.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { I as handleSuipayMcpHttpRequest } from './http-fypqfnVw.js';
1
+ export { H as countMcpToolCalls, J as handleSuipayMcpHttpRequest, a0 as tooManyToolCalls } from './http-BwtYzkbN.js';
2
2
  import '@modelcontextprotocol/sdk/server/index.js';
3
3
  import '@mysten/sui/keypairs/ed25519';
4
4
  import 'node:crypto';
package/dist/http.js CHANGED
@@ -1,6 +1,10 @@
1
1
  import {
2
- handleSuipayMcpHttpRequest
3
- } from "./chunk-OBRKF6BI.js";
2
+ countMcpToolCalls,
3
+ handleSuipayMcpHttpRequest,
4
+ tooManyToolCalls
5
+ } from "./chunk-FUMH3XYC.js";
4
6
  export {
5
- handleSuipayMcpHttpRequest
7
+ countMcpToolCalls,
8
+ handleSuipayMcpHttpRequest,
9
+ tooManyToolCalls
6
10
  };
package/dist/index.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Ed25519Keypair } from '@mysten/sui/keypairs/ed25519';
2
- import { S as SpendAccountSigningRequest, P as PaidHttpRequest, D as DelegatedKeySigner, G as GetObjectJson, a as DelegatedPayerSession, b as DelegatedPayerConfig, c as DelegatedPayerDeps, d as SpendIntent, e as DelegatedPayResult, f as DelegationScope, C as CodeFor, N as NextAction, g as GrantPolicyBinding, h as PaymentAttemptLedger, O as OfferPublicKeySource, i as DelegatedPayerLog, j as PreparedSettlementTerms, X as X402PayProgress, k as Offer, M as McpConfig, l as McpAuthContext, m as McpTraceHooks, n as SpendAccountPayDeps, o as createReader } from './http-fypqfnVw.js';
3
- export { A as AgentHeldResolver, p as AgentHeldSettlement, q as MCP_TARGET_PRESETS, r as McpEnvelope, s as McpEnvelopeEntry, t as McpServerOptions, u as McpTarget, v as McpTraceContext, w as McpTraceRuntime, x as PACKAGE_NAME, y as PreparedPayment, z as SpendAccountPrepareResult, B as SpendAccountPrepareSession, T as TOOLS, E as buildSpendAccountPayKind, F as canonicalMcpRequestId, H as createServer, I as handleSuipayMcpHttpRequest, J as inspectMcpEnvelope, K as loadMcpConfig, L as parseMcpTargetFlag, Q as prepareSpendAccountPayment, R as resetAgentHeldProcessLedger, U as resolveAgentHeldSettlement, V as resolveGrantTarget, W as resolveMcpTarget, Y as sameMcpGateway, Z as traceMcpHttpRequest, _ as verifySpendAccountPayReconstructs } from './http-fypqfnVw.js';
2
+ import { S as SpendAccountSigningRequest, P as PaidHttpRequest, D as DelegatedKeySigner, G as GetObjectJson, a as DelegatedPayerSession, b as DelegatedPayerConfig, c as DelegatedPayerDeps, d as SpendIntent, e as DelegatedPayResult, f as DelegationScope, C as CodeFor, N as NextAction, g as GrantPolicyBinding, h as PaymentAttemptLedger, O as OfferPublicKeySource, i as DelegatedPayerLog, j as PreparedSettlementTerms, X as X402PayProgress, k as Offer, M as McpConfig, l as McpAuthContext, m as McpTraceHooks, n as SpendAccountPayDeps, o as createReader } from './http-BwtYzkbN.js';
3
+ export { A as AgentHeldResolver, p as AgentHeldSettlement, q as MCP_TARGET_PRESETS, r as McpEnvelope, s as McpEnvelopeEntry, t as McpServerOptions, u as McpTarget, v as McpTraceContext, w as McpTraceRuntime, x as PACKAGE_NAME, y as PreparedPayment, z as SpendAccountPrepareResult, B as SpendAccountPrepareSession, T as TOOLS, E as buildSpendAccountPayKind, F as canonicalMcpRequestId, H as countMcpToolCalls, I as createServer, J as handleSuipayMcpHttpRequest, K as inspectMcpEnvelope, L as loadMcpConfig, Q as parseMcpTargetFlag, R as prepareSpendAccountPayment, U as resetAgentHeldProcessLedger, V as resolveAgentHeldSettlement, W as resolveGrantTarget, Y as resolveMcpTarget, Z as sameMcpGateway, _ as traceMcpHttpRequest, $ as verifySpendAccountPayReconstructs } from './http-BwtYzkbN.js';
4
4
  import { SuiGrpcClient } from '@mysten/sui/grpc';
5
5
  import { CallToolResult } from '@modelcontextprotocol/sdk/types.js';
6
6
  import '@modelcontextprotocol/sdk/server/index.js';
package/dist/index.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import {
2
2
  loadBootProfile,
3
3
  main
4
- } from "./chunk-CHTRG5KH.js";
4
+ } from "./chunk-CEZ3NFAR.js";
5
5
  import {
6
6
  MCP_TARGET_PRESETS,
7
7
  PACKAGE_NAME,
8
8
  TOOLS,
9
9
  buildSpendAccountPayKind,
10
10
  canonicalMcpRequestId,
11
+ countMcpToolCalls,
11
12
  createServer,
12
13
  ensureLocalSigningKey,
13
14
  handleSuipayMcpHttpRequest,
@@ -26,13 +27,14 @@ import {
26
27
  settlePreparedMcpPayment,
27
28
  traceMcpHttpRequest,
28
29
  verifySpendAccountPayReconstructs
29
- } from "./chunk-OBRKF6BI.js";
30
+ } from "./chunk-FUMH3XYC.js";
30
31
  export {
31
32
  MCP_TARGET_PRESETS,
32
33
  PACKAGE_NAME,
33
34
  TOOLS,
34
35
  buildSpendAccountPayKind,
35
36
  canonicalMcpRequestId,
37
+ countMcpToolCalls,
36
38
  createServer,
37
39
  ensureLocalSigningKey,
38
40
  handleSuipayMcpHttpRequest,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mysten-incubation/suipay-mcp",
3
- "version": "0.3.0-dev.35",
3
+ "version": "0.3.0-dev.36",
4
4
  "type": "module",
5
5
  "description": "SuiPay MCP — pay MPP-gated APIs from a spend-account grant with an agent-held delegate key.",
6
6
  "repository": {
@@ -42,8 +42,8 @@
42
42
  "tsup": "^8.0.0",
43
43
  "typescript": "^6.0.3",
44
44
  "vitest": "^4.1.10",
45
- "@cmdoss/suipay-sdk": "0.1.0",
46
- "@cmdoss/suipay-core": "0.1.0"
45
+ "@cmdoss/suipay-core": "0.1.0",
46
+ "@cmdoss/suipay-sdk": "0.1.0"
47
47
  },
48
48
  "scripts": {
49
49
  "build": "tsup",