sbuilder-mcp 0.109.0 → 0.110.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,22 @@ All notable changes to this project are documented in this file.
6
6
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
7
7
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
 
9
+ ## [0.110.0] - 2026-11-19
10
+
11
+ ### Added
12
+ - `install` runs as a single guided command, `npx -y sbuilder-mcp@latest install`, that signs in through the browser by default, lets you pick a store by number, and installs into every agent in three steps.
13
+ - Running `npx sbuilder-mcp` with no arguments in a terminal prints the command to run instead of sitting silent.
14
+ - The installer speaks Vietnamese when the machine language is Vietnamese or `--lang vi` is passed.
15
+
16
+ ### Changed
17
+ - `install` targets the live platform (`https://api.sbuilder.io.vn`) by default, so `--api` is only needed for a local platform.
18
+ - Client configs written by a login-style install pin `sbuilder-mcp@latest`, so a stale npx cache cannot run a version that cannot read the login session.
19
+
20
+ ## [0.109.1] - 2026-11-19
21
+
22
+ ### Fixed
23
+ - `sb_site_use` is no longer marked read-only, so clients that auto-approve read-only tools now ask before it changes the site every later write lands on.
24
+
9
25
  ## [0.109.0] - 2026-11-19
10
26
 
11
27
  ### Added
package/CHANGELOG.vi.md CHANGED
@@ -6,6 +6,22 @@ Mọi thay đổi đáng chú ý của dự án được ghi lại trong file n
6
6
  Định dạng dựa trên [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
7
7
  và dự án tuân theo [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
8
8
 
9
+ ## [0.110.0] - 2026-11-19
10
+
11
+ ### Added
12
+ - `install` chạy bằng một lệnh có hướng dẫn, `npx -y sbuilder-mcp@latest install`, mặc định đăng nhập bằng trình duyệt, chọn cửa hàng bằng số và cài vào mọi agent qua ba bước.
13
+ - Chạy `npx sbuilder-mcp` không kèm tham số trong terminal sẽ in ra lệnh cần chạy thay vì đứng im.
14
+ - Trình cài đặt nói tiếng Việt khi máy dùng tiếng Việt hoặc khi truyền `--lang vi`.
15
+
16
+ ### Changed
17
+ - `install` mặc định dùng nền tảng thật (`https://api.sbuilder.io.vn`), nên chỉ cần `--api` khi dùng nền tảng local.
18
+ - Cấu hình client do cài đặt kiểu đăng nhập ghi ra dùng `sbuilder-mcp@latest`, nên bản cũ trong cache npx không thể chạy một phiên bản không đọc được phiên đăng nhập.
19
+
20
+ ## [0.109.1] - 2026-11-19
21
+
22
+ ### Fixed
23
+ - `sb_site_use` không còn được đánh dấu chỉ-đọc, nên các client tự động duyệt công cụ chỉ-đọc giờ sẽ hỏi trước khi nó đổi site mà mọi lệnh ghi sau đó rơi vào.
24
+
9
25
  ## [0.109.0] - 2026-11-19
10
26
 
11
27
  ### Added
package/README.md CHANGED
@@ -8,27 +8,28 @@ publish it — with no human clicking anything.
8
8
 
9
9
  ## Install
10
10
 
11
- One command writes this server into every agent client on your machine:
11
+ One command, nothing to copy:
12
12
 
13
13
  ```bash
14
- npx -y sbuilder-mcp install --token wbk_… --api https://your-host --site site_…
14
+ npx -y sbuilder-mcp@latest install
15
15
  ```
16
16
 
17
- ### Or sign in the whole account in the browser
17
+ It walks you through three steps: **sign in** (a browser page opens — type the code shown in
18
+ the terminal and press Approve), **choose your store** (type its number), and **install** into
19
+ every agent client it finds. Then restart your agent and ask it something like *"list the pages
20
+ of my store"*. No key, no password and no config file to edit. It speaks Vietnamese on a
21
+ Vietnamese machine (or with `--lang vi`), and run with no arguments it just tells you this
22
+ command. Local development: add `--api http://localhost:8080`.
23
+
24
+ The store's **Apps → AI agent** screen hands you the same command with the store already
25
+ chosen (`--site`).
26
+
27
+ ### With an API key instead (one store, scripts, CI)
18
28
 
19
29
  ```bash
20
- npx -y sbuilder-mcp@latest install --login --api https://your-host --site site_…
30
+ npx -y sbuilder-mcp install --token wbk_… --api https://your-host --site site_…
21
31
  ```
22
32
 
23
- It prints a code and opens the platform's sign-in page: type the code, check it matches, press
24
- **Approve**. No key and no password is written anywhere — the login is kept in
25
- `~/.config/sb/credentials.json` (owner-only), **the same file `sb login` uses**, so one approval
26
- signs in the CLI and every agent window together, and survives restarts. `--site` is the site
27
- the agent starts on; with the account it can reach every site you can, and `sb_site_use` moves
28
- it. Already signed in? The command says so and skips the browser. Inside a chat, `sb_login`
29
- does the same thing (the first call returns the code, the next one waits for the approval), and
30
- `sb_login action:"logout"` signs the machine out.
31
-
32
33
  It knows Claude Code, Claude Desktop, Cursor, Windsurf, VS Code and Codex, and installs into
33
34
  the ones it finds. Name them with `--client cursor,codex`, or rehearse with `--dry-run`. An
34
35
  option it does not know is **refused**, not ignored — a flag that silently does nothing is
package/README.vi.md CHANGED
@@ -8,27 +8,27 @@ quả rồi xuất bản — mà không cần người bấm gì.
8
8
 
9
9
  ## Cài đặt
10
10
 
11
- Một lệnh ghi server này vào mọi agent client trên máy bạn:
11
+ Một lệnh, không phải chép gì:
12
12
 
13
13
  ```bash
14
- npx -y sbuilder-mcp install --token wbk_… --api https://your-host --site site_…
14
+ npx -y sbuilder-mcp@latest install
15
15
  ```
16
16
 
17
- ### Hoặc đăng nhập cả tài khoản bằng trình duyệt
17
+ Lệnh dẫn bạn qua ba bước: **đăng nhập** (trang trình duyệt mở ra — gõ mã hiện trong terminal rồi
18
+ bấm Chấp thuận), **chọn cửa hàng** (gõ số), và **cài** vào mọi agent client tìm thấy trên máy.
19
+ Sau đó mở lại agent và hỏi thử *"liệt kê các trang của cửa hàng tôi"*. Không khoá, không mật khẩu,
20
+ không file cấu hình nào phải sửa. Máy tiếng Việt (hoặc `--lang vi`) thì lệnh nói tiếng Việt; chạy
21
+ `npx sbuilder-mcp` không kèm gì thì nó chỉ nhắc lệnh này. Phát triển ở local: thêm
22
+ `--api http://localhost:8080`.
23
+
24
+ Màn **Ứng dụng → AI agent** của cửa hàng đưa sẵn đúng lệnh này với cửa hàng đã chọn (`--site`).
25
+
26
+ ### Hoặc dùng khoá API (một cửa hàng, script, CI)
18
27
 
19
28
  ```bash
20
- npx -y sbuilder-mcp@latest install --login --api https://your-host --site site_…
29
+ npx -y sbuilder-mcp install --token wbk_… --api https://your-host --site site_…
21
30
  ```
22
31
 
23
- Lệnh in ra một mã và mở trang đăng nhập của nền tảng: gõ mã, kiểm tra khớp, bấm **Đồng ý**.
24
- Không khoá, không mật khẩu nào bị ghi ra — phiên đăng nhập được giữ trong
25
- `~/.config/sb/credentials.json` (chỉ chủ máy đọc được), **cùng file với `sb login`**, nên một lần
26
- đồng ý là CLI và mọi cửa sổ agent đều đăng nhập, và vẫn còn sau khi khởi động lại. `--site` là
27
- site agent bắt đầu làm; với cả tài khoản nó với tới mọi site bạn có quyền, và `sb_site_use`
28
- chuyển site. Đã đăng nhập rồi thì lệnh báo và bỏ qua trình duyệt. Ngay trong cuộc chat,
29
- `sb_login` làm việc tương tự (lần gọi đầu trả mã, lần sau chờ bạn đồng ý), và
30
- `sb_login action:"logout"` đăng xuất máy.
31
-
32
32
  Nó biết Claude Code, Claude Desktop, Cursor, Windsurf, VS Code và Codex, và cài vào những
33
33
  cái nó tìm thấy. Chỉ định bằng `--client cursor,codex`, hoặc diễn thử với `--dry-run`. Một
34
34
  tuỳ chọn nó không biết sẽ bị **từ chối**, không phải bỏ qua — một cờ âm thầm không làm gì
package/dist/index.js CHANGED
@@ -2,12 +2,25 @@
2
2
  import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
3
3
  import { buildContext, createServer } from './server.js';
4
4
  import { runInstall } from './install/index.js';
5
+ import { pickLang } from './install/guided.js';
5
6
  import { pkgVersion } from './server.js';
6
7
  import { closeBrowser } from './vision/shoot.js';
7
8
  async function main() {
8
9
  // `sbuilder-mcp install` writes this server into the agent clients on this
9
10
  // machine and exits. Checked BEFORE the transport opens: an installer that
10
11
  // also spoke MCP on stdout would corrupt the protocol for whatever ran it.
12
+ // RUN BY HAND, NOT BY AN AGENT. A client always talks over a pipe; a person
13
+ // who typed `npx sbuilder-mcp` in a terminal would otherwise stare at a cursor
14
+ // that never moves. Tell them the one command they wanted.
15
+ if (process.stdin.isTTY && !process.argv[2]) {
16
+ const vi = pickLang() === 'vi';
17
+ console.error(vi
18
+ ? 'sbuilder-mcp là máy chủ MCP — agent AI (Claude Code, Cursor…) tự chạy nó.\n' +
19
+ 'Để kết nối máy này với Store Builder, chạy:\n\n npx -y sbuilder-mcp@latest install\n'
20
+ : 'sbuilder-mcp is an MCP server — your AI agent (Claude Code, Cursor…) runs it.\n' +
21
+ 'To connect this machine to Store Builder, run:\n\n npx -y sbuilder-mcp@latest install\n');
22
+ process.exit(0);
23
+ }
11
24
  if (process.argv[2] === 'install') {
12
25
  process.exit(await runInstall(process.argv.slice(3), { version: pkgVersion() }));
13
26
  }
@@ -0,0 +1,260 @@
1
+ import { createInterface } from 'node:readline/promises';
2
+ import { openBrowser, pollDevice, startDevice } from '../transport/device.js';
3
+ import { readPairSync, rotate, savePair } from '../transport/stored.js';
4
+ import { install, parseInstallArgs } from './index.js';
5
+ /**
6
+ * `npx -y sbuilder-mcp@latest install` — the whole setup, for a person who
7
+ * does not know what an MCP server, an API key or an env var is.
8
+ *
9
+ * ONE command, no flags required: it signs in through the browser (type the
10
+ * code, Approve), lets them pick the store by number, writes every agent client
11
+ * on the machine, and ends by saying what to do next. Flags still exist for the
12
+ * screen that hands out the command (`--api`, `--site`) and for scripts
13
+ * (`--token`, `--client`, `--dry-run`), but nobody has to type one.
14
+ */
15
+ /** Where a real merchant's store lives. Local dev passes --api. */
16
+ export const PROD_API = 'https://api.sbuilder.io.vn';
17
+ /** --lang, else the environment's locale; English when nothing says Vietnamese. */
18
+ export function pickLang(flag, env = process.env) {
19
+ const hint = flag ?? env.LC_ALL ?? env.LC_MESSAGES ?? env.LANG ?? Intl.DateTimeFormat().resolvedOptions().locale;
20
+ return /^vi/i.test(hint ?? '') ? 'vi' : 'en';
21
+ }
22
+ const M = {
23
+ vi: {
24
+ title: 'Kết nối Store Builder với agent AI trên máy này',
25
+ step: (n, what) => `\nBước ${n}/3 — ${what}`,
26
+ signIn: 'Đăng nhập',
27
+ pick: 'Chọn cửa hàng',
28
+ write: 'Cài vào agent',
29
+ already: (who) => ` ✔ Đã đăng nhập sẵn: ${who}`,
30
+ opened: (url) => ` Trang đăng nhập đã mở trong trình duyệt: ${url}`,
31
+ open: (url) => ` Mở trang này trong trình duyệt: ${url}`,
32
+ type: (code) => ` Gõ mã: ${code}`,
33
+ approve: (min) => ` Thấy mã trùng khớp thì bấm "Chấp thuận". Mã hết hạn sau ${min} phút.`,
34
+ waiting: ' Đang chờ bạn chấp thuận…',
35
+ signedIn: (who) => ` ✔ Đã đăng nhập: ${who}`,
36
+ denied: ' ✖ Bạn đã từ chối trên trình duyệt. Chưa cài gì cả.',
37
+ expired: ' ✖ Mã đã hết hạn. Chạy lại lệnh để lấy mã mới.',
38
+ noSites: ' Tài khoản chưa có cửa hàng nào — agent vẫn tạo được cửa hàng mới.',
39
+ oneSite: (name) => ` ✔ Cửa hàng: ${name}`,
40
+ choose: (n) => ` Gõ số cửa hàng agent sẽ làm việc (1–${n}), Enter để bỏ qua: `,
41
+ skipped: ' · Bỏ qua — agent sẽ hỏi cửa hàng khi cần, hoặc bạn bảo nó "chuyển sang cửa hàng …".',
42
+ given: (name) => ` ✔ Cửa hàng: ${name}`,
43
+ installed: (c) => ` ✔ ${c}`,
44
+ unchanged: (c) => ` · ${c} (đã cài sẵn)`,
45
+ preview: (c) => ` → ${c} (thử, chưa ghi)`,
46
+ failed: (c, why) => ` ✖ ${c}: ${why}`,
47
+ backup: (f) => ` bản cũ lưu ở ${f}`,
48
+ noClient: ' ✖ Không tìm thấy Claude Code, Claude Desktop, Cursor, Windsurf, VS Code hay Codex trên máy này. Cài một cái rồi chạy lại.',
49
+ done: (site) => `\nXong! Mở lại (khởi động lại) agent của bạn, rồi thử nói:\n "${site ? `Liệt kê các trang của cửa hàng ${site}` : 'Liệt kê các cửa hàng của tôi'}"\n` +
50
+ 'Đăng xuất máy này: bảo agent "đăng xuất sbuilder".',
51
+ },
52
+ en: {
53
+ title: 'Connect Store Builder to the AI agents on this machine',
54
+ step: (n, what) => `\nStep ${n}/3 — ${what}`,
55
+ signIn: 'Sign in',
56
+ pick: 'Choose a store',
57
+ write: 'Install into your agents',
58
+ already: (who) => ` ✔ Already signed in: ${who}`,
59
+ opened: (url) => ` The sign-in page is open in your browser: ${url}`,
60
+ open: (url) => ` Open this page in your browser: ${url}`,
61
+ type: (code) => ` Type the code: ${code}`,
62
+ approve: (min) => ` When the code matches, press "Approve". It expires in ${min} minutes.`,
63
+ waiting: ' Waiting for your approval…',
64
+ signedIn: (who) => ` ✔ Signed in: ${who}`,
65
+ denied: ' ✖ You denied it in the browser. Nothing was installed.',
66
+ expired: ' ✖ The code expired. Run the command again for a new one.',
67
+ noSites: ' This account has no store yet — the agent can still create one.',
68
+ oneSite: (name) => ` ✔ Store: ${name}`,
69
+ choose: (n) => ` Type the number of the store the agent works on (1–${n}), Enter to skip: `,
70
+ skipped: ' · Skipped — the agent asks when it needs one, or tell it "switch to store …".',
71
+ given: (name) => ` ✔ Store: ${name}`,
72
+ installed: (c) => ` ✔ ${c}`,
73
+ unchanged: (c) => ` · ${c} (already set up)`,
74
+ preview: (c) => ` → ${c} (dry run, nothing written)`,
75
+ failed: (c, why) => ` ✖ ${c}: ${why}`,
76
+ backup: (f) => ` previous file saved as ${f}`,
77
+ noClient: ' ✖ No Claude Code, Claude Desktop, Cursor, Windsurf, VS Code or Codex found on this machine. Install one and run this again.',
78
+ done: (site) => `\nDone! Restart your agent, then try saying:\n "${site ? `List the pages of the ${site} store` : 'List my stores'}"\n` +
79
+ 'To sign this machine out: tell the agent "sign out of sbuilder".',
80
+ },
81
+ };
82
+ const trim = (api) => api.replace(/\/+$/, '');
83
+ async function getJson(api, path, token, f) {
84
+ const res = await f(`${trim(api)}${path}`, { headers: { Authorization: `Bearer ${token}` } }).catch(() => null);
85
+ if (!res)
86
+ return { status: 0 };
87
+ return { status: res.status, data: res.ok ? (await res.json().catch(() => undefined)) : undefined };
88
+ }
89
+ /** The stored login's token and email when it still works (renewing it once if refused). */
90
+ async function storedLogin(api, f) {
91
+ let pair = readPairSync(api);
92
+ for (let attempt = 0; pair && attempt < 2; attempt++) {
93
+ const me = await getJson(api, '/api/auth/me', pair.accessToken, f);
94
+ if (me.status === 200)
95
+ return { token: pair.accessToken, who: me.data?.user?.email || '' };
96
+ if (me.status !== 401)
97
+ return undefined;
98
+ pair = await rotate(api, pair.accessToken, f).catch(() => undefined);
99
+ }
100
+ return undefined;
101
+ }
102
+ /**
103
+ * The browser sign-in, in this terminal. Reuses a login the machine already
104
+ * holds (`sb login`, an agent's sb_login). Returns the token, or undefined when
105
+ * the person denied it or let the code expire.
106
+ */
107
+ export async function deviceLogin(api, deps = {}) {
108
+ const t = M[deps.lang ?? 'en'];
109
+ const log = deps.log ?? ((l) => console.error(l));
110
+ const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
111
+ const f = deps.fetchImpl ?? fetch;
112
+ const held = await storedLogin(api, f);
113
+ if (held) {
114
+ log(t.already(held.who || api));
115
+ return held.token;
116
+ }
117
+ const s = await startDevice(api, deps.version ?? '0.0.0', f);
118
+ log((deps.open ?? openBrowser)(s.verificationUri) ? t.opened(s.verificationUri) : t.open(s.verificationUri));
119
+ log(t.type(s.userCode));
120
+ log(t.approve(Math.round(s.expiresIn / 60)));
121
+ log(t.waiting);
122
+ let interval = s.interval * 1000;
123
+ const deadline = Date.now() + s.expiresIn * 1000;
124
+ while (Date.now() < deadline) {
125
+ await sleep(interval);
126
+ // A dropped connection is not a refusal; anything else the server says is.
127
+ const r = await pollDevice(api, s.deviceCode, f).catch((err) => {
128
+ if (err instanceof TypeError)
129
+ return { state: 'pending' };
130
+ throw err;
131
+ });
132
+ if (r.state === 'approved') {
133
+ await savePair(api, r.pair);
134
+ const me = await getJson(api, '/api/auth/me', r.pair.accessToken, f);
135
+ log(t.signedIn(me.data?.user?.email || api));
136
+ return r.pair.accessToken;
137
+ }
138
+ if (r.state === 'slow')
139
+ interval += 5000;
140
+ if (r.state === 'denied') {
141
+ log(t.denied);
142
+ return undefined;
143
+ }
144
+ if (r.state === 'expired')
145
+ break;
146
+ }
147
+ log(t.expired);
148
+ return undefined;
149
+ }
150
+ /** Pick the store: the one named, the only one, or the person's choice by number. */
151
+ async function chooseSite(api, token, opts, deps, log) {
152
+ const t = M[deps.lang ?? 'en'];
153
+ const listed = await getJson(api, '/api/sites', token, deps.fetchImpl ?? fetch);
154
+ const sites = listed.data?.sites ?? [];
155
+ if (opts.site) {
156
+ const named = sites.find((s) => s.id === opts.site);
157
+ if (named && !opts.siteName)
158
+ opts.siteName = named.name;
159
+ log(t.given(opts.siteName ?? opts.site));
160
+ return;
161
+ }
162
+ if (!sites.length)
163
+ return log(t.noSites);
164
+ if (sites.length === 1) {
165
+ opts.site = sites[0].id;
166
+ opts.siteName = sites[0].name;
167
+ return log(t.oneSite(sites[0].name));
168
+ }
169
+ if (!deps.ask)
170
+ return log(t.skipped);
171
+ sites.forEach((s, i) => log(` ${String(i + 1).padStart(2)}. ${s.name}`));
172
+ const answer = (await deps.ask(t.choose(sites.length))).trim();
173
+ const picked = sites[Number(answer) - 1];
174
+ if (!answer || !picked)
175
+ return log(t.skipped);
176
+ opts.site = picked.id;
177
+ opts.siteName = picked.name;
178
+ log(t.given(picked.name));
179
+ }
180
+ function report(results, opts, lang, log) {
181
+ const t = M[lang];
182
+ if (!results.length) {
183
+ log(t.noClient);
184
+ return 1;
185
+ }
186
+ for (const r of results) {
187
+ if (opts.dryRun)
188
+ log(t.preview(r.client));
189
+ else if (r.status === 'installed')
190
+ log(t.installed(r.client));
191
+ else if (r.status === 'unchanged')
192
+ log(t.unchanged(r.client));
193
+ else
194
+ log(t.failed(r.client, r.reason ?? ''));
195
+ if (r.backup)
196
+ log(t.backup(r.backup));
197
+ }
198
+ return opts.dryRun || results.some((r) => r.status !== 'skipped') ? 0 : 1;
199
+ }
200
+ /** Interactive question on the terminal, or undefined when there is none. */
201
+ function terminalAsk() {
202
+ if (!process.stdin.isTTY)
203
+ return undefined;
204
+ return async (q) => {
205
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
206
+ try {
207
+ return await rl.question(q);
208
+ }
209
+ finally {
210
+ rl.close();
211
+ }
212
+ };
213
+ }
214
+ /**
215
+ * The CLI entry. With a key (--token) or a password it installs that, as
216
+ * before. Otherwise — the default — it signs in through the browser.
217
+ */
218
+ export async function runInstall(argv, deps = {}) {
219
+ const log = deps.log ?? ((l) => console.error(l));
220
+ const parsed = parseInstallArgs(argv);
221
+ if ('error' in parsed) {
222
+ log(parsed.error);
223
+ return 1;
224
+ }
225
+ const lang = deps.lang ?? pickLang(parsed.lang);
226
+ const t = M[lang];
227
+ const opts = { ...parsed.opts, api: parsed.opts.api ?? PROD_API, home: deps.home };
228
+ const viaLogin = !opts.token && !(opts.email && opts.password);
229
+ opts.login = viaLogin;
230
+ const d = { ...deps, lang, log, ask: 'ask' in deps ? deps.ask : terminalAsk() };
231
+ log(t.title);
232
+ if (viaLogin && !opts.dryRun) {
233
+ log(t.step(1, t.signIn));
234
+ let token;
235
+ try {
236
+ token = await deviceLogin(opts.api, d);
237
+ }
238
+ catch (err) {
239
+ log(` ✖ ${err.message}`);
240
+ return 1;
241
+ }
242
+ if (!token)
243
+ return 1;
244
+ log(t.step(2, t.pick));
245
+ await chooseSite(opts.api, token, opts, d, log);
246
+ }
247
+ log(t.step(3, t.write));
248
+ let results;
249
+ try {
250
+ results = install(opts);
251
+ }
252
+ catch (err) {
253
+ log(` ✖ ${err.message}`);
254
+ return 1;
255
+ }
256
+ const code = report(results, opts, lang, log);
257
+ if (code === 0 && !opts.dryRun)
258
+ log(t.done(opts.siteName));
259
+ return code;
260
+ }
@@ -1,7 +1,5 @@
1
1
  import { targets, detected } from './paths.js';
2
2
  import { mergeInto } from './write.js';
3
- import { openBrowser, pollDevice, startDevice } from '../transport/device.js';
4
- import { readPairSync, rotate, savePair } from '../transport/stored.js';
5
3
  /** The name the server appears under in every client. */
6
4
  export const SERVER_NAME = 'sbuilder';
7
5
  /**
@@ -30,6 +28,7 @@ const FLAGS = [
30
28
  '--password',
31
29
  '--client',
32
30
  '--login',
31
+ '--lang',
33
32
  '--dry-run',
34
33
  ];
35
34
  /** Flags that take no value. */
@@ -59,7 +58,10 @@ export function buildEntry(opts, pkg = 'sbuilder-mcp') {
59
58
  env.SB_EMAIL = opts.email;
60
59
  if (!opts.token && !opts.login && opts.password)
61
60
  env.SB_PASSWORD = opts.password;
62
- return { command: 'npx', args: ['-y', pkg], env };
61
+ // A login install leans on the stored-login support of 0.109+; an npx cache
62
+ // holding an older copy would start a server that never sees the login. A
63
+ // key install works on any version, so it keeps the cached start.
64
+ return { command: 'npx', args: ['-y', opts.login && !opts.token ? `${pkg}@latest` : pkg], env };
63
65
  }
64
66
  export function chooseTargets(opts) {
65
67
  const all = targets(opts.home);
@@ -104,7 +106,8 @@ export function install(opts) {
104
106
  });
105
107
  }
106
108
  /** `sbuilder-mcp install --token wbk_… --api https://…` */
107
- export function runInstallCli(argv) {
109
+ /** The flags, or the sentence refusing an unknown one. */
110
+ export function parseInstallArgs(argv) {
108
111
  const get = (flag) => {
109
112
  const i = argv.indexOf(flag);
110
113
  return i >= 0 ? argv[i + 1] : undefined;
@@ -123,8 +126,7 @@ export function runInstallCli(argv) {
123
126
  }
124
127
  const unknown = argv.filter((a, i) => a.startsWith('--') && !taken.has(i));
125
128
  if (unknown.length) {
126
- console.error(`sbuilder: unknown option(s) ${unknown.join(', ')}. Known: ${FLAGS.join(', ')}.`);
127
- return 1;
129
+ return { error: `sbuilder: unknown option(s) ${unknown.join(', ')}. Known: ${FLAGS.join(', ')}.` };
128
130
  }
129
131
  const opts = {
130
132
  token: get('--token') ?? process.env.SB_TOKEN,
@@ -137,6 +139,15 @@ export function runInstallCli(argv) {
137
139
  login: argv.includes('--login'),
138
140
  dryRun: argv.includes('--dry-run'),
139
141
  };
142
+ return { opts, lang: get('--lang') };
143
+ }
144
+ export function runInstallCli(argv, extra = {}) {
145
+ const parsed = parseInstallArgs(argv);
146
+ if ('error' in parsed) {
147
+ console.error(parsed.error);
148
+ return 1;
149
+ }
150
+ const opts = { ...parsed.opts, ...extra };
140
151
  if (!opts.token && !(opts.email && opts.password) && !opts.login) {
141
152
  console.error('sbuilder: nothing to install with.\n' +
142
153
  ' Sign in through the browser (the whole account, no key to copy):\n' +
@@ -183,87 +194,4 @@ export function runInstallCli(argv) {
183
194
  return 0;
184
195
  return results.some((r) => r.status === 'installed' || r.status === 'unchanged') ? 0 : 1;
185
196
  }
186
- /** The stored login's email when it still works (renewing it once if refused), else undefined. */
187
- async function storedUser(api, f) {
188
- let pair = readPairSync(api);
189
- for (let attempt = 0; pair && attempt < 2; attempt++) {
190
- const res = await f(`${api.replace(/\/+$/, '')}/api/auth/me`, {
191
- headers: { Authorization: `Bearer ${pair.accessToken}` },
192
- }).catch(() => null);
193
- if (res?.ok) {
194
- const me = (await res.json().catch(() => ({})));
195
- return me.user?.email || 'this account';
196
- }
197
- if (res?.status !== 401)
198
- return undefined;
199
- pair = await rotate(api, pair.accessToken, f).catch(() => undefined);
200
- }
201
- return undefined;
202
- }
203
- /**
204
- * `install --login`: the browser sign-in `sb login` does, in this terminal.
205
- * Reuses a login the machine already holds. Returns false when it did not sign in.
206
- */
207
- export async function deviceLogin(api, deps = {}) {
208
- const log = deps.log ?? ((l) => console.error(l));
209
- const sleep = deps.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
210
- const f = deps.fetchImpl ?? fetch;
211
- const already = await storedUser(api, f);
212
- if (already) {
213
- log(`✔ Already signed in as ${already} on ${api}.`);
214
- return true;
215
- }
216
- const s = await startDevice(api, deps.version ?? '0.0.0', f);
217
- log('Sign in to Store Builder');
218
- log(` 1. Open ${s.verificationUri}`);
219
- log(` 2. Type ${s.userCode}`);
220
- log(` 3. Check the page shows the same code, then Approve. It expires in ${Math.round(s.expiresIn / 60)} minutes.`);
221
- if ((deps.open ?? openBrowser)(s.verificationUri))
222
- log('Opened the page in your browser. Waiting for approval…');
223
- let interval = s.interval * 1000;
224
- const deadline = Date.now() + s.expiresIn * 1000;
225
- while (Date.now() < deadline) {
226
- await sleep(interval);
227
- // A dropped connection is not a refusal; anything else the server says is.
228
- const r = await pollDevice(api, s.deviceCode, f).catch((err) => {
229
- if (err instanceof TypeError)
230
- return { state: 'pending' };
231
- throw err;
232
- });
233
- if (r.state === 'approved') {
234
- await savePair(api, r.pair);
235
- log('✔ Signed in. The login is kept on this machine (shared with the sb CLI).');
236
- return true;
237
- }
238
- if (r.state === 'slow')
239
- interval += 5000;
240
- if (r.state === 'denied') {
241
- log('✖ The sign-in was denied in the browser. Nothing was installed.');
242
- return false;
243
- }
244
- if (r.state === 'expired')
245
- break;
246
- }
247
- log('✖ The code expired before it was approved. Run the command again.');
248
- return false;
249
- }
250
- /** The CLI entry: signs in first when --login is given, then writes the clients. */
251
- export async function runInstall(argv, deps = {}) {
252
- if (argv.includes('--login') && !argv.includes('--dry-run')) {
253
- const i = argv.indexOf('--api');
254
- const api = (i >= 0 ? argv[i + 1] : undefined) ?? process.env.SB_API;
255
- if (!api) {
256
- console.error('sbuilder: --login needs --api https://your-host (the platform to sign in to).');
257
- return 1;
258
- }
259
- try {
260
- if (!(await deviceLogin(api, deps)))
261
- return 1;
262
- }
263
- catch (err) {
264
- console.error(err.message);
265
- return 1;
266
- }
267
- }
268
- return runInstallCli(argv);
269
- }
197
+ export { deviceLogin, runInstall, PROD_API } from './guided.js';
@@ -167,6 +167,8 @@ export function registerLoginTools(server, ctx, version) {
167
167
  server.registerTool('sb_site_use', {
168
168
  description: 'Switch the site every tool defaults to (needs the sb_login account login).',
169
169
  inputSchema: { site_id: z.string() },
170
- annotations: { readOnlyHint: true },
170
+ // NOT read-only: it moves where every later write lands, so a client that
171
+ // auto-approves read-only tools must still ask before it.
172
+ annotations: { readOnlyHint: false, idempotentHint: true },
171
173
  }, async ({ site_id }) => text(await useSite(ctx, site_id)));
172
174
  }
@@ -7,7 +7,7 @@ import { spawn } from 'node:child_process';
7
7
  * that pre-fills it is a link a phisher can send.
8
8
  */
9
9
  /** What the approval page shows as the asking app — on the server's allowlist
10
- * (web_builder KnownDeviceClients) from v1.0.277; older servers say "unknown app". */
10
+ * (web_builder KnownDeviceClients) from v1.0.278; older servers say "unknown app". */
11
11
  export const DEVICE_CLIENT = 'sbuilder-mcp';
12
12
  const trim = (base) => base.replace(/\/+$/, '');
13
13
  async function post(base, path, body, fetchImpl) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "sbuilder-mcp",
3
- "version": "0.109.0",
3
+ "version": "0.110.0",
4
4
  "description": "MCP server that designs and operates a Store Builder site — pages, data, theme and publish — through the platform's own API and live-edit protocol.",
5
5
  "mcpName": "io.github.vuluu2k/sbuilder-mcp",
6
6
  "type": "module",