@tanqory/theme-mcp 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Tanqory
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,54 @@
1
- # Temporary Holding Version
1
+ # @tanqory/theme-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Build a Tanqory store theme with any AI client, on your own machine. Two commands:
4
+
5
+ - `theme-mcp`: a local MCP server (stdio) with the Tanqory theme tools;
6
+ - `tanqory-theme`: a CLI, `init | validate | dev | login | themes | pull | push | publish | skill | mcp`.
7
+
8
+ Whatever the AI or other tools (an image generator) produce, the result is a standard Tanqory theme: the content of the
9
+ Nova V3 base theme, checked by `@tanqory/theme-standard`, the same validator the Tanqory cloud runs before it saves a
10
+ draft or publishes.
11
+
12
+ ## Use it from an AI client
13
+
14
+ Claude Code:
15
+
16
+ ```sh
17
+ claude mcp add tanqory-theme -- npx -y @tanqory/theme-mcp
18
+ npx -y -p @tanqory/theme-mcp tanqory-theme skill # the Tanqory Theme Skill in .claude/skills
19
+ ```
20
+
21
+ Any client that runs local MCP servers (Claude Desktop, and others), in its MCP configuration:
22
+
23
+ ```json
24
+ { "mcpServers": { "tanqory-theme": { "command": "npx", "args": ["-y", "@tanqory/theme-mcp"], "env": { "TANQORY_MCP_URL": "https://api.<root>/v1/mcp" } } } }
25
+ ```
26
+
27
+ The tools that read or change the store (`theme_get`, `theme_files`, `theme_push_draft`, `theme_preview_url`,
28
+ `theme_upload_asset`, `theme_publish`) need a sign-in once: `npx -y -p @tanqory/theme-mcp tanqory-theme login` opens the
29
+ browser, you sign in and choose the store. They use the cloud server named by `TANQORY_MCP_URL`
30
+ (`https://api.<root>/v1/mcp`, `<root>` being the platform domain you use); there is no built-in address. Without the
31
+ local package, connect the client to that cloud server directly; it has the same tools.
32
+
33
+ ## Use it from the terminal
34
+
35
+ ```sh
36
+ npx -y -p @tanqory/theme-mcp tanqory-theme init my-theme # Nova V3 starter content
37
+ npx -y -p @tanqory/theme-mcp tanqory-theme validate my-theme # file:line:column for every problem
38
+ npx -y -p @tanqory/theme-mcp tanqory-theme dev my-theme # local preview, re-checked on every change
39
+ npx -y -p @tanqory/theme-mcp tanqory-theme login
40
+ npx -y -p @tanqory/theme-mcp tanqory-theme push my-theme # a draft on the store, never the live theme
41
+ npx -y -p @tanqory/theme-mcp tanqory-theme publish --theme <id>
42
+ ```
43
+
44
+ `push` and `publish` show the change and ask before making it (`--yes` approves without the prompt). `dev --push` keeps
45
+ one draft on the store up to date with every valid change and links its real preview.
46
+
47
+ ## What a theme is here
48
+
49
+ A folder with `config/settings.json`, `groups/header.json`, `groups/footer.json` and `templates/<page>.json`. Only those
50
+ files are read or sent; code is the base theme's own. Images go to the store's files with `theme_upload_asset` and are
51
+ used by their https URL.
52
+
53
+ `TANQORY_MCP_URL` picks the cloud server (`https://api.<root>/v1/mcp`). Credentials are kept in
54
+ `~/.tanqory/theme-mcp/credentials.json` (`TANQORY_HOME` moves it), readable by you only.
@@ -0,0 +1,125 @@
1
+ #!/usr/bin/env node
2
+ // tanqory-theme: build a Tanqory store theme from a folder.
3
+ // tanqory-theme init [dir] Nova V3 starter content into dir (default .)
4
+ // tanqory-theme validate [dir] check against the Tanqory theme standard (exit 1 when not valid)
5
+ // tanqory-theme dev [dir] [--port n] [--push] local preview; --push keeps a draft on the store up to date
6
+ // tanqory-theme login | logout sign in to the Tanqory cloud (browser), or forget the sign-in
7
+ // tanqory-theme themes list the store's themes
8
+ // tanqory-theme pull <themeId> [dir] the store theme's content files into dir
9
+ // tanqory-theme push [dir] [--theme id] [--yes] save dir as a draft (never the live theme)
10
+ // tanqory-theme publish --theme id [--yes] make a draft this sign-in pushed the live theme
11
+ // tanqory-theme skill [dir] install the Tanqory Theme Skill for Claude Code (.claude/skills)
12
+ // tanqory-theme mcp run the stdio MCP server (same as the theme-mcp command)
13
+ // TANQORY_MCP_URL picks the cloud server (required for them; there is no built-in address).
14
+ import { cpSync, mkdirSync } from 'node:fs'
15
+ import { createRequire } from 'node:module'
16
+ import { dirname, join, resolve } from 'node:path'
17
+ import { createInterface } from 'node:readline/promises'
18
+ import standard from '@tanqory/theme-standard'
19
+ import { DEFAULT_SERVER, callTool, login, logout } from '../lib/cloud.mjs'
20
+ import { readTheme, writeTheme } from '../lib/project.mjs'
21
+ import { dev } from '../lib/dev.mjs'
22
+ import { serve } from '../lib/server.mjs'
23
+
24
+ const { validateTheme, formatReport, starterFiles } = standard
25
+ const argv = process.argv.slice(2)
26
+ const cmd = argv[0]
27
+ const flag = (n) => argv.includes(`--${n}`)
28
+ const opt = (n) => { const i = argv.indexOf(`--${n}`); return i >= 0 ? argv[i + 1] : undefined }
29
+ const positional = argv.slice(1).filter((a, i, all) => !a.startsWith('--') && !(i > 0 && ['--port', '--theme'].includes(all[i - 1])))
30
+ const dirArg = (i = 0) => resolve(positional[i] ?? '.')
31
+ const out = (v) => process.stdout.write(`${typeof v === 'string' ? v : JSON.stringify(v, null, 2)}\n`)
32
+ const fail = (m, code = 1) => { process.stderr.write(`${m}\n`); process.exit(code) }
33
+
34
+ async function approve(card) {
35
+ out(`${card.title}\n${card.summary}`)
36
+ if (flag('yes')) return true
37
+ if (!process.stdin.isTTY) fail('Not approved: run again with --yes to approve without a prompt.')
38
+ const rl = createInterface({ input: process.stdin, output: process.stderr })
39
+ const a = (await rl.question('Approve? [y/N] ')).trim().toLowerCase()
40
+ rl.close()
41
+ return a === 'y' || a === 'yes'
42
+ }
43
+
44
+ /** A cloud write: the first call returns the change; after approval the second makes it. */
45
+ async function write(name, args) {
46
+ const ask = await callTool(name, args)
47
+ if (ask.isError) fail(ask.value?.report || ask.value?.message || JSON.stringify(ask.value))
48
+ if (!(await approve(ask.value))) fail('Nothing was changed.')
49
+ const done = await callTool(name, { ...args, confirmationToken: ask.value.confirmationToken })
50
+ if (done.isError) fail(done.value?.report || done.value?.message || JSON.stringify(done.value))
51
+ return done.value
52
+ }
53
+
54
+ switch (cmd) {
55
+ case 'init': {
56
+ const dir = dirArg()
57
+ const written = writeTheme(dir, starterFiles())
58
+ out(`Wrote ${written.length} files to ${dir} (existing files kept). Next: edit them, then tanqory-theme validate ${positional[0] ?? '.'}`)
59
+ break
60
+ }
61
+ case 'validate': {
62
+ const { files, ignored } = readTheme(dirArg())
63
+ const r = validateTheme(files)
64
+ out(formatReport(r))
65
+ if (ignored.length) out(`Not theme files (ignored): ${ignored.join(', ')}`)
66
+ process.exit(r.ok ? 0 : 1)
67
+ }
68
+ case 'dev':
69
+ await dev(dirArg(), { port: Number(opt('port') ?? 4380), push: flag('push'), themeId: opt('theme') ?? null })
70
+ break
71
+ case 'login': {
72
+ const e = await login(DEFAULT_SERVER)
73
+ out(`Signed in to ${e.server} (${e.scope}).`)
74
+ break
75
+ }
76
+ case 'logout':
77
+ logout(DEFAULT_SERVER)
78
+ out('Signed out.')
79
+ break
80
+ case 'themes': {
81
+ const r = await callTool('theme_get', {})
82
+ if (r.isError) fail(r.value?.message || JSON.stringify(r.value))
83
+ for (const t of r.value.themes) out(`${t.id} ${t.role.padEnd(11)} ${t.name}${t.madeByThisConnection ? ' (pushed from here)' : ''}`)
84
+ break
85
+ }
86
+ case 'pull': {
87
+ if (!positional[0]) fail('tanqory-theme pull <themeId> [dir]')
88
+ const r = await callTool('theme_files', { themeId: positional[0] })
89
+ if (r.isError) fail(r.value?.message || JSON.stringify(r.value))
90
+ const dir = resolve(positional[1] ?? '.')
91
+ out(`Wrote ${writeTheme(dir, r.value.files, { overwrite: true }).length} files to ${dir}.`)
92
+ break
93
+ }
94
+ case 'push': {
95
+ const { files } = readTheme(dirArg())
96
+ const r = validateTheme(files)
97
+ if (!r.ok) fail(formatReport(r))
98
+ const v = await write('theme_push_draft', { files, ...(opt('theme') ? { themeId: opt('theme') } : {}) })
99
+ out(`Saved to draft ${v.themeId}. Preview: tanqory-theme dev --push --theme ${v.themeId}, or ask theme_preview_url.`)
100
+ const pv = await callTool('theme_preview_url', { themeId: v.themeId })
101
+ if (!pv.isError && pv.value?.url) out(`Preview (${pv.value.status}): ${pv.value.url}`)
102
+ break
103
+ }
104
+ case 'publish': {
105
+ if (!opt('theme')) fail('tanqory-theme publish --theme <themeId>')
106
+ const v = await write('theme_publish', { themeId: opt('theme') })
107
+ out(v.live ? `Live: ${v.liveUrl ?? v.themeId}` : v.message)
108
+ break
109
+ }
110
+ case 'skill': {
111
+ const require = createRequire(import.meta.url)
112
+ const src = join(dirname(require.resolve('@tanqory/theme-standard/package.json')), 'guide', 'tanqory-theme')
113
+ const target = join(resolve(positional[0] ?? '.'), '.claude', 'skills', 'tanqory-theme')
114
+ mkdirSync(target, { recursive: true })
115
+ cpSync(src, target, { recursive: true })
116
+ out(`Installed the Tanqory Theme Skill at ${target}. Claude Code loads it in this project.`)
117
+ break
118
+ }
119
+ case 'mcp':
120
+ serve()
121
+ break
122
+ default:
123
+ out('tanqory-theme init|validate|dev|login|logout|themes|pull|push|publish|skill|mcp (see the README of @tanqory/theme-mcp)')
124
+ process.exit(cmd ? 2 : 0)
125
+ }
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env node
2
+ // The local Tanqory Theme MCP server over stdio (lib/server.mjs). For an MCP client's configuration:
3
+ // { "command": "npx", "args": ["-y", "@tanqory/theme-mcp"] }
4
+ // TANQORY_MCP_URL picks the cloud server for the store tools (required for them; there is no built-in address).
5
+ import { serve } from '../lib/server.mjs'
6
+ serve()
package/lib/cloud.mjs ADDED
@@ -0,0 +1,169 @@
1
+ // The Tanqory cloud MCP server (`https://api.<root>/v1/mcp`) as a client: sign-in and tool calls.
2
+ //
3
+ // Sign-in is the MCP authorization flow (specification 2025-06-18) as a native app does it (RFC 8252): the server's
4
+ // RFC 9728 metadata names the authorization server; its RFC 8414 metadata gives the endpoints; the client registers
5
+ // itself (RFC 7591) with a loopback redirect, then runs the authorization code flow with PKCE S256 and the RFC 8707
6
+ // `resource`, in the merchant's browser, and the merchant picks the store on Tanqory's consent page. Tokens are kept in
7
+ // ~/.tanqory/theme-mcp/credentials.json (mode 0600), per server URL; the refresh token rotates (OAuth 2.1 §4.3.1).
8
+ import { createHash, randomBytes } from 'node:crypto'
9
+ import { spawn } from 'node:child_process'
10
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
11
+ import { createServer } from 'node:http'
12
+ import { homedir } from 'node:os'
13
+ import { join } from 'node:path'
14
+
15
+ // No built-in address: Prod's platform API host is still the old system (tools/guards/check-old-system.mjs, owner rule
16
+ // 2026-11-05), and a host written into code survives the next move unnoticed. The store tools need TANQORY_MCP_URL.
17
+ export const DEFAULT_SERVER = process.env.TANQORY_MCP_URL || ''
18
+ function need(server) {
19
+ if (!server) throw new Error('No cloud server: set TANQORY_MCP_URL to the Tanqory MCP address, https://api.<root>/v1/mcp for the platform domain you use.')
20
+ return server
21
+ }
22
+ const HOME = process.env.TANQORY_HOME || join(homedir(), '.tanqory')
23
+ const STORE = join(HOME, 'theme-mcp', 'credentials.json')
24
+ const SCOPES = 'read_themes write_themes'
25
+
26
+ function load() {
27
+ try { return JSON.parse(readFileSync(STORE, 'utf8')) } catch { return {} }
28
+ }
29
+ function save(all) {
30
+ mkdirSync(join(HOME, 'theme-mcp'), { recursive: true })
31
+ writeFileSync(STORE, `${JSON.stringify(all, null, 2)}\n`, { mode: 0o600 })
32
+ chmodSync(STORE, 0o600)
33
+ }
34
+
35
+ const b64url = (b) => Buffer.from(b).toString('base64url')
36
+
37
+ async function json(res) {
38
+ const t = await res.text()
39
+ try { return JSON.parse(t) } catch { return { raw: t } }
40
+ }
41
+
42
+ /** RFC 9728 §3.1: the metadata URL of a resource with a path. */
43
+ export function resourceMetadataUrl(server) {
44
+ const u = new URL(server)
45
+ return `${u.origin}/.well-known/oauth-protected-resource${u.pathname === '/' ? '' : u.pathname}`
46
+ }
47
+
48
+ async function discover(server) {
49
+ const prm = await json(await fetch(resourceMetadataUrl(server)))
50
+ const issuer = prm.authorization_servers?.[0]
51
+ if (!issuer) throw new Error(`${server} publishes no authorization server.`)
52
+ const as = await json(await fetch(`${issuer.replace(/\/+$/, '')}/.well-known/oauth-authorization-server`))
53
+ if (!as.authorization_endpoint || !as.token_endpoint) throw new Error(`${issuer} publishes no OAuth metadata.`)
54
+ if (!(as.code_challenge_methods_supported ?? []).includes('S256')) throw new Error('The authorization server does not support PKCE S256.')
55
+ return { resource: prm.resource ?? server, issuer, as }
56
+ }
57
+
58
+ function openBrowser(url) {
59
+ const cmd = process.platform === 'darwin' ? 'open' : process.platform === 'win32' ? 'cmd' : 'xdg-open'
60
+ const args = process.platform === 'win32' ? ['/c', 'start', '', url] : [url]
61
+ try { spawn(cmd, args, { stdio: 'ignore', detached: true }).unref() } catch { /* the URL is printed too */ }
62
+ }
63
+
64
+ /** Sign in for `server`; prints the URL to open. Answers the saved entry. */
65
+ export async function login(server = DEFAULT_SERVER, log = console.error) {
66
+ need(server)
67
+ const { resource, issuer, as } = await discover(server)
68
+ const verifier = b64url(randomBytes(32))
69
+ const challenge = b64url(createHash('sha256').update(verifier).digest())
70
+ const state = b64url(randomBytes(16))
71
+ const httpServer = createServer()
72
+ await new Promise((r) => httpServer.listen(0, '127.0.0.1', r))
73
+ const redirectUri = `http://127.0.0.1:${httpServer.address().port}/callback`
74
+ try {
75
+ const reg = await json(await fetch(as.registration_endpoint, {
76
+ method: 'POST',
77
+ headers: { 'content-type': 'application/json' },
78
+ body: JSON.stringify({ client_name: 'Tanqory Theme MCP (local)', redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', scope: SCOPES }),
79
+ }))
80
+ if (!reg.client_id) throw new Error(`Registration failed: ${JSON.stringify(reg)}`)
81
+ const auth = new URL(as.authorization_endpoint)
82
+ for (const [k, v] of Object.entries({ response_type: 'code', client_id: reg.client_id, redirect_uri: redirectUri, code_challenge: challenge, code_challenge_method: 'S256', resource, scope: SCOPES, state })) auth.searchParams.set(k, v)
83
+ log(`Open this page to sign in and choose the store:\n ${auth}\n`)
84
+ openBrowser(auth.toString())
85
+ const code = await new Promise((resolve, reject) => {
86
+ const timer = setTimeout(() => reject(new Error('Sign-in timed out after 5 minutes.')), 5 * 60_000)
87
+ httpServer.on('request', (req, res) => {
88
+ const u = new URL(req.url, redirectUri)
89
+ if (u.pathname !== '/callback') { res.writeHead(404).end(); return }
90
+ const ok = u.searchParams.get('state') === state && u.searchParams.get('code') && (!u.searchParams.get('iss') || u.searchParams.get('iss') === issuer)
91
+ res.writeHead(ok ? 200 : 400, { 'content-type': 'text/html; charset=utf-8' }).end(ok ? '<p>Signed in. You can close this tab.</p>' : '<p>Sign-in did not complete.</p>')
92
+ clearTimeout(timer)
93
+ if (ok) resolve(u.searchParams.get('code'))
94
+ else reject(new Error(u.searchParams.get('error_description') || u.searchParams.get('error') || 'Sign-in did not complete.'))
95
+ })
96
+ })
97
+ const tok = await json(await fetch(as.token_endpoint, {
98
+ method: 'POST',
99
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
100
+ body: new URLSearchParams({ grant_type: 'authorization_code', code, code_verifier: verifier, redirect_uri: redirectUri, client_id: reg.client_id, resource }),
101
+ }))
102
+ if (!tok.access_token) throw new Error(`Token request failed: ${tok.error_description || tok.error || 'no token'}`)
103
+ const entry = { server, resource, tokenEndpoint: as.token_endpoint, clientId: reg.client_id, accessToken: tok.access_token, refreshToken: tok.refresh_token, expiresAt: Date.now() + (tok.expires_in ?? 900) * 1000, scope: tok.scope }
104
+ const all = load()
105
+ all[server] = entry
106
+ save(all)
107
+ return entry
108
+ } finally {
109
+ httpServer.close()
110
+ }
111
+ }
112
+
113
+ export function logout(server = DEFAULT_SERVER) {
114
+ if (!server) return
115
+ const all = load()
116
+ delete all[server]
117
+ save(all)
118
+ }
119
+
120
+ export function signedIn(server = DEFAULT_SERVER) {
121
+ return !!server && !!load()[server]
122
+ }
123
+
124
+ async function accessToken(server) {
125
+ need(server)
126
+ const all = load()
127
+ const e = all[server]
128
+ if (!e) throw new Error(`Not signed in to ${server}. Run: tanqory-theme login`)
129
+ if (e.expiresAt - 60_000 > Date.now()) return e.accessToken
130
+ const tok = await json(await fetch(e.tokenEndpoint, {
131
+ method: 'POST',
132
+ headers: { 'content-type': 'application/x-www-form-urlencoded' },
133
+ body: new URLSearchParams({ grant_type: 'refresh_token', refresh_token: e.refreshToken, client_id: e.clientId, resource: e.resource }),
134
+ }))
135
+ if (!tok.access_token) {
136
+ delete all[server]
137
+ save(all)
138
+ throw new Error('The sign-in has ended. Run: tanqory-theme login')
139
+ }
140
+ all[server] = { ...e, accessToken: tok.access_token, refreshToken: tok.refresh_token ?? e.refreshToken, expiresAt: Date.now() + (tok.expires_in ?? 900) * 1000 }
141
+ save(all)
142
+ return tok.access_token
143
+ }
144
+
145
+ let seq = 0
146
+ /** One JSON-RPC request to the cloud MCP server (Streamable HTTP, JSON response). */
147
+ export async function rpc(method, params, server = DEFAULT_SERVER) {
148
+ need(server)
149
+ const res = await fetch(server, {
150
+ method: 'POST',
151
+ headers: { 'content-type': 'application/json', accept: 'application/json, text/event-stream', authorization: `Bearer ${await accessToken(server)}`, 'mcp-protocol-version': '2025-06-18' },
152
+ body: JSON.stringify({ jsonrpc: '2.0', id: ++seq, method, ...(params ? { params } : {}) }),
153
+ })
154
+ const body = await json(res)
155
+ if (res.status === 401) throw new Error('The cloud refused the sign-in (401). Run: tanqory-theme login')
156
+ if (body.error) throw new Error(body.error.message || JSON.stringify(body.error))
157
+ return body.result
158
+ }
159
+
160
+ /** A cloud tool call → { isError, value } (the tool's JSON result). */
161
+ export async function callTool(name, args, server = DEFAULT_SERVER) {
162
+ const r = await rpc('tools/call', { name, arguments: args }, server)
163
+ const text = r?.content?.[0]?.text ?? 'null'
164
+ let value
165
+ try { value = JSON.parse(text) } catch { value = text }
166
+ // Images (theme_preview_screenshot) come after the JSON text, as MCP image content.
167
+ const images = (r?.content ?? []).filter((c) => c?.type === 'image' && typeof c.data === 'string' && typeof c.mimeType === 'string').map((c) => ({ type: 'image', data: c.data, mimeType: c.mimeType }))
168
+ return { isError: !!r?.isError, value, images }
169
+ }
package/lib/dev.mjs ADDED
@@ -0,0 +1,93 @@
1
+ // `tanqory-theme dev`: a local preview of a theme folder while it is edited. It validates on every change with the same
2
+ // validator as the cloud and serves, at http://127.0.0.1:<port>, each page as an outline of what will render: every
3
+ // section and block in order, with its title from the Nova V3 catalogue, its text and its images, plus the findings.
4
+ // The real Nova rendering is the cloud draft preview: with --push (signed in), every change that passes is pushed to
5
+ // the same draft and the page links its preview. The page reloads itself when a file changes.
6
+ import { createServer } from 'node:http'
7
+ import standard from '@tanqory/theme-standard'
8
+ import { readTheme } from './project.mjs'
9
+ import { callTool } from './cloud.mjs'
10
+
11
+ const { validateTheme, formatReport, loadBase } = standard
12
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c])
13
+
14
+ function nodeHtml(node, catalog) {
15
+ const def = catalog[node?.type] ?? {}
16
+ const s = node?.settings ?? {}
17
+ const parts = []
18
+ for (const [k, v] of Object.entries(s)) {
19
+ const t = def.attributes?.[k]?.type
20
+ if (typeof v !== 'string' || !v) continue
21
+ if ((t === 'image' || t === 'image_picker') && /^https:\/\//.test(v)) parts.push(`<img src="${esc(v)}" alt="" loading="lazy">`)
22
+ else if (['text', 'textarea', 'richtext'].includes(t)) parts.push(`<p><span class="k">${esc(def.attributes[k].label || k)}</span> ${esc(v.replace(/<[^>]*>/g, ''))}</p>`)
23
+ }
24
+ const kids = (node?.blocks ?? []).map((b) => nodeHtml(b, catalog)).join('')
25
+ return `<section class="${def.role === 'block' ? 'block' : 'section'}"><h3>${esc(def.title || node?.type)} <small>${esc(node?.id)}</small></h3>${parts.join('')}${kids}</section>`
26
+ }
27
+
28
+ function page(dir, state) {
29
+ const base = loadBase()
30
+ const { files } = readTheme(dir)
31
+ const r = validateTheme(files)
32
+ const templates = Object.keys(files).filter((p) => p.startsWith('templates/')).sort()
33
+ const body = templates.map((p) => {
34
+ let doc
35
+ try { doc = JSON.parse(files[p]) } catch { return `<h2>${esc(p)}</h2><p class="bad">Not JSON</p>` }
36
+ return `<h2>${esc(p)}</h2>${(doc.sections ?? []).map((n) => nodeHtml(n, base.catalog)).join('')}`
37
+ }).join('')
38
+ return `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Theme preview</title>
39
+ <style>:root{color-scheme:light dark;--fg:#1f2328;--bg:#fff;--line:#d0d7de;--muted:#59636e;--bad:#b42318;--good:#1a7f37}
40
+ @media (prefers-color-scheme:dark){:root{--fg:#e6edf3;--bg:#0d1117;--line:#30363d;--muted:#9198a1;--bad:#ff7b72;--good:#3fb950}}
41
+ body{font:15px/1.5 system-ui,sans-serif;margin:0 auto;max-width:960px;padding:16px;color:var(--fg);background:var(--bg)}
42
+ section{border:1px solid var(--line);border-radius:8px;padding:12px;margin:8px 0}section.block{margin-left:16px}
43
+ h3{margin:0 0 4px;font-size:15px}small,.k{color:var(--muted);font-weight:400}img{max-width:240px;display:block;border-radius:4px}
44
+ pre{white-space:pre-wrap;border:1px solid var(--line);border-radius:8px;padding:12px}.bad{color:var(--bad)}.good{color:var(--good)}</style>
45
+ <h1>Theme preview <small>${esc(dir)}</small></h1>
46
+ <p class="${r.ok ? 'good' : 'bad'}">${esc(r.summary)}</p>${r.ok ? '' : `<pre>${esc(formatReport(r))}</pre>`}
47
+ ${state.preview ? `<p>Draft <code>${esc(state.themeId)}</code> on the store: <a href="${esc(state.preview)}" target="_blank" rel="noopener">open the real preview</a></p>` : ''}
48
+ ${state.pushError ? `<p class="bad">${esc(state.pushError)}</p>` : ''}
49
+ ${body}
50
+ <script>let v=${state.version};setInterval(async()=>{try{const r=await fetch('/version');if(Number(await r.text())!==v)location.reload()}catch{}},1000)</script>`
51
+ }
52
+
53
+ export async function dev(dir, { port = 4380, push = false, themeId = null, log = console.error } = {}) {
54
+ const state = { version: 0, themeId, preview: null, pushError: null }
55
+ let last = ''
56
+ const tick = async () => {
57
+ const { files } = readTheme(dir)
58
+ const sig = JSON.stringify(files)
59
+ if (sig === last) return
60
+ last = sig
61
+ state.version++
62
+ const r = validateTheme(files)
63
+ log(`${new Date().toLocaleTimeString()} ${r.summary}`)
64
+ if (!push || !r.ok) return
65
+ // A push from dev is the merchant's own command (they asked for --push); its confirmation is taken here.
66
+ try {
67
+ const args = { files, ...(state.themeId ? { themeId: state.themeId } : {}) }
68
+ const ask = await callTool('theme_push_draft', args)
69
+ if (ask.isError) throw new Error(ask.value?.message || ask.value?.error || 'refused')
70
+ const done = await callTool('theme_push_draft', { ...args, confirmationToken: ask.value.confirmationToken })
71
+ if (done.isError) throw new Error(done.value?.message || done.value?.error || 'refused')
72
+ state.themeId = done.value.themeId
73
+ const pv = await callTool('theme_preview_url', { themeId: state.themeId })
74
+ state.preview = pv.value?.url ?? null
75
+ state.pushError = null
76
+ state.version++
77
+ log(`pushed to draft ${state.themeId}${state.preview ? `: ${state.preview}` : ''}`)
78
+ } catch (e) {
79
+ state.pushError = `Push failed: ${e instanceof Error ? e.message : String(e)}`
80
+ state.version++
81
+ log(state.pushError)
82
+ }
83
+ }
84
+ await tick()
85
+ const timer = setInterval(() => void tick(), 1000)
86
+ const server = createServer((req, res) => {
87
+ if (req.url === '/version') return res.writeHead(200, { 'content-type': 'text/plain' }).end(String(state.version))
88
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }).end(page(dir, state))
89
+ })
90
+ await new Promise((r) => server.listen(port, '127.0.0.1', r))
91
+ log(`Preview: http://127.0.0.1:${server.address().port} (Ctrl+C to stop)`)
92
+ return { close: () => { clearInterval(timer); server.close() }, port: server.address().port }
93
+ }
@@ -0,0 +1,40 @@
1
+ // A theme folder on disk: config/settings.json, groups/*.json, templates/*.json. Nothing else is read or written.
2
+ import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'node:fs'
3
+ import { dirname, join, relative, sep } from 'node:path'
4
+
5
+ const CONTENT = /^(config\/settings\.json|groups\/[^/]+\.json|templates\/[^/]+\.json)$/
6
+
7
+ /** Every content file under `dir`, as { 'templates/index.json': text }. Other files are listed in `ignored`. */
8
+ export function readTheme(dir) {
9
+ const files = {}
10
+ const ignored = []
11
+ const walk = (d) => {
12
+ if (!existsSync(d)) return
13
+ for (const name of readdirSync(d, { withFileTypes: true })) {
14
+ if (name.name.startsWith('.') || name.name === 'node_modules') continue
15
+ const p = join(d, name.name)
16
+ if (name.isDirectory()) walk(p)
17
+ else {
18
+ const rel = relative(dir, p).split(sep).join('/')
19
+ if (CONTENT.test(rel)) files[rel] = readFileSync(p, 'utf8')
20
+ else ignored.push(rel)
21
+ }
22
+ }
23
+ }
24
+ for (const sub of ['config', 'groups', 'templates']) walk(join(dir, sub))
25
+ return { files, ignored }
26
+ }
27
+
28
+ /** Writes { path: text } under `dir`; refuses any path outside the three content kinds. */
29
+ export function writeTheme(dir, files, { overwrite = false } = {}) {
30
+ const written = []
31
+ for (const [rel, text] of Object.entries(files)) {
32
+ if (!CONTENT.test(rel) || rel.includes('..')) throw new Error(`Not a theme content file: ${rel}`)
33
+ const target = join(dir, rel)
34
+ if (existsSync(target) && !overwrite) continue
35
+ mkdirSync(dirname(target), { recursive: true })
36
+ writeFileSync(target, typeof text === 'string' ? text : `${JSON.stringify(text, null, 2)}\n`)
37
+ written.push(rel)
38
+ }
39
+ return written
40
+ }
package/lib/server.mjs ADDED
@@ -0,0 +1,224 @@
1
+ // The local Tanqory Theme MCP server (stdio). The same tools as the cloud server (`api.<root>/v1/mcp`, docs/themes/
2
+ // THEME_MCP.md §4), on a theme folder on this machine:
3
+ // - theme_guide, theme_reference, theme_validate and theme_init run here, offline, with @tanqory/theme-standard (the
4
+ // validator the cloud runs);
5
+ // - theme_get, theme_files, theme_push_draft, theme_preview_url, theme_preview_screenshot, theme_upload_asset and
6
+ // theme_publish go to the cloud
7
+ // with the merchant's own sign-in (`tanqory-theme login`). A push is validated here first and refused here if it
8
+ // does not pass; the cloud validates it again.
9
+ // Transport: MCP stdio, one JSON-RPC message per line on stdin and stdout; logs on stderr (specification 2025-06-18,
10
+ // "Transports").
11
+ import { createInterface } from 'node:readline'
12
+ import { readFileSync, statSync } from 'node:fs'
13
+ import { isAbsolute, resolve } from 'node:path'
14
+ import standard from '@tanqory/theme-standard'
15
+ import { DEFAULT_SERVER, callTool } from './cloud.mjs'
16
+ import { readTheme, writeTheme } from './project.mjs'
17
+
18
+ const { validateTheme, formatReport, references, starterFiles, guide, guideReference, prompts, LIMITS, LICENCES } = standard
19
+ const PROTOCOL = '2025-06-18'
20
+ const VERSION = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8')).version
21
+
22
+ const REFS = [...references('nova-v3'), guideReference()]
23
+ const PROMPTS = prompts()
24
+ const filesSchema = { type: 'object', description: 'Theme files by path, each the full text: templates/<name>.json, groups/<name>.json, config/settings.json.', additionalProperties: { type: ['string', 'object'] } }
25
+ const dirSchema = { type: 'string', description: 'A theme folder on this machine (config/, groups/, templates/); relative to the working directory.' }
26
+ const themeIdSchema = { type: 'string', description: 'A theme of the store, from theme_get.' }
27
+ const confirmSchema = { type: 'string', description: 'Leave out on the first call: it changes nothing and returns the change with a confirmationToken. After the merchant approves that change, call again with the same arguments and this token to make it.' }
28
+
29
+ // What the merchant sees is the title and a description of at most two short sentences, in plain words; how to call a
30
+ // tool goes in its property descriptions and the server instructions, which models read (the cloud server does the
31
+ // same: apps/ai store/tools.ts StoreTool). Annotations follow the MCP ToolAnnotations as each tool behaves here: a tool
32
+ // that writes files on this machine is not read-only, and one that may replace them is destructive.
33
+ const ann = ({ readOnly = true, destructive = false, idempotent = true, openWorld = false } = {}) => ({ readOnlyHint: readOnly, destructiveHint: readOnly ? false : destructive, idempotentHint: idempotent, openWorldHint: openWorld })
34
+ const tool = (name, title, description, inputSchema, annotations) => ({ name, title, description, inputSchema: { type: 'object', additionalProperties: false, ...inputSchema }, annotations: { title, ...annotations } })
35
+
36
+ export const INSTRUCTIONS = [
37
+ 'Build Tanqory store themes: read theme_guide first. Themes are content for the Nova V3 base theme and must pass theme_validate before they are pushed or published.',
38
+ 'Every tool that changes the store (theme_push_draft, theme_upload_asset, theme_publish) takes two calls: the first changes nothing and returns the change and a confirmationToken; show that change to the merchant, and only after they approve it call the same tool again with the same arguments and the token.',
39
+ 'Tools that read or change the store need a sign-in once (tanqory-theme login). Push a draft (never the live theme), look at it with theme_preview_screenshot and fix what differs from the request, push a follow-up change with the same themeId, give the merchant the previewLink of theme_preview_url, and publish only when the merchant asks.',
40
+ ].join(' ')
41
+
42
+ export function toolList() {
43
+ return [
44
+ tool('theme_guide', 'How to build a theme', 'Explains, step by step and with examples, how to build or restyle your store theme with AI. Read it before starting a theme.', { properties: {} }, ann()),
45
+ tool('theme_reference', 'Read a theme reference', 'Reads one reference of the theme rules, such as every section and setting a theme can use.', {
46
+ properties: { name: { type: 'string', enum: REFS.map((r) => r.name), description: 'theme-schema, theme-setting-types, theme-limits, theme-assets, nova-v3-catalogue (every section and block), nova-v3-settings, nova-v3-templates or theme-guide. The same documents are MCP resources.' } },
47
+ required: ['name'],
48
+ }, ann()),
49
+ tool('theme_validate', 'Check a theme', 'Checks a theme for problems and says how to fix each one, before anything is saved. It changes nothing.', {
50
+ properties: {
51
+ files: { ...filesSchema, description: `${filesSchema.description} Give files or dir. Every problem comes back with file, line, column and fix; at most ${LIMITS.sectionsPerTemplate} sections per template, blocks ${LIMITS.nestingDepth} levels deep. Checks the packaged Nova offline; theme_push_draft checks again against the store's installed build.` },
52
+ dir: dirSchema,
53
+ },
54
+ }, ann()),
55
+ tool('theme_init', 'Start a new theme', 'Gives the starter files of the Nova base theme to build a new theme from. It never overwrites a file you already have.', {
56
+ properties: {
57
+ dir: { ...dirSchema, description: `${dirSchema.description} With dir, the starter files are written into it, never over an existing file; without it, the core files are returned.` },
58
+ paths: { type: 'array', items: { type: 'string' }, description: 'Without dir: the starter files to return in full (by default config/settings.json, groups/header.json, groups/footer.json, templates/index.json).' },
59
+ },
60
+ }, ann({ readOnly: false, destructive: false, idempotent: true })),
61
+ tool('theme_get', 'List your themes', "Lists your store's themes and shows which one is live and which are drafts.", {
62
+ properties: { themeId: { type: 'string', description: 'One theme; leave out to list them all. Needs tanqory-theme login once.' } },
63
+ }, ann()),
64
+ tool('theme_files', "Read a theme's files", 'Reads the content of one of your themes: its settings, header, footer and page templates. It can also save them into a folder on this computer.', {
65
+ properties: {
66
+ themeId: themeIdSchema,
67
+ paths: { type: 'array', items: { type: 'string' }, description: 'Only these files, e.g. templates/index.json; leave out for all.' },
68
+ dir: { ...dirSchema, description: `${dirSchema.description} With dir, the files are also written into it, replacing what is there.` },
69
+ },
70
+ required: ['themeId'],
71
+ }, ann({ readOnly: false, destructive: true, idempotent: true })),
72
+ tool('theme_push_draft', 'Save a theme as a draft', 'Saves theme changes as a draft, never touching your live theme. You approve the change before it is saved.', {
73
+ properties: {
74
+ files: { ...filesSchema, description: `${filesSchema.description} Give files or dir. Validated here first, then by the cloud; a theme that does not pass is refused with every finding.` },
75
+ dir: dirSchema,
76
+ themeId: { type: 'string', description: 'A draft this connection made (theme_get shows madeByThisConnection). Leave out to make a new draft.' },
77
+ confirmationToken: confirmSchema,
78
+ },
79
+ }, ann({ readOnly: false, destructive: false, idempotent: false })),
80
+ tool('theme_preview_url', 'Preview a draft theme', 'Gives a private link to preview a draft theme before it goes live. The link stays the same when the draft changes.', {
81
+ properties: { themeId: { type: 'string', description: 'A theme that is not live, from theme_get. While the preview is being prepared the answer has status "pending": ask again after a few seconds. Give the merchant previewLink: it stays the same after every push. url opens this version only.' } },
82
+ required: ['themeId'],
83
+ }, ann()),
84
+ tool('theme_preview_screenshot', 'See a draft theme', 'Takes desktop and mobile pictures of a draft theme, so the AI can check its work before you see it. It changes nothing.', {
85
+ properties: {
86
+ themeId: { type: 'string', description: 'A draft you pushed (theme_push_draft answers it). The answer holds images, desktop 1440 wide and mobile 390 wide, rendered by the cloud. Call this after every push, compare the images with the request, fix what differs and push again with the same themeId, then give the merchant previewLink.' },
87
+ template: { type: 'string', enum: ['index', 'collection', 'list-collections', 'cart', 'search', '404'], description: 'A page with a fixed address; default index (the home page).' },
88
+ path: { type: 'string', description: 'Any other page by its address on the store, starting with "/", e.g. "/products/<handle>". Instead of template.' },
89
+ viewports: { type: 'array', items: { type: 'string', enum: ['desktop', 'mobile'] }, description: 'Default both.' },
90
+ fullPage: { type: 'boolean', description: 'The whole page instead of the first screen. Default false.' },
91
+ },
92
+ required: ['themeId'],
93
+ }, ann()),
94
+ tool('theme_upload_asset', 'Add an image to your files', "Adds an image to your store's files so your theme can use it. You approve each upload, and its licence must allow commercial use.", {
95
+ properties: {
96
+ source: { type: 'object', description: `{ "url": "https://…" } that another tool gave, or { "path": "hero.webp" }, a file on this machine of at most ${LIMITS.inlineAssetBytes / 1048576} MiB. PNG, JPEG or WebP. The answer has the https URL to put in an image setting.` },
97
+ alt: { type: 'string', description: 'What the image shows, for people who cannot see it.' },
98
+ licence: { type: 'object', description: `How the file may be used. kind: ${Object.keys(LICENCES).join(', ')}; it must allow commercial use.` },
99
+ confirmationToken: confirmSchema,
100
+ },
101
+ required: ['source', 'alt', 'licence'],
102
+ }, ann({ readOnly: false, destructive: false, idempotent: false, openWorld: true })),
103
+ tool('theme_publish', 'Publish a draft theme', "Makes a draft theme your live theme once you've seen its preview. You approve it before shoppers see it.", {
104
+ properties: {
105
+ themeId: { type: 'string', description: 'A draft this connection made with theme_push_draft, after the merchant saw its preview and asked to publish it.' },
106
+ confirmationToken: confirmSchema,
107
+ },
108
+ required: ['themeId'],
109
+ }, ann({ readOnly: false, destructive: true, idempotent: true })),
110
+ ]
111
+ }
112
+
113
+ const abs = (dir) => (isAbsolute(dir) ? dir : resolve(process.cwd(), dir))
114
+ const result = (value, isError = false, images = []) => ({ content: [{ type: 'text', text: JSON.stringify(value) }, ...images], structuredContent: { result: value }, isError })
115
+
116
+ function filesFrom(args) {
117
+ if (args.dir) {
118
+ const { files, ignored } = readTheme(abs(args.dir))
119
+ return { files, ignored }
120
+ }
121
+ return { files: args.files ?? {}, ignored: [] }
122
+ }
123
+
124
+ export async function callLocal(name, args = {}, server = DEFAULT_SERVER) {
125
+ switch (name) {
126
+ case 'theme_guide':
127
+ return result({ guide: guide() })
128
+ case 'theme_reference': {
129
+ const r = REFS.find((x) => x.name === args.name)
130
+ return r ? result({ uri: r.uri, mimeType: r.mimeType, text: r.body() }) : result({ error: 'invalid_input', message: `name is one of ${REFS.map((x) => x.name).join(', ')}` }, true)
131
+ }
132
+ case 'theme_validate': {
133
+ const { files, ignored } = filesFrom(args)
134
+ const r = validateTheme(files)
135
+ const t = standard.loadBase().meta.theme
136
+ // Offline: the packaged Nova. The cloud's theme_validate (with read_themes) and every push check the store's installed build.
137
+ const checkedAgainst = { build: 'packaged', theme: `${t.name}@${t.version}`, note: "The packaged Nova, offline. The store may run another build: theme_push_draft checks again against the store's installed build." }
138
+ return result({ ok: r.ok, summary: r.summary, report: formatReport(r), errors: r.errors, warnings: r.warnings, checked: r.checked, checkedAgainst, ...(ignored.length ? { ignored } : {}) })
139
+ }
140
+ case 'theme_init': {
141
+ const files = starterFiles()
142
+ if (args.dir) return result({ dir: abs(args.dir), written: writeTheme(abs(args.dir), files), next: 'Edit the files, run theme_validate with this dir, then theme_push_draft.' })
143
+ const want = args.paths?.length ? args.paths : ['config/settings.json', 'groups/header.json', 'groups/footer.json', 'templates/index.json']
144
+ return result({ base: 'nova-v3', paths: Object.fromEntries(Object.entries(files).map(([p, t]) => [p, Buffer.byteLength(t)])), files: Object.fromEntries(want.filter((p) => p in files).map((p) => [p, files[p]])) })
145
+ }
146
+ case 'theme_push_draft': {
147
+ const { files } = filesFrom(args)
148
+ const r = validateTheme(files)
149
+ if (!r.ok) return result({ error: 'not_standard', message: 'This theme does not meet the Tanqory theme standard; nothing was sent. Fix each finding and validate again.', summary: r.summary, report: formatReport(r), errors: r.errors }, true)
150
+ const out = await callTool('theme_push_draft', { files, ...(args.themeId ? { themeId: args.themeId } : {}), ...(args.confirmationToken ? { confirmationToken: args.confirmationToken } : {}) }, server)
151
+ return result(out.value, out.isError)
152
+ }
153
+ case 'theme_files': {
154
+ const out = await callTool('theme_files', { themeId: args.themeId, ...(args.paths ? { paths: args.paths } : {}) }, server)
155
+ if (!out.isError && args.dir) out.value.written = writeTheme(abs(args.dir), out.value.files, { overwrite: true })
156
+ return result(out.value, out.isError)
157
+ }
158
+ case 'theme_upload_asset': {
159
+ let source = args.source ?? {}
160
+ if (source.path) {
161
+ const p = abs(source.path)
162
+ if (statSync(p).size > LIMITS.inlineAssetBytes) return result({ error: 'file_too_large', message: `A local file is sent inline, at most ${LIMITS.inlineAssetBytes / 1048576} MiB. Give a larger one as an https URL.` }, true)
163
+ source = { data: readFileSync(p).toString('base64'), filename: p.split(/[\\/]/).pop() }
164
+ }
165
+ const out = await callTool('theme_upload_asset', { source, alt: args.alt, licence: args.licence, ...(args.confirmationToken ? { confirmationToken: args.confirmationToken } : {}) }, server)
166
+ return result(out.value, out.isError)
167
+ }
168
+ case 'theme_get':
169
+ case 'theme_preview_url':
170
+ case 'theme_preview_screenshot':
171
+ case 'theme_publish': {
172
+ const out = await callTool(name, args, server)
173
+ return result(out.value, out.isError, out.images)
174
+ }
175
+ default:
176
+ return null
177
+ }
178
+ }
179
+
180
+ /** Runs the stdio server until stdin closes. */
181
+ export function serve({ server = DEFAULT_SERVER } = {}) {
182
+ const send = (msg) => process.stdout.write(`${JSON.stringify(msg)}\n`)
183
+ const rl = createInterface({ input: process.stdin })
184
+ rl.on('line', async (line) => {
185
+ if (!line.trim()) return
186
+ let msg
187
+ try { msg = JSON.parse(line) } catch { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); return }
188
+ if (msg.id === undefined) return // a notification
189
+ const ok = (r) => send({ jsonrpc: '2.0', id: msg.id, result: r })
190
+ const err = (code, message) => send({ jsonrpc: '2.0', id: msg.id, error: { code, message } })
191
+ try {
192
+ switch (msg.method) {
193
+ case 'initialize':
194
+ return ok({ protocolVersion: PROTOCOL, capabilities: { tools: { listChanged: false }, resources: { listChanged: false }, prompts: { listChanged: false } }, serverInfo: { name: 'tanqory-theme', title: 'Tanqory Theme', version: VERSION }, instructions: INSTRUCTIONS })
195
+ case 'ping':
196
+ return ok({})
197
+ case 'tools/list':
198
+ return ok({ tools: toolList() })
199
+ case 'tools/call': {
200
+ const r = await callLocal(msg.params?.name, msg.params?.arguments ?? {}, server)
201
+ return r ? ok(r) : err(-32602, `Unknown tool: ${msg.params?.name}`)
202
+ }
203
+ case 'resources/list':
204
+ return ok({ resources: REFS.map(({ uri, name, title, description, mimeType }) => ({ uri, name, title, description, mimeType })) })
205
+ case 'resources/read': {
206
+ const r = REFS.find((x) => x.uri === msg.params?.uri)
207
+ return r ? ok({ contents: [{ uri: r.uri, mimeType: r.mimeType, text: r.body() }] }) : err(-32002, `Resource not found: ${msg.params?.uri}`)
208
+ }
209
+ case 'prompts/list':
210
+ return ok({ prompts: PROMPTS.map(({ name, title, description, arguments: a }) => ({ name, title, description, arguments: a })) })
211
+ case 'prompts/get': {
212
+ const p = PROMPTS.find((x) => x.name === msg.params?.name)
213
+ return p ? ok({ description: p.description, messages: p.messages(msg.params?.arguments ?? {}) }) : err(-32602, `Unknown prompt: ${msg.params?.name}`)
214
+ }
215
+ default:
216
+ return err(-32601, `Method not found: ${msg.method}`)
217
+ }
218
+ } catch (e) {
219
+ // A cloud failure is a tool result the client can show, not a protocol error.
220
+ if (msg.method === 'tools/call') return ok(result({ error: 'failed', message: e instanceof Error ? e.message : String(e) }, true))
221
+ return err(-32603, e instanceof Error ? e.message : String(e))
222
+ }
223
+ })
224
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@tanqory/theme-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Build Tanqory store themes with any AI client: a local MCP server (stdio) and the tanqory-theme CLI. Validates locally with @tanqory/theme-standard, the same validator the Tanqory cloud MCP server runs, and pushes drafts and publishes through the cloud with the merchant's sign-in.",
5
+ "license": "MIT",
6
+ "author": "Tanqory",
7
+ "keywords": [
8
+ "tanqory",
9
+ "theme",
10
+ "mcp",
11
+ "model-context-protocol",
12
+ "claude",
13
+ "chatgpt",
14
+ "cli"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/tanqory/tanqory-platform-v2.git",
19
+ "directory": "packages/theme-mcp"
20
+ },
21
+ "type": "module",
22
+ "bin": {
23
+ "theme-mcp": "./bin/theme-mcp.mjs",
24
+ "tanqory-theme": "./bin/tanqory-theme.mjs"
25
+ },
26
+ "exports": {
27
+ ".": "./lib/server.mjs",
28
+ "./package.json": "./package.json"
29
+ },
30
+ "files": [
31
+ "bin",
32
+ "lib",
33
+ "README.md",
34
+ "LICENSE"
35
+ ],
36
+ "engines": {
37
+ "node": ">=20.0.0"
38
+ },
39
+ "dependencies": {
40
+ "@tanqory/theme-standard": "0.1.0"
41
+ },
42
+ "scripts": {
43
+ "test": "node --test test/*.test.mjs"
44
+ },
45
+ "publishConfig": {
46
+ "access": "public",
47
+ "registry": "https://registry.npmjs.org/",
48
+ "tag": "latest"
49
+ }
50
+ }