sellwavy-cli 0.0.0-stage → 0.1.1

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/lib/mcp.mjs ADDED
@@ -0,0 +1,383 @@
1
+ import readline from 'node:readline'
2
+ import { VERSION } from './version.mjs'
3
+ import { EDITOR, HOOKS, MCP_INSTRUCTIONS, RULES } from './guide.mjs'
4
+ import {
5
+ GLOBAL_KEYS, PAGES, PAGE_NAMES, findProduct, getSite, lintSite, normalizeKey, pageOf, productBody,
6
+ removeSection, reorderSections, resolveStore, saveSite, upsertSection, uploadMedia,
7
+ } from './core.mjs'
8
+
9
+ /**
10
+ * `sellwavy mcp`: the store as tools for an AI agent, over the Model Context
11
+ * Protocol on stdin/stdout. Connect it to Claude Code with
12
+ *
13
+ * claude mcp add sellwavy -- npx -y sellwavy-cli mcp
14
+ *
15
+ * or the same command in Cursor, Windsurf, Codex or Claude Desktop's MCP
16
+ * settings. It signs in with the key from `sellwavy login` (or
17
+ * SELLWAVY_TOKEN), and works on the folder's linked store, the --store
18
+ * given, or the store named in each call.
19
+ *
20
+ * stdout carries protocol messages only; anything else goes to stderr.
21
+ */
22
+
23
+ const PROTOCOL_VERSIONS = ['2025-06-18', '2025-03-26', '2024-11-05']
24
+
25
+ const STORE = { type: 'string', description: 'Store id or subdomain. Optional when only one store is available or the folder is linked.' }
26
+ const PAGE = { type: 'string', enum: ['global', ...PAGES], description: 'Which page: "global" is the shared header and footer.' }
27
+
28
+ const TOOLS = [
29
+ {
30
+ name: 'sellwavy_guide',
31
+ description: 'How Sellwavy store pages are built: the data-sw-* hooks for live products, cart and logo, and the rules the server enforces. Read once before writing sections.',
32
+ inputSchema: { type: 'object', properties: {} },
33
+ annotations: { readOnlyHint: true },
34
+ },
35
+ {
36
+ name: 'list_stores',
37
+ description: 'The stores this account can work on, with their live and editor addresses.',
38
+ inputSchema: { type: 'object', properties: {} },
39
+ annotations: { readOnlyHint: true },
40
+ },
41
+ {
42
+ name: 'get_pages',
43
+ description: 'The store’s pages as HTML sections ({ page, key, label, html }), live now. Optionally just one page.',
44
+ inputSchema: { type: 'object', properties: { store: STORE, page: PAGE } },
45
+ annotations: { readOnlyHint: true },
46
+ },
47
+ {
48
+ name: 'save_section',
49
+ description: 'Adds or replaces one section of a page (HTML + Tailwind, using the hooks from sellwavy_guide). Goes live at once and stays editable in the owner’s visual editor. New sections go at the end of the page unless before/after names a section.',
50
+ inputSchema: {
51
+ type: 'object',
52
+ properties: {
53
+ store: STORE,
54
+ page: PAGE,
55
+ key: { type: 'string', description: 'Short stable name, unique on the page: hero, featured, faq. "header" and "footer" are the shared ones.' },
56
+ label: { type: 'string', description: 'Name the owner sees in the editor, e.g. "Hero".' },
57
+ html: { type: 'string', description: 'The section: one HTML fragment, Tailwind classes, no scripts/styles/forms.' },
58
+ before: { type: 'string', description: 'Put it before this section key.' },
59
+ after: { type: 'string', description: 'Put it after this section key.' },
60
+ },
61
+ required: ['page', 'key', 'html'],
62
+ },
63
+ },
64
+ {
65
+ name: 'remove_section',
66
+ description: 'Removes one section from a page. Live at once.',
67
+ inputSchema: { type: 'object', properties: { store: STORE, page: PAGE, key: { type: 'string' } }, required: ['page', 'key'] },
68
+ annotations: { destructiveHint: true },
69
+ },
70
+ {
71
+ name: 'reorder_sections',
72
+ description: 'Puts a page’s sections in the order given (keys not listed keep their place after them).',
73
+ inputSchema: {
74
+ type: 'object',
75
+ properties: { store: STORE, page: { type: 'string', enum: PAGES }, keys: { type: 'array', items: { type: 'string' } } },
76
+ required: ['page', 'keys'],
77
+ },
78
+ },
79
+ {
80
+ name: 'upload_media',
81
+ description: 'Uploads a photo or video to the store’s media library from a local file path or an https URL, and returns its address to use in <img src> or <video src>. It appears in the owner’s media library.',
82
+ inputSchema: { type: 'object', properties: { store: STORE, source: { type: 'string', description: 'Local file path or https:// URL.' } }, required: ['source'] },
83
+ },
84
+ {
85
+ name: 'list_media',
86
+ description: 'Photos and videos in the store’s media library.',
87
+ inputSchema: { type: 'object', properties: { store: STORE } },
88
+ annotations: { readOnlyHint: true },
89
+ },
90
+ {
91
+ name: 'list_products',
92
+ description: 'The store’s products: id, title, price (cents), stock, status, category.',
93
+ inputSchema: { type: 'object', properties: { store: STORE } },
94
+ annotations: { readOnlyHint: true },
95
+ },
96
+ {
97
+ name: 'get_product',
98
+ description: 'One product in full, by id, slug or exact title.',
99
+ inputSchema: { type: 'object', properties: { store: STORE, product: { type: 'string' } }, required: ['product'] },
100
+ annotations: { readOnlyHint: true },
101
+ },
102
+ {
103
+ name: 'create_product',
104
+ description: 'Adds a product. Price in the store’s currency (19.99). Images: local paths or URLs, uploaded to the media library.',
105
+ inputSchema: {
106
+ type: 'object',
107
+ properties: {
108
+ store: STORE,
109
+ title: { type: 'string' },
110
+ price: { type: 'number', description: 'In the store’s currency, e.g. 19.99.' },
111
+ description: { type: 'string' },
112
+ inventory: { type: 'integer', description: 'Units in stock.' },
113
+ category: { type: 'string' },
114
+ status: { type: 'string', enum: ['active', 'draft'] },
115
+ images: { type: 'array', items: { type: 'string' } },
116
+ tags: { type: 'array', items: { type: 'string' } },
117
+ },
118
+ required: ['title', 'price'],
119
+ },
120
+ },
121
+ {
122
+ name: 'update_product',
123
+ description: 'Changes a product. Only the fields given change. Price in the store’s currency.',
124
+ inputSchema: {
125
+ type: 'object',
126
+ properties: {
127
+ store: STORE,
128
+ product: { type: 'string', description: 'Id, slug or exact title.' },
129
+ title: { type: 'string' }, price: { type: 'number' }, description: { type: 'string' },
130
+ inventory: { type: 'integer' }, category: { type: 'string' }, status: { type: 'string', enum: ['active', 'draft'] },
131
+ images: { type: 'array', items: { type: 'string' }, description: 'Replaces all photos.' },
132
+ tags: { type: 'array', items: { type: 'string' } },
133
+ },
134
+ required: ['product'],
135
+ },
136
+ },
137
+ {
138
+ name: 'delete_product',
139
+ description: 'Deletes a product for good.',
140
+ inputSchema: { type: 'object', properties: { store: STORE, product: { type: 'string' } }, required: ['product'] },
141
+ annotations: { destructiveHint: true },
142
+ },
143
+ {
144
+ name: 'list_orders',
145
+ description: 'Recent orders (up to 300): id, total (cents), status, customer, items.',
146
+ inputSchema: { type: 'object', properties: { store: STORE, status: { type: 'string', enum: ['PENDING', 'PAID', 'CANCELLED', 'REFUNDED'] } } },
147
+ annotations: { readOnlyHint: true },
148
+ },
149
+ {
150
+ name: 'get_order',
151
+ description: 'One order in full: customer, address, items, payment and shipping.',
152
+ inputSchema: { type: 'object', properties: { store: STORE, order: { type: 'string' } }, required: ['order'] },
153
+ annotations: { readOnlyHint: true },
154
+ },
155
+ {
156
+ name: 'ship_order',
157
+ description: 'Marks an order shipped and emails the shopper once, with the tracking info if given.',
158
+ inputSchema: { type: 'object', properties: { store: STORE, order: { type: 'string' }, tracking: { type: 'string' } }, required: ['order'] },
159
+ },
160
+ {
161
+ name: 'mark_order_paid',
162
+ description: 'Records payment for an order (cash on delivery, bank transfer).',
163
+ inputSchema: { type: 'object', properties: { store: STORE, order: { type: 'string' } }, required: ['order'] },
164
+ },
165
+ {
166
+ name: 'get_theme',
167
+ description: 'The store’s design settings: colours, fonts, logo, and whether its AI-built pages are on.',
168
+ inputSchema: { type: 'object', properties: { store: STORE } },
169
+ annotations: { readOnlyHint: true },
170
+ },
171
+ {
172
+ name: 'update_theme',
173
+ description: 'Changes design settings, e.g. { "primaryColor": "#111111", "font": "sans", "logoUrl": "https://..." }. Pages are changed with the section tools, not here.',
174
+ inputSchema: { type: 'object', properties: { store: STORE, settings: { type: 'object' } }, required: ['settings'] },
175
+ },
176
+ {
177
+ name: 'store_api',
178
+ description: 'Calls any of the store’s API routes for what the other tools do not cover (categories, discounts, shipping, pages, policies, settings, customers, reviews). Path is relative to /api/stores/<store>, e.g. "/discounts".',
179
+ inputSchema: {
180
+ type: 'object',
181
+ properties: {
182
+ store: STORE,
183
+ method: { type: 'string', enum: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'] },
184
+ path: { type: 'string' },
185
+ body: { type: 'object' },
186
+ },
187
+ required: ['method', 'path'],
188
+ },
189
+ },
190
+ ]
191
+
192
+ function omit(obj, keys) {
193
+ return Object.fromEntries(Object.entries(obj).filter(([k]) => !keys.includes(k)))
194
+ }
195
+
196
+ function guideText() {
197
+ return [
198
+ '# Building a Sellwavy store',
199
+ `Pages: ${PAGES.map(p => `${p} (${PAGE_NAMES[p]})`).join(', ')}, plus the shared header and footer (page "global", keys "header" and "footer"). Each page is a list of sections; each section is one HTML fragment. Checkout, cart and account pages are Sellwavy’s own.`,
200
+ 'Workflow: get_pages to see what is there; save_section for each new or changed section (header and footer first for a new store); upload_media for any photo or video, then use the returned address. Every save is live at once. If get_pages shows aiDesignOn false, the first save switches the store from its standard design to these pages: build header, footer and home first and ask the owner before saving.',
201
+ HOOKS,
202
+ RULES,
203
+ EDITOR,
204
+ ].join('\n\n')
205
+ }
206
+
207
+ export async function runMcp({ api, defaultStore, project }) {
208
+ let meCache = null
209
+ async function store(wanted) {
210
+ if (!meCache || Date.now() - meCache.at > 60_000 || wanted) {
211
+ const r = await resolveStore(api, { wanted: wanted || defaultStore, project })
212
+ if (!wanted) meCache = { at: Date.now(), r }
213
+ return r.store
214
+ }
215
+ return meCache.r.store
216
+ }
217
+
218
+ async function sectionChange(args, change) {
219
+ const s = await store(args.store)
220
+ const { sections } = await getSite(api, s.id)
221
+ const next = change(sections)
222
+ const saved = await saveSite(api, s.id, next)
223
+ return { store: s, saved: saved.sections }
224
+ }
225
+
226
+ const handlers = {
227
+ sellwavy_guide: async () => guideText(),
228
+ list_stores: async () => (await api.get('/api/cli/me')).stores,
229
+ get_pages: async a => {
230
+ const s = await store(a.store)
231
+ const site = await getSite(api, s.id)
232
+ const sections = a.page ? site.sections.filter(x => pageOf(x) === a.page) : site.sections
233
+ return { store: s.subdomain, aiDesignOn: site.aiDesign, editorUrl: s.editorUrl, sections }
234
+ },
235
+ save_section: async a => {
236
+ const { store: s, saved } = await sectionChange(a, list => upsertSection(list, a))
237
+ const key = normalizeKey(a.key)
238
+ const page = GLOBAL_KEYS.includes(key) ? 'global' : a.page
239
+ const kept = saved.find(x => x.key === key && pageOf(x) === page)
240
+ const sent = String(a.html).trim()
241
+ return {
242
+ saved: kept ? { page, key: kept.key, label: kept.label } : null,
243
+ live: `${s.url}${{ products: '/products', about: '/about', contact: '/contact' }[page] ?? ''}`,
244
+ editor: s.editorUrl,
245
+ warnings: lintSite([{ key, page, html: sent }]).map(w => w.problem),
246
+ ...(kept && kept.html !== sent ? { note: 'The server cleaned this section; this is what was kept.', html: kept.html } : {}),
247
+ }
248
+ },
249
+ remove_section: async a => {
250
+ await sectionChange(a, list => removeSection(list, { page: a.page, key: a.key }))
251
+ return { removed: `${a.page}/${normalizeKey(a.key)}` }
252
+ },
253
+ reorder_sections: async a => {
254
+ const { saved } = await sectionChange(a, list => reorderSections(list, { page: a.page, keys: a.keys ?? [] }))
255
+ return { page: a.page, order: saved.filter(x => pageOf(x) === a.page).map(x => x.key) }
256
+ },
257
+ upload_media: async a => {
258
+ const s = await store(a.store)
259
+ const m = await uploadMedia(api, s.id, a.source)
260
+ return { url: m.url, type: m.type, id: m.id }
261
+ },
262
+ list_media: async a => {
263
+ const s = await store(a.store)
264
+ return (await api.get(`/api/stores/${s.id}/media`)).map(m => ({ id: m.id, url: m.url, type: m.type, filename: m.filename, width: m.width, height: m.height }))
265
+ },
266
+ list_products: async a => {
267
+ const s = await store(a.store)
268
+ return { currency: s.currency, products: await api.get(`/api/stores/${s.id}/products`) }
269
+ },
270
+ get_product: async a => {
271
+ const s = await store(a.store)
272
+ const p = await findProduct(api, s.id, a.product)
273
+ return (await api.get(`/api/stores/${s.id}/products/${p.id}`)).product
274
+ },
275
+ create_product: async a => {
276
+ const s = await store(a.store)
277
+ return api.post(`/api/stores/${s.id}/products`, await productBody(api, s.id, a))
278
+ },
279
+ update_product: async a => {
280
+ const s = await store(a.store)
281
+ const p = await findProduct(api, s.id, a.product)
282
+ const fields = omit(a, ['product', 'store'])
283
+ return (await api.patch(`/api/stores/${s.id}/products/${p.id}`, await productBody(api, s.id, fields, { partial: true }))).product
284
+ },
285
+ delete_product: async a => {
286
+ const s = await store(a.store)
287
+ const p = await findProduct(api, s.id, a.product)
288
+ await api.del(`/api/stores/${s.id}/products/${p.id}`)
289
+ return { deleted: p.title }
290
+ },
291
+ list_orders: async a => {
292
+ const s = await store(a.store)
293
+ const list = await api.get(`/api/stores/${s.id}/orders`)
294
+ return { currency: s.currency, orders: a.status ? list.filter(o => o.status === a.status) : list }
295
+ },
296
+ get_order: async a => {
297
+ const s = await store(a.store)
298
+ return api.get(`/api/stores/${s.id}/orders/${encodeURIComponent(a.order)}`)
299
+ },
300
+ ship_order: async a => {
301
+ const s = await store(a.store)
302
+ return api.post(`/api/stores/${s.id}/orders/${encodeURIComponent(a.order)}/ship`, { trackingInfo: a.tracking ?? '' })
303
+ },
304
+ mark_order_paid: async a => {
305
+ const s = await store(a.store)
306
+ return api.post(`/api/stores/${s.id}/orders/${encodeURIComponent(a.order)}/mark-paid`, {})
307
+ },
308
+ get_theme: async a => {
309
+ const s = await store(a.store)
310
+ const t = (await api.get(`/api/stores/${s.id}/theme`)) ?? {}
311
+ return omit(t, ['aiSections', 'id', 'storeId'])
312
+ },
313
+ update_theme: async a => {
314
+ const s = await store(a.store)
315
+ const settings = omit(a.settings ?? {}, ['aiSections'])
316
+ const t = await api.post(`/api/stores/${s.id}/theme`, settings)
317
+ return Object.fromEntries(Object.keys(settings).map(k => [k, t?.[k]]))
318
+ },
319
+ store_api: async a => {
320
+ const path = String(a.path)
321
+ const full = path.startsWith('/api/') ? path : `/api/stores/${(await store(a.store)).id}${path.startsWith('/') ? path : `/${path}`}`
322
+ return api.request(a.method, full, a.method === 'GET' || a.method === 'DELETE' ? undefined : (a.body ?? {}))
323
+ },
324
+ }
325
+
326
+ const send = msg => process.stdout.write(JSON.stringify(msg) + '\n')
327
+
328
+ async function handle(msg) {
329
+ const { id, method, params } = msg ?? {}
330
+ const isRequest = id !== undefined && id !== null
331
+ try {
332
+ switch (method) {
333
+ case 'initialize': {
334
+ const asked = params?.protocolVersion
335
+ return isRequest && send({
336
+ jsonrpc: '2.0',
337
+ id,
338
+ result: {
339
+ protocolVersion: PROTOCOL_VERSIONS.includes(asked) ? asked : PROTOCOL_VERSIONS[0],
340
+ capabilities: { tools: { listChanged: false } },
341
+ serverInfo: { name: 'sellwavy', title: 'Sellwavy', version: VERSION },
342
+ instructions: MCP_INSTRUCTIONS,
343
+ },
344
+ })
345
+ }
346
+ case 'ping':
347
+ return isRequest && send({ jsonrpc: '2.0', id, result: {} })
348
+ case 'tools/list':
349
+ return isRequest && send({ jsonrpc: '2.0', id, result: { tools: TOOLS } })
350
+ case 'tools/call': {
351
+ const handler = handlers[params?.name]
352
+ if (!handler) return send({ jsonrpc: '2.0', id, error: { code: -32602, message: `Unknown tool: ${params?.name}` } })
353
+ try {
354
+ const out = await handler(params.arguments ?? {})
355
+ const text = typeof out === 'string' ? out : JSON.stringify(out, null, 2)
356
+ return send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text }] } })
357
+ } catch (err) {
358
+ return send({ jsonrpc: '2.0', id, result: { content: [{ type: 'text', text: err?.message || String(err) }], isError: true } })
359
+ }
360
+ }
361
+ default:
362
+ // Notifications (initialized, cancelled) need no answer.
363
+ if (isRequest) send({ jsonrpc: '2.0', id, error: { code: -32601, message: `Method not found: ${method}` } })
364
+ }
365
+ } catch (err) {
366
+ if (isRequest) send({ jsonrpc: '2.0', id, error: { code: -32603, message: err?.message || 'Internal error' } })
367
+ }
368
+ }
369
+
370
+ process.stderr.write(`sellwavy mcp ${VERSION}: ready on stdio (${api.host})\n`)
371
+ const rl = readline.createInterface({ input: process.stdin, crlfDelay: Infinity })
372
+ rl.on('line', line => {
373
+ if (!line.trim()) return
374
+ let msg
375
+ try {
376
+ msg = JSON.parse(line)
377
+ } catch {
378
+ return send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } })
379
+ }
380
+ for (const m of Array.isArray(msg) ? msg : [msg]) handle(m)
381
+ })
382
+ await new Promise(resolve => rl.on('close', resolve))
383
+ }
@@ -0,0 +1,52 @@
1
+ // Types for sections.mjs, which the dashboard's code editor imports.
2
+
3
+ export type AiPage = 'home' | 'products' | 'product' | 'about' | 'contact'
4
+ export type SectionPage = AiPage | 'global'
5
+
6
+ export interface Section {
7
+ key: string
8
+ label: string
9
+ html: string
10
+ page?: string
11
+ }
12
+
13
+ export interface SectionFile {
14
+ rel: string
15
+ section: Section
16
+ page: SectionPage
17
+ }
18
+
19
+ export interface SiteDiff {
20
+ added: string[]
21
+ removed: string[]
22
+ changed: string[]
23
+ reordered: boolean
24
+ }
25
+
26
+ export declare const PAGES: AiPage[]
27
+ export declare const PAGE_NAMES: Record<SectionPage, string>
28
+ export declare const GLOBAL_KEYS: string[]
29
+ export declare const MAX_SECTIONS: number
30
+ export declare const MAX_HTML: number
31
+
32
+ export declare function normalizeKey(key: unknown): string
33
+ export declare function pageOf(s: { key: string; page?: string }): SectionPage
34
+ export declare function labelFor(key: string): string
35
+ export declare function sectionId(s: { key: string; page?: string }): string
36
+ export declare function normalizeSections(input: unknown): Section[]
37
+ export declare function orderSections<T extends { key: string; page?: string }>(sections: T[]): T[]
38
+ export declare function sameSite(a: Section[], b: Section[]): boolean
39
+ export declare function diffSections(before: Section[], after: Section[]): SiteDiff
40
+ export declare function mergeSite(
41
+ base: Section[],
42
+ local: Section[],
43
+ remote: Section[],
44
+ options?: { prefer?: 'local' | 'remote' },
45
+ ): { sections: Section[]; conflicts: string[]; fromRemote: string[] }
46
+ export declare function lintSection(s: Section): string[]
47
+ export declare function lintSite(sections: Section[]): { section: string; problem: string }[]
48
+ export declare function fileContent(s: Section): string
49
+ export declare function parseSectionFile(text: string, key: string): { label: string; html: string }
50
+ export declare function keyFromFileName(name: string): string
51
+ export declare function sectionFiles(sections: Section[]): SectionFile[]
52
+ export declare function sectionsFromFiles(files: Record<string, string>): { sections: Section[]; warnings: string[] }