@sakupa/mcp 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/bin.js +134 -207
  2. package/dist/index.js +186 -259
  3. package/package.json +1 -1
package/dist/bin.js CHANGED
@@ -136,11 +136,11 @@ var HTTP_STATUS = {
136
136
  conflict: 409,
137
137
  state_conflict: 409,
138
138
  rate_limited: 429,
139
- insufficient_balance: 402,
140
139
  payment_required: 402,
141
140
  confirmation_required: 428,
142
141
  dns_not_verified: 403,
143
142
  not_deployable: 422,
143
+ upgrade_required: 426,
144
144
  internal: 500
145
145
  };
146
146
  var SakupaError = class extends Error {
@@ -450,11 +450,12 @@ async function sha256Hex(bytes) {
450
450
  }
451
451
 
452
452
  // ../core/dist/domain/subscription.js
453
- var SUBSCRIPTION_WARNING_TEXT = "You are subscribing {billingDomain} to Sakupa Domain Hosting: the {plan} monthly plan (\xA5{priceJpy}/month).\n\nPaying does not prove that you own this domain, does not grant management rights, and does not by itself publish a website: the domain must still pass DNS ownership verification.\n\nIf this site outgrows its plan, Sakupa automatically upgrades the subscription to the next plan (water -> personal -> share -> business) and renewals bill the new plan. There is no metered overage: above the Business plan, growth is limited instead of billed further.\n\nYou can cancel anytime; hosting then runs to the end of the already-paid month and stops.";
453
+ var SUBSCRIPTION_WARNING_TEXT = "You are subscribing this site ({siteUrl}) to Sakupa Hosting: the {plan} monthly plan (\xA5{priceJpy}/month).\n\nPaying makes THIS site permanent on its {siteUrl} address \u2014 it stops expiring. Binding a custom domain afterwards is an optional included extra: it requires proving DNS control of that domain, and whether or not you ever bind one does not change the subscription or qualify for a refund.\n\nIf this site outgrows its plan, Sakupa automatically upgrades the subscription to the next plan (water -> personal -> share -> business) and renewals bill the new plan. There is no metered overage: above the Business plan, growth is limited instead of billed further.\n\nYou can cancel anytime; when the subscription ends, the site immediately becomes a free temporary site again (24h validity) and all paid data \u2014 custom domain bindings included \u2014 is removed.";
454
454
 
455
455
  // ../core/dist/dto.js
456
456
  var CREDENTIAL_HEADER = "x-sakupa-credential";
457
457
  var IDEMPOTENCY_HEADER = "x-sakupa-idempotency-key";
458
+ var MCP_VERSION_HEADER = "x-sakupa-mcp-version";
458
459
 
459
460
  // ../core/dist/services/sites.js
460
461
  var utf8Decoder = new TextDecoder("utf-8", { fatal: false });
@@ -473,11 +474,11 @@ var KNOWN_ERROR_CODES = /* @__PURE__ */ new Set([
473
474
  "conflict",
474
475
  "state_conflict",
475
476
  "rate_limited",
476
- "insufficient_balance",
477
477
  "payment_required",
478
478
  "confirmation_required",
479
479
  "dns_not_verified",
480
480
  "not_deployable",
481
+ "upgrade_required",
481
482
  "internal"
482
483
  ]);
483
484
  var HttpApiClient = class {
@@ -578,14 +579,7 @@ var HttpApiClient = class {
578
579
  { body: req }
579
580
  );
580
581
  }
581
- /** Wallet-era recharge checkout; unused (kept for SakupaApiClient compatibility). */
582
- async createCheckout(req) {
583
- return this.call("POST", "/v1/payments/checkout", {
584
- body: req,
585
- idempotencyKey: req.idempotencyKey
586
- });
587
- }
588
- /** Subscription checkout: a fixed monthly plan for one apex domain (owner-only). */
582
+ /** Subscription checkout: a fixed monthly plan permanentizing one site (owner-only). */
589
583
  async createPlanCheckout(req, credential) {
590
584
  return this.call("POST", "/v1/payments/checkout", {
591
585
  credential,
@@ -594,31 +588,24 @@ var HttpApiClient = class {
594
588
  });
595
589
  }
596
590
  /** Stripe-hosted billing portal (payment method, invoices, cancellation). */
597
- async createBillingPortal(apexDomain, credential) {
591
+ async createBillingPortal(siteId, credential) {
598
592
  return this.call(
599
593
  "POST",
600
- `/v1/billing/${encodeURIComponent(apexDomain)}/portal`,
594
+ `/v1/sites/${encodeURIComponent(siteId)}/billing/portal`,
601
595
  { credential, body: {} }
602
596
  );
603
597
  }
604
- async getBillingStatus(apexDomain, credential) {
598
+ async getBillingStatus(siteId, credential) {
605
599
  return this.call(
606
600
  "GET",
607
- `/v1/billing/${encodeURIComponent(apexDomain)}`,
608
- credential !== void 0 ? { credential } : {}
609
- );
610
- }
611
- async setBillingPlan(apexDomain, credential, req) {
612
- return this.call(
613
- "POST",
614
- `/v1/billing/${encodeURIComponent(apexDomain)}/plan`,
615
- { credential, body: req }
601
+ `/v1/sites/${encodeURIComponent(siteId)}/billing`,
602
+ { credential }
616
603
  );
617
604
  }
618
- async downgradeSite(siteId, credential, req) {
605
+ async setBillingPlan(siteId, credential, req) {
619
606
  return this.call(
620
607
  "POST",
621
- `/v1/sites/${encodeURIComponent(siteId)}/downgrade`,
608
+ `/v1/sites/${encodeURIComponent(siteId)}/billing/plan`,
622
609
  { credential, body: req }
623
610
  );
624
611
  }
@@ -1070,7 +1057,7 @@ async function analyzeProject(projectDir, opts = {}) {
1070
1057
 
1071
1058
  // src/project-file.ts
1072
1059
  import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
1073
- import { join as join2 } from "node:path";
1060
+ import { dirname, join as join2 } from "node:path";
1074
1061
  var SITE_DIR = ".sakupa";
1075
1062
  var SITE_FILE = "site.json";
1076
1063
  function siteFilePath(projectDir) {
@@ -1096,8 +1083,7 @@ function readSiteFile(projectDir) {
1096
1083
  apiBaseUrl: typeof parsed.apiBaseUrl === "string" ? parsed.apiBaseUrl : "",
1097
1084
  ...typeof parsed.shortId === "string" ? { shortId: parsed.shortId } : {},
1098
1085
  ...typeof parsed.url === "string" ? { url: parsed.url } : {},
1099
- ...typeof parsed.billingDomain === "string" ? { billingDomain: parsed.billingDomain } : {},
1100
- ...typeof parsed.billingDomainId === "string" ? { billingDomainId: parsed.billingDomainId } : {}
1086
+ ...typeof parsed.boundDomain === "string" ? { boundDomain: parsed.boundDomain } : {}
1101
1087
  };
1102
1088
  } catch {
1103
1089
  return null;
@@ -1114,9 +1100,22 @@ function writeSiteFile(projectDir, file) {
1114
1100
  } catch {
1115
1101
  }
1116
1102
  }
1103
+ function isInsideGitRepo(projectDir) {
1104
+ let dir = projectDir;
1105
+ for (; ; ) {
1106
+ if (existsSync(join2(dir, ".git"))) return true;
1107
+ const parent = dirname(dir);
1108
+ if (parent === dir) return false;
1109
+ dir = parent;
1110
+ }
1111
+ }
1112
+ function credentialGitReminder(projectDir) {
1113
+ if (!isInsideGitRepo(projectDir)) return "";
1114
+ return '\nNOTE: this project is inside a git repository. The management credential in .sakupa/site.json is the key to this site \u2014 do NOT commit it to a PUBLIC repository (add ".sakupa/" to .gitignore yourself if you want to keep it out of version control).';
1115
+ }
1117
1116
 
1118
1117
  // src/version.ts
1119
- var MCP_VERSION = "0.1.0";
1118
+ var MCP_VERSION = "0.4.0";
1120
1119
  var CLIENT_TYPE = "sakupa-mcp";
1121
1120
 
1122
1121
  // src/tools/context.ts
@@ -1156,8 +1155,8 @@ var severityEnum = z.enum(["low", "medium", "high", "critical"]);
1156
1155
  function planCatalog() {
1157
1156
  return TIER_ORDER.map((p) => `${p} \xA5${tierPriceJpy(p)}/month`).join(", ");
1158
1157
  }
1159
- function subscriptionWarning(domain, plan) {
1160
- return SUBSCRIPTION_WARNING_TEXT.replaceAll("{billingDomain}", domain).replaceAll("{plan}", plan).replaceAll("{priceJpy}", String(tierPriceJpy(plan)));
1158
+ function subscriptionWarning(siteUrl, plan) {
1159
+ return SUBSCRIPTION_WARNING_TEXT.replaceAll("{siteUrl}", siteUrl).replaceAll("{plan}", plan).replaceAll("{priceJpy}", String(tierPriceJpy(plan)));
1161
1160
  }
1162
1161
  var ticketCategoryEnum = z.enum([
1163
1162
  "billing",
@@ -1210,7 +1209,7 @@ function ensureUploadSizeWithinLimits(manifest, isFirstFreeDeploy) {
1210
1209
  if (total > FREE_SITE_MAX_TOTAL_BYTES) {
1211
1210
  throw new SakupaError(
1212
1211
  "validation_failed",
1213
- `The static output is ${(total / MB2).toFixed(1)}MB, over the ${Math.floor(FREE_SITE_MAX_TOTAL_BYTES / MB2)}MB free-site limit. Reduce the output (bundle/compress assets, drop large media) or use a paid domain plan for larger sites.`
1212
+ `The static output is ${(total / MB2).toFixed(1)}MB, over the ${Math.floor(FREE_SITE_MAX_TOTAL_BYTES / MB2)}MB free-site limit. Reduce the output (bundle/compress assets, drop large media) or subscribe the site to a paid plan for larger sites.`
1214
1213
  );
1215
1214
  }
1216
1215
  }
@@ -1279,7 +1278,7 @@ Next action: ${analysis.suggestedNextAction}`,
1279
1278
  server.registerTool(
1280
1279
  "deploy_site",
1281
1280
  {
1282
- description: `Deploy the local static output to Sakupa. First deploy creates a free temporary site (valid ${FREE_SITE_TTL_HOURS}h, public URL like https://{shortId}.sakupa.com) and stores the management credential in .sakupa/site.json. Later runs update the existing site and refresh its validity. Runs analyze_site first and refuses to upload source projects, secrets, .env files, archives, media or server code. Never uploads anything when the analysis says the project is not deployable.`,
1281
+ description: `Deploy the local static output to Sakupa. First deploy creates a free temporary site (valid ${FREE_SITE_TTL_HOURS}h, public URL like https://{shortId}.sakupa.com) and stores the management credential in .sakupa/site.json. Later runs update the existing site (free sites also refresh their validity; subscribed sites are permanent). Runs analyze_site first and refuses to upload source projects, secrets, .env files, archives, media or server code. Never uploads anything when the analysis says the project is not deployable.`,
1283
1282
  inputSchema: {
1284
1283
  outputDir: z.string().optional().describe("Output directory relative to the project root (overrides detection)."),
1285
1284
  spaFallback: z.boolean().optional().describe("Enable SPA fallback (requires spaFallbackConfirmed: true)."),
@@ -1331,8 +1330,8 @@ Next action: ${analysis.suggestedNextAction}`,
1331
1330
  Files uploaded: ${uploaded2} (${finalized2.totalBytes} bytes)
1332
1331
  ` + (finalized2.expiresAt ? `Expires at: ${finalized2.expiresAt}
1333
1332
  ` : "") + `
1334
- This is a FREE temporary preview: it stays live for ${FREE_SITE_TTL_HOURS} hours. Deploying again or calling refresh_site extends the validity. The management credential was saved to .sakupa/site.json \u2014 keep that file: it is the only way to manage this free site.
1335
- ` + (finalized2.warnings.length > 0 ? `
1333
+ This is a FREE temporary preview: it stays live for ${FREE_SITE_TTL_HOURS} hours. Deploying again or calling refresh_site extends the validity; subscribing the site (subscribe_site) makes this URL permanent. The management credential was saved to .sakupa/site.json \u2014 keep that file: it is the only way to manage this site.
1334
+ ` + credentialGitReminder(ctx.projectDir) + (finalized2.warnings.length > 0 ? `
1336
1335
  Warnings:
1337
1336
  ${JSON.stringify(finalized2.warnings, null, 2)}` : "")
1338
1337
  );
@@ -1372,8 +1371,8 @@ ${JSON.stringify(finalized2.warnings, null, 2)}` : "")
1372
1371
  Files uploaded: ${uploaded} (${finalized.totalBytes} bytes)
1373
1372
  ` + (finalized.expiresAt ? `Validity refreshed \u2014 expires at: ${finalized.expiresAt}
1374
1373
  ` : "") + (finalized.mode === "free" ? `
1375
- Reminder: free sites stay live for ${FREE_SITE_TTL_HOURS} hours after the last deploy or refresh_site call.
1376
- ` : "") + (finalized.warnings.length > 0 ? `
1374
+ Reminder: free sites stay live for ${FREE_SITE_TTL_HOURS} hours after the last deploy or refresh_site call. Subscribing (subscribe_site) makes the site permanent.
1375
+ ` : "\nThis site is subscribed and permanent \u2014 no expiry.\n") + (finalized.warnings.length > 0 ? `
1377
1376
  Warnings:
1378
1377
  ${JSON.stringify(finalized.warnings, null, 2)}` : "")
1379
1378
  );
@@ -1385,7 +1384,7 @@ ${JSON.stringify(finalized.warnings, null, 2)}` : "")
1385
1384
  server.registerTool(
1386
1385
  "refresh_site",
1387
1386
  {
1388
- description: "Refresh the validity of the free temporary site WITHOUT uploading content. Uses the local credential in .sakupa/site.json.",
1387
+ description: "Refresh the validity of the free temporary site WITHOUT uploading content. Uses the local credential in .sakupa/site.json. Subscribed sites are permanent and need no refresh.",
1389
1388
  inputSchema: {}
1390
1389
  },
1391
1390
  async () => {
@@ -1404,7 +1403,7 @@ Free sites stay live for ${FREE_SITE_TTL_HOURS} hours after each deploy or refre
1404
1403
  server.registerTool(
1405
1404
  "site_status",
1406
1405
  {
1407
- description: "Show the current status of this project's Sakupa site: URL, mode (free/paid), expiry, domain binding, size, last deployment and warnings.",
1406
+ description: "Show the current status of this project's Sakupa site: URL, mode (free/paid), expiry, subscription state, custom domains, size, last deployment and warnings.",
1408
1407
  inputSchema: {}
1409
1408
  },
1410
1409
  async () => {
@@ -1417,12 +1416,57 @@ Free sites stay live for ${FREE_SITE_TTL_HOURS} hours after each deploy or refre
1417
1416
  }
1418
1417
  }
1419
1418
  );
1419
+ server.registerTool(
1420
+ "subscribe_site",
1421
+ {
1422
+ description: `Create a Stripe Checkout link that subscribes THIS site to a Sakupa Hosting monthly plan (${planCatalog()}). Paying makes the site PERMANENT on its {shortId}.sakupa.com URL \u2014 no more 24h expiry; that is the core value of paying. Binding a custom domain afterwards (bind_domain) is an optional included extra and requires DNS control of that domain. Owner-only: requires this project's site credential (.sakupa/site.json) \u2014 deploy_site first. If the site outgrows its plan, Sakupa auto-upgrades to the next plan (capped at Business, where growth is limited instead of billed further). Card details are entered only on the Stripe-hosted page \u2014 never through the AI tool. Without confirm: true this tool only shows the mandatory disclosure and makes no API call.`,
1423
+ inputSchema: {
1424
+ plan: planEnum.describe(
1425
+ "Monthly plan: water (very light personal pages), personal (personal brand / small shop), share (small-business site), business (steadier traffic, more headroom)."
1426
+ ),
1427
+ confirm: z.boolean().optional().describe("User read the subscription disclosure and confirmed. Required to proceed.")
1428
+ }
1429
+ },
1430
+ async (args) => {
1431
+ try {
1432
+ const site = requireSiteFile(ctx);
1433
+ const siteUrl = site.url ?? (site.shortId ? `https://${site.shortId}.sakupa.com` : site.siteId);
1434
+ if (args.confirm !== true) {
1435
+ return text(
1436
+ `${subscriptionWarning(siteUrl, args.plan)}
1437
+
1438
+ No checkout link was created yet. Please show this disclosure to the user and, after their explicit confirmation, re-run subscribe_site with confirm: true.`
1439
+ );
1440
+ }
1441
+ const res = await ctx.client.createPlanCheckout(
1442
+ {
1443
+ siteId: site.siteId,
1444
+ plan: args.plan,
1445
+ idempotencyKey: randomUUID(),
1446
+ confirmPlan: true
1447
+ },
1448
+ site.credential
1449
+ );
1450
+ return text(
1451
+ `Stripe Checkout link \u2014 Sakupa Hosting for this site: ${res.plan} plan, \xA5${res.monthlyPriceJpy}/month
1452
+ ${res.checkoutUrl}
1453
+
1454
+ Open this link in a browser to subscribe. Card data is entered only on the Stripe-hosted page \u2014 never give card numbers, passwords or security codes to the AI tool.
1455
+ Once payment confirms, the site becomes permanent on its current URL. Binding a custom domain (bind_domain) is optional and still requires DNS verification.`
1456
+ );
1457
+ } catch (e) {
1458
+ return toolError(e);
1459
+ }
1460
+ }
1461
+ );
1420
1462
  server.registerTool(
1421
1463
  "bind_domain",
1422
1464
  {
1423
- description: `Start or continue binding a custom domain to this site (the paid long-term mode). Ownership is proven ONLY by DNS control of the registered apex domain \u2014 payment never grants ownership. The billing subject is always the apex domain: all its subdomains share one hosting subscription (plans: ${planCatalog()}). The apex domain needs an ACTIVE subscription (see subscribe_domain) before paid configuration can start. Call again with verificationId to check DNS verification progress.`,
1465
+ description: "Bind a custom domain to this subscribed site \u2014 an OPTIONAL extra serving surface; the permanent {shortId}.sakupa.com URL keeps working alongside it. The binding unit is the APEX domain: binding example.com automatically includes www.example.com (both serve the same content, one apex TXT verification covers both), and one site binds at most ONE apex domain \u2014 a second domain needs a second subscribed site. Requires an ACTIVE subscription (subscribe_site). Ownership is proven ONLY by DNS control of the apex \u2014 payment never grants ownership. A binding request never reserves the domain: whoever proves DNS control first gets it, and unverified requests expire after 72 hours. Call again with verificationId to check progress.",
1424
1466
  inputSchema: {
1425
- hostname: z.string().describe('Hostname to bind, e.g. "example.com" or "www.example.com".'),
1467
+ hostname: z.string().describe(
1468
+ 'Domain to bind: the apex ("example.com") or its www form ("www.example.com") \u2014 both mean the same unit. Other subdomains cannot be bound.'
1469
+ ),
1426
1470
  verificationId: z.string().optional().describe("Check an existing DNS verification instead of starting a new one.")
1427
1471
  }
1428
1472
  },
@@ -1432,12 +1476,12 @@ Free sites stay live for ${FREE_SITE_TTL_HOURS} hours after each deploy or refre
1432
1476
  if (args.verificationId !== void 0) {
1433
1477
  const res2 = await ctx.client.checkVerification(args.verificationId, site.credential);
1434
1478
  if (res2.status === "verified") {
1435
- writeSiteFile(ctx.projectDir, { ...site, billingDomain: res2.apexDomain });
1479
+ writeSiteFile(ctx.projectDir, { ...site, boundDomain: res2.apexDomain });
1436
1480
  }
1437
1481
  return text(
1438
1482
  `DNS verification ${res2.verificationId}: ${res2.status}
1439
1483
  ${res2.message}
1440
- ` + (res2.provisioningJobId ? `Provisioning started (job ${res2.provisioningJobId}). HTTPS certificate and CDN setup are in progress; check again with bind_domain + verificationId later.
1484
+ ` + (res2.provisioningJobId ? `Provisioning started (job ${res2.provisioningJobId}). HTTPS certificates and serving setup are in progress; check again with bind_domain + verificationId later.
1441
1485
  ` : "") + (res2.pendingDnsRecords.length > 0 ? `
1442
1486
  DNS records still required:
1443
1487
  ${JSON.stringify(res2.pendingDnsRecords, null, 2)}` : "")
@@ -1448,25 +1492,16 @@ ${JSON.stringify(res2.pendingDnsRecords, null, 2)}` : "")
1448
1492
  hostname: args.hostname
1449
1493
  };
1450
1494
  const res = await ctx.client.bindDomain(site.credential, req);
1451
- writeSiteFile(ctx.projectDir, {
1452
- ...site,
1453
- billingDomain: res.apexDomain,
1454
- billingDomainId: res.billingDomainId
1455
- });
1456
- const servingHint = res.isApex ? `"${res.hostname}" is an apex domain: your DNS provider must support ALIAS, ANAME, CNAME flattening, or alias records to point it at the assigned CDN domain.` : `"${res.hostname}" is a subdomain: create a CNAME record pointing it at the assigned CDN domain once provisioning completes.`;
1457
1495
  return text(
1458
- `Domain binding started for ${res.hostname}.
1459
-
1460
- Billing subject: the apex domain "${res.apexDomain}". Subdomains of ${res.apexDomain} cannot be separate billing subjects \u2014 they all share this domain hosting subscription.
1496
+ `Domain binding started for ${res.apexDomain} (includes: ${res.includedHostnames.join(", ")} \u2014 both will serve this site).
1461
1497
 
1462
1498
  1. Prove control of ${res.apexDomain} by creating this DNS record:
1463
1499
  name: ${res.verificationRecord.name}
1464
1500
  type: ${res.verificationRecord.type}
1465
1501
  value: ${res.verificationRecord.value}
1466
- Ownership and management authority come ONLY from DNS control. Paying for the subscription never grants ownership, management rights, or activation.
1502
+ Ownership comes ONLY from DNS control; paying never grants it. This request does not reserve the domain \u2014 the first verified request wins, and this challenge expires after 72 hours.
1467
1503
 
1468
- 2. Serving DNS (after verification): ${servingHint}
1469
- Server guidance: ${res.servingInstructions}
1504
+ 2. Serving DNS (after verification): ${res.servingInstructions}
1470
1505
 
1471
1506
  Then run bind_domain again with verificationId: "${res.verificationId}" to check verification and start provisioning.`
1472
1507
  );
@@ -1478,33 +1513,24 @@ Then run bind_domain again with verificationId: "${res.verificationId}" to check
1478
1513
  server.registerTool(
1479
1514
  "billing_status",
1480
1515
  {
1481
- description: "Show the hosting subscription status of an apex billing domain: current plan, payment state, current paid period, reconciled usage, estimated usage tier, next renewal, risks and the per-site usage breakdown. Reads are based on the latest reconciled snapshot.",
1482
- inputSchema: {
1483
- domain: z.string().optional().describe("Apex billing domain; defaults to the domain bound in .sakupa/site.json.")
1484
- }
1516
+ description: "Show this site's hosting subscription: plan, payment state, current paid period, reconciled usage, estimated usage tier, bound custom domains and risks. Owner-only (uses the credential in .sakupa/site.json).",
1517
+ inputSchema: {}
1485
1518
  },
1486
- async (args) => {
1519
+ async () => {
1487
1520
  try {
1488
- const site = readSiteFile(ctx.projectDir);
1489
- const domain = args.domain ?? site?.billingDomain;
1490
- if (!domain) {
1491
- throw new SakupaError(
1492
- "invalid_request",
1493
- 'No domain given and this project has no bound billing domain. Pass domain, e.g. billing_status { domain: "example.com" }.'
1494
- );
1495
- }
1496
- const res = await ctx.client.getBillingStatus(domain, site?.credential);
1521
+ const site = requireSiteFile(ctx);
1522
+ const res = await ctx.client.getBillingStatus(site.siteId, site.credential);
1497
1523
  const lines = [
1498
- `Billing status for ${res.paidSubject} (service status: ${res.serviceStatus})`,
1499
- res.committedTier ? `Plan: ${res.committedTier} (\xA5${tierPriceJpy(res.committedTier)}/month)` : "Plan: (no subscription yet)",
1524
+ `Billing status for site ${res.siteId} (mode: ${res.mode})`,
1525
+ res.permanentUrl ? `Permanent URL: ${res.permanentUrl}` : void 0,
1526
+ res.plan ? `Plan: ${res.plan} (\xA5${res.monthlyPriceJpy ?? tierPriceJpy(res.plan)}/month)` : "Plan: (no subscription yet)",
1500
1527
  res.subscriptionStatus ? `Subscription payment state: ${res.subscriptionStatus}` : void 0,
1501
- res.cancelAtCycleEnd ? "Renewal: CANCELED \u2014 hosting stops at the end of the already-paid month" : void 0,
1502
- res.currentCycleStart ? `Current paid period: ${res.currentCycleStart} -> ${res.currentCycleEnd ?? "?"}` : void 0,
1528
+ res.cancelAtPeriodEnd ? "Renewal: CANCELED \u2014 the site reverts to free at the end of the already-paid month" : void 0,
1529
+ res.currentPeriodStart ? `Current paid period: ${res.currentPeriodStart} -> ${res.currentPeriodEnd ?? "?"}` : void 0,
1503
1530
  res.estimatedUsageTier ? `Estimated usage tier: ${res.estimatedUsageTier}` : void 0,
1504
1531
  res.lastReconciledAt ? `Last usage reconciliation: ${res.lastReconciledAt}` : void 0,
1505
- res.nextSettlementAt ? `Next renewal: ${res.nextSettlementAt}` : void 0,
1506
- res.risks.unpaid ? "ATTENTION: renewal payment failed \u2014 update the payment method (manage_billing) to keep the custom domain hosted." : void 0,
1507
- res.ownerView ? void 0 : "Note: public view (no valid owner credential presented)."
1532
+ res.boundHostnames.length > 0 ? `Bound custom domains: ${res.boundHostnames.join(", ")}` : void 0,
1533
+ res.risks.pastDue ? "ATTENTION: renewal payment failing \u2014 update the payment method (manage_billing). Serving continues while Stripe retries; if Stripe gives up, the site reverts to free." : void 0
1508
1534
  ].filter((l) => l !== void 0);
1509
1535
  return textJson(`${lines.join("\n")}
1510
1536
 
@@ -1514,71 +1540,18 @@ Full status:`, res);
1514
1540
  }
1515
1541
  }
1516
1542
  );
1517
- server.registerTool(
1518
- "subscribe_domain",
1519
- {
1520
- description: `Create a Stripe Checkout link that subscribes an apex domain to a Sakupa Domain Hosting monthly plan (${planCatalog()}). Owner-only: requires this project's site credential (.sakupa/site.json) \u2014 deploy_site first; a lost credential means payment is not possible. One domain = one subscription; if the site outgrows its plan, Sakupa auto-upgrades to the next plan (capped at Business, where growth is limited instead of billed further). Paying never proves domain ownership and never activates a website \u2014 DNS verification (bind_domain) is still required. Card details are entered only on the Stripe-hosted page \u2014 never through the AI tool. Without confirm: true this tool only shows the mandatory disclosure and makes no API call.`,
1521
- inputSchema: {
1522
- domain: z.string().describe('Apex domain to subscribe, e.g. "example.com".'),
1523
- plan: planEnum.describe(
1524
- "Monthly plan: water (very light personal pages), personal (personal brand / small shop), share (small-business site), business (steadier traffic, more headroom)."
1525
- ),
1526
- confirm: z.boolean().optional().describe("User read the subscription disclosure and confirmed. Required to proceed.")
1527
- }
1528
- },
1529
- async (args) => {
1530
- try {
1531
- const site = requireSiteFile(ctx);
1532
- if (args.confirm !== true) {
1533
- return text(
1534
- `${subscriptionWarning(args.domain, args.plan)}
1535
-
1536
- No checkout link was created yet. Please show this disclosure to the user and, after their explicit confirmation, re-run subscribe_domain with confirm: true.`
1537
- );
1538
- }
1539
- const res = await ctx.client.createPlanCheckout(
1540
- {
1541
- siteId: site.siteId,
1542
- domain: args.domain,
1543
- plan: args.plan,
1544
- idempotencyKey: randomUUID(),
1545
- confirmPlan: true
1546
- },
1547
- site.credential
1548
- );
1549
- return text(
1550
- `Stripe Checkout link \u2014 Sakupa Domain Hosting for ${res.apexDomain}: ${res.plan} plan, \xA5${res.monthlyPriceJpy}/month
1551
- ${res.checkoutUrl}
1552
-
1553
- Open this link in a browser to subscribe. Card data is entered only on the Stripe-hosted page \u2014 never give card numbers, passwords or security codes to the AI tool.
1554
- Reminder: the subscription is payment state only. It grants no domain ownership and no management rights; the domain must still pass DNS verification (bind_domain) before long-term hosting activates.`
1555
- );
1556
- } catch (e) {
1557
- return toolError(e);
1558
- }
1559
- }
1560
- );
1561
1543
  server.registerTool(
1562
1544
  "manage_billing",
1563
1545
  {
1564
- description: "Open the Stripe-hosted billing portal for the bound apex domain: update the payment method, view invoices, or cancel the subscription. All billing operations happen on the Stripe-hosted page \u2014 never inside the AI tool. Requires the local site credential (.sakupa/site.json) of a site bound to the domain.",
1565
- inputSchema: {
1566
- domain: z.string().optional().describe("Apex billing domain; defaults to the domain bound in .sakupa/site.json.")
1567
- }
1546
+ description: "Open the Stripe-hosted billing portal for this site: update the payment method, view invoices, or cancel the subscription. All billing operations happen on the Stripe-hosted page \u2014 never inside the AI tool. Requires the local site credential (.sakupa/site.json).",
1547
+ inputSchema: {}
1568
1548
  },
1569
- async (args) => {
1549
+ async () => {
1570
1550
  try {
1571
1551
  const site = requireSiteFile(ctx);
1572
- const domain = args.domain ?? site.billingDomain;
1573
- if (!domain) {
1574
- throw new SakupaError(
1575
- "invalid_request",
1576
- "No domain given and this project has no bound billing domain. Pass domain explicitly."
1577
- );
1578
- }
1579
- const res = await ctx.client.createBillingPortal(domain, site.credential);
1552
+ const res = await ctx.client.createBillingPortal(site.siteId, site.credential);
1580
1553
  return text(
1581
- `Stripe billing portal for ${res.apexDomain}:
1554
+ `Stripe billing portal for this site:
1582
1555
  ${res.portalUrl}
1583
1556
 
1584
1557
  Open this link in a browser to update the payment method, view invoices, or manage the subscription. The link is temporary \u2014 create a fresh one when needed.`
@@ -1591,7 +1564,7 @@ Open this link in a browser to update the payment method, view invoices, or mana
1591
1564
  server.registerTool(
1592
1565
  "recover_domain_site",
1593
1566
  {
1594
- description: "Recover management control of a paid custom-domain site after losing the local project, by proving DNS control of the apex domain. By default, completing recovery REVOKES all previous local credentials for the site. Call first with the hostname to get the DNS record, then again with verificationId to complete recovery (writes a new .sakupa/site.json and returns a download link for the current site content).",
1567
+ description: "Recover management control of a subscribed site WITH A BOUND CUSTOM DOMAIN after losing the local project, by proving DNS control of the apex domain. Sites without a bound domain are identified solely by their local credential and cannot be recovered. By default, completing recovery REVOKES all previous local credentials. Call first with the hostname to get the DNS record, then again with verificationId to complete recovery (writes a new .sakupa/site.json and returns a download link for the current site content).",
1595
1568
  inputSchema: {
1596
1569
  hostname: z.string().describe('Hostname of the site to recover, e.g. "www.example.com".'),
1597
1570
  verificationId: z.string().optional().describe("Complete a recovery previously started for this hostname."),
@@ -1603,7 +1576,7 @@ Open this link in a browser to update the payment method, view invoices, or mana
1603
1576
  if (args.verificationId === void 0) {
1604
1577
  const res2 = await ctx.client.recoverDomain({ hostname: args.hostname });
1605
1578
  return text(
1606
- `Recovery started for ${args.hostname} (apex billing domain: ${res2.apexDomain}).
1579
+ `Recovery started for ${args.hostname} (apex domain: ${res2.apexDomain}).
1607
1580
 
1608
1581
  Create this DNS record to prove apex-domain control:
1609
1582
  name: ${res2.verificationRecord.name}
@@ -1622,18 +1595,18 @@ After the DNS record resolves, re-run recover_domain_site with verificationId: "
1622
1595
  });
1623
1596
  writeSiteFile(ctx.projectDir, {
1624
1597
  siteId: res.siteId,
1625
- billingDomain: res.billingDomain,
1598
+ ...res.boundHostnames[0] !== void 0 ? { boundDomain: res.boundHostnames[0] } : {},
1626
1599
  credential: res.credential,
1627
1600
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
1628
1601
  apiBaseUrl: ctx.apiBaseUrl
1629
1602
  });
1630
1603
  return text(
1631
- `Recovery complete for ${res.billingDomain}.
1604
+ `Recovery complete.
1632
1605
  Site: ${res.siteId} (hostnames: ${res.boundHostnames.join(", ") || "(none)"})
1633
1606
  Previous credentials revoked: ${res.revokedPreviousCredentials ? "YES" : "no (preserved on request)"}
1634
1607
 
1635
1608
  A NEW management credential was written to .sakupa/site.json in this project \u2014 this project now manages the site.
1636
-
1609
+ ` + credentialGitReminder(ctx.projectDir) + `
1637
1610
  Download the current site content (signed URL):
1638
1611
  ${res.archiveUrl}`
1639
1612
  );
@@ -1645,39 +1618,32 @@ ${res.archiveUrl}`
1645
1618
  server.registerTool(
1646
1619
  "set_billing_plan",
1647
1620
  {
1648
- description: `Change the hosting plan of the apex billing domain or cancel/re-enable renewal. Plans: ${planCatalog()}. Plan changes go through the Stripe subscription; renewals bill the new plan. Auto-upgrade (one plan up when usage exceeds the current plan, capped at Business) is built in and not configurable. The API returns the billing consequences first; explicit owner confirmation (confirm: true) is required before anything is applied.`,
1621
+ description: `Change this site's hosting plan, cancel/re-enable renewal, or cancel immediately. Plans: ${planCatalog()}. Plan changes go through the Stripe subscription; renewals bill the new plan. Auto-upgrade (one plan up when usage exceeds the current plan, capped at Business) is built in and not configurable. cancelRenewal: true ends the subscription at the period end; cancelNow: true ends it IMMEDIATELY \u2014 the site reverts to a free 24h site at once and all paid data (custom domain bindings included) is removed, with no refund of the current period. The API returns the consequences first; explicit owner confirmation (confirm: true) is required before anything is applied.`,
1649
1622
  inputSchema: {
1650
- domain: z.string().optional().describe("Apex billing domain; defaults to the domain bound in .sakupa/site.json."),
1651
1623
  plan: planEnum.optional().describe("Target monthly plan."),
1652
1624
  cancelRenewal: z.boolean().optional().describe(
1653
- "true: cancel renewal (hosting runs to the end of the paid month, then stops). false: re-enable renewal."
1625
+ "true: cancel renewal (the site stays permanent to the end of the paid month, then reverts to free). false: re-enable renewal."
1654
1626
  ),
1627
+ cancelNow: z.boolean().optional().describe("End the subscription immediately; the site reverts to free right away."),
1655
1628
  confirm: z.boolean().optional().describe("User saw the consequences and explicitly confirmed.")
1656
1629
  }
1657
1630
  },
1658
1631
  async (args) => {
1659
1632
  try {
1660
1633
  const site = requireSiteFile(ctx);
1661
- const domain = args.domain ?? site.billingDomain;
1662
- if (!domain) {
1663
- throw new SakupaError(
1664
- "invalid_request",
1665
- "No domain given and this project has no bound billing domain. Pass domain explicitly."
1666
- );
1667
- }
1668
1634
  const req = {
1669
- siteId: site.siteId,
1670
- ...args.plan !== void 0 ? { committedTier: args.plan } : {},
1635
+ ...args.plan !== void 0 ? { plan: args.plan } : {},
1671
1636
  ...args.cancelRenewal !== void 0 ? { cancelRenewal: args.cancelRenewal } : {},
1637
+ ...args.cancelNow !== void 0 ? { cancelNow: args.cancelNow } : {},
1672
1638
  confirm: args.confirm === true
1673
1639
  };
1674
1640
  try {
1675
- const res = await ctx.client.setBillingPlan(domain, site.credential, req);
1641
+ const res = await ctx.client.setBillingPlan(site.siteId, site.credential, req);
1676
1642
  return textJson(
1677
- `Billing plan updated for ${res.apexDomain}.
1643
+ `Billing updated for site ${res.siteId} (mode: ${res.mode}).
1678
1644
  Consequences:
1679
1645
  ${res.consequences.map((c) => `- ${c}`).join("\n")}
1680
- Applied plan:`,
1646
+ Result:`,
1681
1647
  res
1682
1648
  );
1683
1649
  } catch (e) {
@@ -1697,50 +1663,6 @@ ${e.message}
1697
1663
  }
1698
1664
  }
1699
1665
  );
1700
- server.registerTool(
1701
- "downgrade_to_free",
1702
- {
1703
- description: "Move this paid custom-domain site back to free temporary mode. Takes effect at the next billing period boundary by default; immediateStopServing stops custom-domain serving now but never erases the already-paid month. Remember to also cancel the domain subscription (set_billing_plan cancelRenewal: true or manage_billing) if no other site uses it. The API returns the consequences first; confirm: true is required to apply.",
1704
- inputSchema: {
1705
- immediateStopServing: z.boolean().optional().describe(
1706
- "Also stop custom-domain serving immediately (does not remove current-cycle charges)."
1707
- ),
1708
- confirm: z.boolean().optional().describe("User saw the consequences and explicitly confirmed.")
1709
- }
1710
- },
1711
- async (args) => {
1712
- try {
1713
- const site = requireSiteFile(ctx);
1714
- try {
1715
- const res = await ctx.client.downgradeSite(site.siteId, site.credential, {
1716
- ...args.immediateStopServing !== void 0 ? { immediateStopServing: args.immediateStopServing } : {},
1717
- confirm: args.confirm === true
1718
- });
1719
- return text(
1720
- `Downgrade scheduled for site ${res.siteId}.
1721
- Effective at: ${res.effectiveAt}
1722
- Immediate stop-serving applied: ${res.immediateStopApplied ? "yes" : "no"}
1723
- ${res.message}
1724
-
1725
- After it takes effect the site becomes a free temporary site again (24h validity, free banner, free limits). If no other site uses this domain, also cancel its hosting subscription (set_billing_plan cancelRenewal: true or manage_billing).`
1726
- );
1727
- } catch (e) {
1728
- if (isSakupaError(e) && e.code === "confirmation_required") {
1729
- return text(
1730
- `Confirmation required before downgrading \u2014 nothing was applied.
1731
-
1732
- ${e.message}
1733
- ` + (e.details !== void 0 ? `${JSON.stringify(e.details, null, 2)}
1734
- ` : "") + "\nPlease show these consequences to the user and, after their explicit confirmation, re-run downgrade_to_free with confirm: true."
1735
- );
1736
- }
1737
- throw e;
1738
- }
1739
- } catch (e) {
1740
- return toolError(e);
1741
- }
1742
- }
1743
- );
1744
1666
  server.registerTool(
1745
1667
  "create_support_ticket",
1746
1668
  {
@@ -1771,7 +1693,7 @@ ${e.message}
1771
1693
  server.registerTool(
1772
1694
  "report_bug",
1773
1695
  {
1774
- description: "Prepare and submit a sanitized bug report when a Sakupa tool failed and the issue looks like a product bug. Only whitelisted structured diagnostics are sent (tool name, error code/message, site id, billing domain, deployment id, timestamps, client/MCP version, request id) \u2014 NEVER file contents, source code, secrets, .env values or credentials. Without confirmSubmit: true the exact payload is shown for user review and nothing is submitted.",
1696
+ description: "Prepare and submit a sanitized bug report when a Sakupa tool failed and the issue looks like a product bug. Only whitelisted structured diagnostics are sent (tool name, error code/message, site id, bound domain, deployment id, timestamps, client/MCP version, request id) \u2014 NEVER file contents, source code, secrets, .env values or credentials. Without confirmSubmit: true the exact payload is shown for user review and nothing is submitted.",
1775
1697
  inputSchema: {
1776
1698
  toolName: z.string().describe('The Sakupa tool that failed, e.g. "deploy_site".'),
1777
1699
  errorCode: z.string().optional(),
@@ -1791,7 +1713,7 @@ ${e.message}
1791
1713
  ...args.errorCode !== void 0 ? { errorCode: args.errorCode } : {},
1792
1714
  ...args.errorMessage !== void 0 ? { sanitizedErrorMessage: args.errorMessage } : {},
1793
1715
  ...site ? { siteId: site.siteId } : {},
1794
- ...site?.billingDomain ? { billingDomain: site.billingDomain } : {},
1716
+ ...site?.boundDomain ? { boundDomain: site.boundDomain } : {},
1795
1717
  ...args.deploymentId !== void 0 ? { deploymentId: args.deploymentId } : {},
1796
1718
  occurredAt: (/* @__PURE__ */ new Date()).toISOString(),
1797
1719
  clientType: CLIENT_TYPE,
@@ -1835,6 +1757,7 @@ var FetchTransport = class {
1835
1757
  }
1836
1758
  const headers = {
1837
1759
  accept: "application/json",
1760
+ [MCP_VERSION_HEADER]: MCP_VERSION,
1838
1761
  ...req.body !== void 0 ? { "content-type": "application/json" } : {},
1839
1762
  ...req.headers
1840
1763
  };
@@ -1885,19 +1808,23 @@ Workflow:
1885
1808
  site (public URL {shortId}.sakupa.com, valid 24 hours, free banner shown) and stores the
1886
1809
  management credential in .sakupa/site.json. Deploying again updates the site and refreshes
1887
1810
  its validity; refresh_site extends validity without uploading.
1888
- 3. For long-term use, subscribe the apex domain to a monthly hosting plan (subscribe_domain ->
1811
+ 3. To make the site PERMANENT, subscribe it to a monthly hosting plan (subscribe_site ->
1889
1812
  Stripe-hosted checkout; water/personal/share/business, auto-upgrade when the site outgrows
1890
- its plan), then bind the custom domain (bind_domain): the billing subject is always the
1891
- registered apex domain and ownership is proven only by DNS control. billing_status,
1892
- set_billing_plan, manage_billing, downgrade_to_free and recover_domain_site manage the
1893
- paid lifecycle.
1813
+ its plan). Paying makes the {shortId}.sakupa.com URL permanent \u2014 that is what payment buys.
1814
+ 4. Optionally bind a custom domain to the subscribed site (bind_domain): an included extra
1815
+ serving surface alongside the permanent URL. Ownership is proven only by DNS control; the
1816
+ first verified request wins; unverified requests expire after 72 hours. billing_status,
1817
+ set_billing_plan, manage_billing and recover_domain_site manage the paid lifecycle.
1818
+ Canceling the subscription immediately reverts the site to a free 24h site and removes all
1819
+ paid data.
1894
1820
 
1895
1821
  Safety boundaries:
1896
1822
  - Static output only: no SSR, API routes, middleware, server actions, databases or online builds.
1897
1823
  - Never upload source projects, secrets, .env files, private keys, archives, videos or audio.
1898
1824
  - Payment card data is entered only on Stripe-hosted pages \u2014 never through the AI tool.
1899
- - A subscription is payment state only; it never grants domain ownership or management rights.
1900
- - The management credential lives only in .sakupa/site.json; never share or upload it.`;
1825
+ - A subscription never grants domain ownership; only DNS verification does.
1826
+ - The management credential lives only in .sakupa/site.json; never share or upload it. Without
1827
+ a bound custom domain, a lost credential is unrecoverable by design.`;
1901
1828
  function createSakupaMcpServer(opts) {
1902
1829
  const client = opts.client ?? new HttpApiClient(new FetchTransport(opts.apiBaseUrl));
1903
1830
  const server = new McpServer(