previewer-agency 0.1.1 → 0.2.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/README.md +26 -0
- package/bin/previewer.mjs +13 -4
- package/lib/mcp.mjs +385 -0
- package/package.json +5 -3
package/README.md
CHANGED
|
@@ -76,6 +76,32 @@ PREVIEWER_TOKEN=pvw_… npx previewer-agency push dist --campaign 42
|
|
|
76
76
|
|
|
77
77
|
`PREVIEWER_URL` points it at another Previewer address.
|
|
78
78
|
|
|
79
|
+
## With an AI agent
|
|
80
|
+
|
|
81
|
+
`previewer mcp` runs Previewer as an MCP server, so an agent like Claude Code or Cursor can upload,
|
|
82
|
+
check approvals and set up a project for you. It uses the same sign-in as the command line; if this
|
|
83
|
+
computer isn't signed in yet, the agent starts the sign-in and you approve the code in your browser.
|
|
84
|
+
|
|
85
|
+
Claude Code:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
claude mcp add previewer -- npx -y previewer-agency mcp
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
Cursor, Windsurf, Claude Desktop and others, in their MCP settings:
|
|
92
|
+
|
|
93
|
+
```json
|
|
94
|
+
{ "mcpServers": { "previewer": { "command": "npx", "args": ["-y", "previewer-agency", "mcp"] } } }
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
Then ask things like "upload dist to the Acme spring campaign and give me the link" or "which banners
|
|
98
|
+
are still waiting for approval?". The tools: `whoami`, `sign_in`, `list_clients`, `list_campaigns`,
|
|
99
|
+
`get_campaign`, `create_campaign`, `link_folder`, `upload_folder` and `remove_banner`. Approving is
|
|
100
|
+
left to your client, in the preview.
|
|
101
|
+
|
|
102
|
+
To have an agent set up a project from scratch, point it at
|
|
103
|
+
[previewer.agency/llms.txt](https://previewer.agency/llms.txt).
|
|
104
|
+
|
|
79
105
|
## As a library
|
|
80
106
|
|
|
81
107
|
```js
|
package/bin/previewer.mjs
CHANGED
|
@@ -10,6 +10,7 @@ import { createInterface } from 'node:readline/promises';
|
|
|
10
10
|
import { parseArgs } from 'node:util';
|
|
11
11
|
import { PreviewerClient, PreviewerError, newCliToken } from '../lib/api.mjs';
|
|
12
12
|
import { collectUploads } from '../lib/files.mjs';
|
|
13
|
+
import { createMcpServer, runStdio } from '../lib/mcp.mjs';
|
|
13
14
|
import { selectMenu } from '../lib/menu.mjs';
|
|
14
15
|
import { DEFAULT_SITE, PROJECT_FILE, findProject, forgetSiteLogin, normalizeSite, resolveAuth, saveProject, saveSiteLogin } from '../lib/config.mjs';
|
|
15
16
|
|
|
@@ -41,6 +42,7 @@ ${bold('Usage')}
|
|
|
41
42
|
previewer campaigns List campaigns
|
|
42
43
|
previewer whoami Show who you're signed in as
|
|
43
44
|
previewer logout Sign out (revokes this computer's token)
|
|
45
|
+
previewer mcp Run as an MCP server, for AI agents (Claude Code, Cursor, …)
|
|
44
46
|
|
|
45
47
|
${bold('Options')}
|
|
46
48
|
--client <name|id> Client to publish to (push, link, campaigns)
|
|
@@ -62,9 +64,10 @@ ${bold('Folders')}
|
|
|
62
64
|
|
|
63
65
|
// --- small helpers -------------------------------------------------------------------------------
|
|
64
66
|
|
|
65
|
-
// PREVIEWER_NO_BROWSER=1 (or no terminal, e.g. over SSH or in CI) prints the link instead.
|
|
66
|
-
|
|
67
|
-
|
|
67
|
+
// PREVIEWER_NO_BROWSER=1 (or no terminal, e.g. over SSH or in CI) prints the link instead. The MCP
|
|
68
|
+
// server has no terminal but does have a person at the computer, so it passes `always`.
|
|
69
|
+
const openInBrowser = (url, { always = false } = {}) => {
|
|
70
|
+
if (process.env.PREVIEWER_NO_BROWSER || (!interactive && !always)) return false;
|
|
68
71
|
const [command, args] =
|
|
69
72
|
process.platform === 'darwin' ? ['open', [url]] : process.platform === 'win32' ? ['cmd', ['/c', 'start', '""', url]] : ['xdg-open', [url]];
|
|
70
73
|
try {
|
|
@@ -380,7 +383,13 @@ async function open(options) {
|
|
|
380
383
|
|
|
381
384
|
// --- main ----------------------------------------------------------------------------------------
|
|
382
385
|
|
|
383
|
-
|
|
386
|
+
// stdout carries the protocol from here on: nothing else may print to it.
|
|
387
|
+
async function mcp() {
|
|
388
|
+
await runStdio(createMcpServer({ version: VERSION, deps: { openBrowser: (url) => openInBrowser(url, { always: true }) } }));
|
|
389
|
+
process.exit(0);
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
const COMMANDS = { login, logout, whoami, push, status, open, link, campaigns: listCampaigns, mcp };
|
|
384
393
|
|
|
385
394
|
const main = async () => {
|
|
386
395
|
let parsed;
|
package/lib/mcp.mjs
ADDED
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// `previewer mcp`: Previewer as tools for AI agents (Claude Code, Cursor, …), over the Model Context
|
|
2
|
+
// Protocol on stdio. No dependencies: newline-delimited JSON-RPC 2.0, the same API client and
|
|
3
|
+
// sign-in as the command line.
|
|
4
|
+
//
|
|
5
|
+
// stdout belongs to the protocol: nothing else may be written there while this runs.
|
|
6
|
+
|
|
7
|
+
import os from 'node:os';
|
|
8
|
+
import path from 'node:path';
|
|
9
|
+
import { createInterface } from 'node:readline';
|
|
10
|
+
import { PreviewerClient, PreviewerError, newCliToken } from './api.mjs';
|
|
11
|
+
import { collectUploads } from './files.mjs';
|
|
12
|
+
import { PROJECT_FILE, findProject, resolveAuth, saveProject, saveSiteLogin } from './config.mjs';
|
|
13
|
+
|
|
14
|
+
const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
|
|
15
|
+
|
|
16
|
+
const INSTRUCTIONS = `Previewer (previewer.agency) hosts live previews of HTML5 banners, images and videos for an agency's clients: one link per campaign, where the client looks and approves.
|
|
17
|
+
Typical flow: whoami (call sign_in if not signed in; a person must approve in the browser) → list_campaigns or get_campaign → upload_folder → give the user the previewUrl.
|
|
18
|
+
A banner uploaded with the same file name replaces the existing one as a new version. Approvals are made by the client in the preview; you can read them (get_campaign) but not set them.
|
|
19
|
+
Only remove banners when the user asked for that specific banner.`;
|
|
20
|
+
|
|
21
|
+
export class ToolError extends Error {}
|
|
22
|
+
|
|
23
|
+
const object = (properties = {}, required = []) => ({ type: 'object', properties, required, additionalProperties: false });
|
|
24
|
+
const CAMPAIGN = { type: 'string', description: 'Campaign id or exact name.' };
|
|
25
|
+
const CLIENT = { type: 'string', description: 'Client id or exact name. Narrows a campaign name to one client.' };
|
|
26
|
+
const FOLDER = {
|
|
27
|
+
type: 'string',
|
|
28
|
+
description: `A folder in the project, absolute or relative to the project. Its ${PROJECT_FILE} (searched upwards) says which campaign it publishes to.`,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const errorText = (error) => {
|
|
32
|
+
if (error instanceof PreviewerError) {
|
|
33
|
+
if (error.code === 'auth') return `${error.message}\nThis computer isn't signed in to Previewer, or its token stopped working. Call sign_in.`;
|
|
34
|
+
if (error.code === 'forbidden') return `${error.message}\nThe signed-in token doesn't have the access for this (see whoami).`;
|
|
35
|
+
if (error.code === 'not_found') return `${error.message}\nCheck the id with list_campaigns; the token may not reach it.`;
|
|
36
|
+
return error.message;
|
|
37
|
+
}
|
|
38
|
+
return error instanceof ToolError ? error.message : `Unexpected error: ${error?.message ?? error}`;
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
const matchOne = (items, wanted, what) => {
|
|
42
|
+
const text = String(wanted ?? '').trim();
|
|
43
|
+
if (!text) return null;
|
|
44
|
+
if (/^\d+$/.test(text)) {
|
|
45
|
+
const byId = items.find((item) => item.id === Number(text));
|
|
46
|
+
if (byId) return byId;
|
|
47
|
+
}
|
|
48
|
+
const matches = items.filter((item) => String(item.name).toLowerCase() === text.toLowerCase());
|
|
49
|
+
if (matches.length > 1) throw new ToolError(`Several ${what}s are called "${text}". Use the id (list_${what}s shows them).`);
|
|
50
|
+
return matches[0] ?? null;
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
const campaignSummary = (campaign) => ({
|
|
54
|
+
id: campaign.id,
|
|
55
|
+
name: campaign.name,
|
|
56
|
+
client: campaign.client,
|
|
57
|
+
previewUrl: campaign.previewUrl,
|
|
58
|
+
bannerCount: campaign.bannerCount,
|
|
59
|
+
approvedCount: campaign.approvedCount,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* The server: `handle(message)` answers one JSON-RPC message (or returns null for a notification).
|
|
64
|
+
* `deps` are injectable for tests.
|
|
65
|
+
*/
|
|
66
|
+
export const createMcpServer = ({ version = '0.0.0', cwd = process.cwd(), deps = {} } = {}) => {
|
|
67
|
+
const d = {
|
|
68
|
+
resolveAuth,
|
|
69
|
+
findProject,
|
|
70
|
+
saveProject,
|
|
71
|
+
saveSiteLogin,
|
|
72
|
+
collectUploads,
|
|
73
|
+
makeClient: (options) => new PreviewerClient(options),
|
|
74
|
+
openBrowser: () => false,
|
|
75
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms).unref?.()),
|
|
76
|
+
deviceName: () => `${os.userInfo().username}@${os.hostname().replace(/\.local$/, '')} (MCP)`,
|
|
77
|
+
...deps,
|
|
78
|
+
};
|
|
79
|
+
const userAgent = `previewer-mcp/${version}`;
|
|
80
|
+
let login = null; // the sign-in in progress, if any
|
|
81
|
+
|
|
82
|
+
const folderPath = (folder) => path.resolve(cwd, folder || '.');
|
|
83
|
+
|
|
84
|
+
const connect = async (folder) => {
|
|
85
|
+
const project = await d.findProject(folderPath(folder));
|
|
86
|
+
const auth = await d.resolveAuth({ project });
|
|
87
|
+
if (!auth.token) {
|
|
88
|
+
const waiting = login?.status === 'pending' ? ` A sign-in is waiting for approval: code ${login.code} at ${login.url}.` : ' Call sign_in.';
|
|
89
|
+
throw new ToolError(`Not signed in to ${auth.site}.${waiting}`);
|
|
90
|
+
}
|
|
91
|
+
return { api: d.makeClient({ baseUrl: auth.site, token: auth.token, userAgent }), auth, project };
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
const resolveClient = async (api, wanted) => {
|
|
95
|
+
const clients = await api.clients();
|
|
96
|
+
const client = matchOne(clients, wanted, 'client');
|
|
97
|
+
if (!client) throw new ToolError(`No client "${wanted}". Clients: ${clients.map((item) => `${item.name} (${item.id})`).join(', ') || 'none'}.`);
|
|
98
|
+
return client;
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const resolveCampaign = async (api, project, args, { create = false } = {}) => {
|
|
102
|
+
const wanted = args.campaign === undefined || args.campaign === null ? '' : String(args.campaign).trim();
|
|
103
|
+
if (!wanted) {
|
|
104
|
+
if (project?.campaignId) return { campaign: await api.campaign(project.campaignId) };
|
|
105
|
+
throw new ToolError(`No campaign given, and the folder has no ${PROJECT_FILE}. Pass campaign (id or name); list_campaigns shows them.`);
|
|
106
|
+
}
|
|
107
|
+
const clientId = args.client ? (await resolveClient(api, args.client)).id : undefined;
|
|
108
|
+
const campaigns = await api.campaigns(clientId ? { clientId } : {});
|
|
109
|
+
const found = matchOne(campaigns, wanted, 'campaign');
|
|
110
|
+
if (found) return { campaign: await api.campaign(found.id) };
|
|
111
|
+
if (!create) throw new ToolError(`No campaign "${wanted}"${clientId ? ' for that client' : ''}. Pass create: true (with client) to make it.`);
|
|
112
|
+
if (!clientId) throw new ToolError(`To create campaign "${wanted}", also pass client.`);
|
|
113
|
+
return { campaign: await api.createCampaign({ clientId, name: wanted }), created: true };
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
// Writes the link next to the project when there is none yet: in the project root when the
|
|
117
|
+
// folder is inside it (./dist gets wiped by builds), otherwise in the folder itself.
|
|
118
|
+
const remember = async (site, campaign, folder) => {
|
|
119
|
+
const target = folderPath(folder);
|
|
120
|
+
const inside = !path.relative(cwd, target).startsWith('..') && !path.isAbsolute(path.relative(cwd, target));
|
|
121
|
+
const file = await d.saveProject(inside ? cwd : target, {
|
|
122
|
+
site,
|
|
123
|
+
campaignId: campaign.id,
|
|
124
|
+
clientId: campaign.client.id,
|
|
125
|
+
client: campaign.client.name,
|
|
126
|
+
campaign: campaign.name,
|
|
127
|
+
});
|
|
128
|
+
return path.relative(cwd, file) || file;
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
const startLogin = async (site) => {
|
|
132
|
+
const auth = await d.resolveAuth({ site });
|
|
133
|
+
if (login?.status === 'pending' && login.site === auth.site && Date.now() < login.expires) return login;
|
|
134
|
+
const api = d.makeClient({ baseUrl: auth.site, userAgent });
|
|
135
|
+
const { token, hash, hint } = newCliToken();
|
|
136
|
+
const started = await api.startLogin({ tokenHash: hash, tokenHint: hint, clientName: d.deviceName() });
|
|
137
|
+
const current = {
|
|
138
|
+
status: 'pending',
|
|
139
|
+
site: auth.site,
|
|
140
|
+
code: started.userCode,
|
|
141
|
+
url: `${auth.site}${started.verifyPath}`,
|
|
142
|
+
expires: Date.parse(started.expiresAt),
|
|
143
|
+
};
|
|
144
|
+
login = current;
|
|
145
|
+
current.opened = d.openBrowser(current.url);
|
|
146
|
+
// Wait for the approval in the background; the agent asks the user and checks with whoami.
|
|
147
|
+
current.done = (async () => {
|
|
148
|
+
while (Date.now() < current.expires && current.status === 'pending') {
|
|
149
|
+
await d.sleep(2000);
|
|
150
|
+
try {
|
|
151
|
+
const status = await api.loginStatus(started.requestId, token);
|
|
152
|
+
if (status === 'approved') {
|
|
153
|
+
const me = await d.makeClient({ baseUrl: auth.site, token, userAgent }).me();
|
|
154
|
+
await d.saveSiteLogin(auth.site, { token, account: me.account });
|
|
155
|
+
current.status = 'approved';
|
|
156
|
+
} else if (status !== 'pending') {
|
|
157
|
+
current.status = status;
|
|
158
|
+
}
|
|
159
|
+
} catch {
|
|
160
|
+
// A blip while polling: try again on the next round.
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
if (current.status === 'pending') current.status = 'expired';
|
|
164
|
+
})();
|
|
165
|
+
return current;
|
|
166
|
+
};
|
|
167
|
+
|
|
168
|
+
const TOOLS = [
|
|
169
|
+
{
|
|
170
|
+
name: 'whoami',
|
|
171
|
+
title: 'Previewer account',
|
|
172
|
+
description: 'Which Previewer account this computer is signed in to, and what the token may do (read, upload, manage) and reach. Call this first.',
|
|
173
|
+
inputSchema: object(),
|
|
174
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
175
|
+
run: async () => {
|
|
176
|
+
try {
|
|
177
|
+
const { api, auth } = await connect();
|
|
178
|
+
const me = await api.me();
|
|
179
|
+
return { signedIn: true, site: auth.site, account: me.account, token: me.token, fromEnvironment: auth.fromEnv };
|
|
180
|
+
} catch (error) {
|
|
181
|
+
if (error instanceof ToolError || (error instanceof PreviewerError && error.code === 'auth')) {
|
|
182
|
+
return {
|
|
183
|
+
signedIn: false,
|
|
184
|
+
signIn: login ? { status: login.status, code: login.code, url: login.url } : null,
|
|
185
|
+
next: login?.status === 'pending' ? 'Ask the user to approve the code in their browser, then call whoami again.' : 'Call sign_in.',
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
throw error;
|
|
189
|
+
}
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
{
|
|
193
|
+
name: 'sign_in',
|
|
194
|
+
title: 'Sign in to Previewer',
|
|
195
|
+
description:
|
|
196
|
+
'Start signing this computer in to Previewer. Returns a code and a link (also opened in the browser when possible). Ask the user to open the link, check that it shows the same code, and approve; only a person signed in to Previewer can. Then call whoami. The request lasts 10 minutes.',
|
|
197
|
+
inputSchema: object({ site: { type: 'string', description: 'Previewer address. Default https://previewer.agency.' } }),
|
|
198
|
+
annotations: { openWorldHint: false },
|
|
199
|
+
run: async (args) => {
|
|
200
|
+
const current = await startLogin(args.site);
|
|
201
|
+
return {
|
|
202
|
+
status: 'waiting_for_approval',
|
|
203
|
+
code: current.code,
|
|
204
|
+
url: current.url,
|
|
205
|
+
openedInBrowser: Boolean(current.opened),
|
|
206
|
+
next: `Tell the user: open ${current.url}, check the code ${current.code}, and approve. Then call whoami.`,
|
|
207
|
+
};
|
|
208
|
+
},
|
|
209
|
+
},
|
|
210
|
+
{
|
|
211
|
+
name: 'list_clients',
|
|
212
|
+
title: 'List clients',
|
|
213
|
+
description: 'The clients this token can reach, with their campaign counts.',
|
|
214
|
+
inputSchema: object(),
|
|
215
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
216
|
+
run: async () => ({ clients: await (await connect()).api.clients() }),
|
|
217
|
+
},
|
|
218
|
+
{
|
|
219
|
+
name: 'list_campaigns',
|
|
220
|
+
title: 'List campaigns',
|
|
221
|
+
description: 'Campaigns this token can reach, most recently changed first: preview link, banner count, approvals and when the client last looked.',
|
|
222
|
+
inputSchema: object({ client: CLIENT }),
|
|
223
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
224
|
+
run: async (args) => {
|
|
225
|
+
const { api } = await connect();
|
|
226
|
+
const clientId = args.client ? (await resolveClient(api, args.client)).id : undefined;
|
|
227
|
+
return { campaigns: await api.campaigns(clientId ? { clientId } : {}) };
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
{
|
|
231
|
+
name: 'get_campaign',
|
|
232
|
+
title: 'Campaign status',
|
|
233
|
+
description:
|
|
234
|
+
'One campaign: preview link, when the client last opened it, and per banner its size, kind, status (review or approved, with when), whether it has a backup image, and its file size. Without campaign, uses the campaign the folder is linked to.',
|
|
235
|
+
inputSchema: object({ campaign: CAMPAIGN, client: CLIENT, folder: FOLDER }),
|
|
236
|
+
annotations: { readOnlyHint: true, openWorldHint: false },
|
|
237
|
+
run: async (args) => {
|
|
238
|
+
const { api, project } = await connect(args.folder);
|
|
239
|
+
return { campaign: (await resolveCampaign(api, project, args)).campaign };
|
|
240
|
+
},
|
|
241
|
+
},
|
|
242
|
+
{
|
|
243
|
+
name: 'create_campaign',
|
|
244
|
+
title: 'Create campaign',
|
|
245
|
+
description: 'Create a campaign for a client (needs Manage access). Returns it with its preview link.',
|
|
246
|
+
inputSchema: object({ client: CLIENT, name: { type: 'string', description: 'Campaign name.' } }, ['client', 'name']),
|
|
247
|
+
annotations: { openWorldHint: false },
|
|
248
|
+
run: async (args) => {
|
|
249
|
+
const { api } = await connect();
|
|
250
|
+
const client = await resolveClient(api, args.client);
|
|
251
|
+
const name = String(args.name ?? '').trim();
|
|
252
|
+
if (!name) throw new ToolError('Give the campaign a name.');
|
|
253
|
+
return { campaign: campaignSummary(await api.createCampaign({ clientId: client.id, name })) };
|
|
254
|
+
},
|
|
255
|
+
},
|
|
256
|
+
{
|
|
257
|
+
name: 'link_folder',
|
|
258
|
+
title: 'Link project to campaign',
|
|
259
|
+
description: `Remember which campaign this project publishes to, in ${PROJECT_FILE} (ids and names only, safe to commit). upload_folder, get_campaign and \`npx previewer-agency push\` then use it without being told.`,
|
|
260
|
+
inputSchema: object({ campaign: CAMPAIGN, client: CLIENT, folder: FOLDER, create: { type: 'boolean', description: 'Create the campaign when no campaign has that name (needs client).' } }, ['campaign']),
|
|
261
|
+
annotations: { idempotentHint: true, openWorldHint: false },
|
|
262
|
+
run: async (args) => {
|
|
263
|
+
const { api, auth } = await connect(args.folder);
|
|
264
|
+
const { campaign, created } = await resolveCampaign(api, null, args, { create: Boolean(args.create) });
|
|
265
|
+
return { linked: await remember(auth.site, campaign, args.folder), created: Boolean(created), campaign: campaignSummary(campaign) };
|
|
266
|
+
},
|
|
267
|
+
},
|
|
268
|
+
{
|
|
269
|
+
name: 'upload_folder',
|
|
270
|
+
title: 'Upload banners',
|
|
271
|
+
description:
|
|
272
|
+
'Upload a folder to a campaign: HTML5 banner ZIPs, banner folders with an index.html (zipped for you), images and videos, and backup images (300x250.jpg next to 300x250.zip, or anything in backups/). A file named like a banner already in the campaign replaces it as a new version. Returns the preview link to give the user. Use dry_run to see what would go up.',
|
|
273
|
+
inputSchema: object(
|
|
274
|
+
{
|
|
275
|
+
folder: { ...FOLDER, description: `The folder to upload, e.g. "dist". ${FOLDER.description}` },
|
|
276
|
+
campaign: { ...CAMPAIGN, description: `${CAMPAIGN.description} Leave out to use the folder's ${PROJECT_FILE}.` },
|
|
277
|
+
client: CLIENT,
|
|
278
|
+
create: { type: 'boolean', description: 'Create the campaign when no campaign has that name (needs client).' },
|
|
279
|
+
dry_run: { type: 'boolean', description: 'List what would be uploaded; upload nothing.' },
|
|
280
|
+
},
|
|
281
|
+
['folder'],
|
|
282
|
+
),
|
|
283
|
+
annotations: { openWorldHint: false },
|
|
284
|
+
run: async (args) => {
|
|
285
|
+
const dir = folderPath(args.folder);
|
|
286
|
+
const { items, skipped } = await d.collectUploads(dir).catch((error) => {
|
|
287
|
+
throw new ToolError(error.code === 'ENOENT' ? `No folder ${dir}.` : `Could not read ${dir}: ${error.message}`);
|
|
288
|
+
});
|
|
289
|
+
const files = items.map((item) => ({ type: item.type, file: item.source ?? item.name, as: item.name, bytes: item.size }));
|
|
290
|
+
if (args.dry_run) return { dryRun: true, folder: dir, files, skipped };
|
|
291
|
+
if (items.length === 0) throw new ToolError(`Nothing to upload in ${dir}: expected ZIPs, banner folders with an index.html, images or videos.`);
|
|
292
|
+
|
|
293
|
+
const { api, auth, project } = await connect(args.folder);
|
|
294
|
+
const { campaign, created } = await resolveCampaign(api, project, args, { create: Boolean(args.create) });
|
|
295
|
+
const result = await api.upload(campaign.id, items);
|
|
296
|
+
const before = new Set((campaign.banners ?? []).map((banner) => banner.id));
|
|
297
|
+
const linked = project ? null : await remember(auth.site, result.campaign, args.folder);
|
|
298
|
+
return {
|
|
299
|
+
campaign: campaignSummary(result.campaign),
|
|
300
|
+
createdCampaign: Boolean(created),
|
|
301
|
+
uploaded: result.uploaded.length,
|
|
302
|
+
newVersions: result.uploaded.filter((id) => before.has(id)).length,
|
|
303
|
+
backups: items.filter((item) => item.type === 'backup').length,
|
|
304
|
+
skipped,
|
|
305
|
+
...(linked ? { linked } : {}),
|
|
306
|
+
};
|
|
307
|
+
},
|
|
308
|
+
},
|
|
309
|
+
{
|
|
310
|
+
name: 'remove_banner',
|
|
311
|
+
title: 'Remove banner',
|
|
312
|
+
description: 'Remove one banner and its backup image from a campaign (needs Manage access). The client no longer sees it. Only when the user asked for this banner.',
|
|
313
|
+
inputSchema: object({ campaign: CAMPAIGN, client: CLIENT, banner: { type: 'string', description: 'The banner id, as get_campaign lists it (e.g. "300x250").' } }, ['campaign', 'banner']),
|
|
314
|
+
annotations: { destructiveHint: true, idempotentHint: true, openWorldHint: false },
|
|
315
|
+
run: async (args) => {
|
|
316
|
+
const { api } = await connect();
|
|
317
|
+
const { campaign } = await resolveCampaign(api, null, args);
|
|
318
|
+
const result = await api.removeBanner(campaign.id, String(args.banner));
|
|
319
|
+
return { removed: result.removed, campaign: campaignSummary(result.campaign) };
|
|
320
|
+
},
|
|
321
|
+
},
|
|
322
|
+
];
|
|
323
|
+
|
|
324
|
+
const reply = (id, result) => ({ jsonrpc: '2.0', id, result });
|
|
325
|
+
const failure = (id, code, message) => ({ jsonrpc: '2.0', id: id ?? null, error: { code, message } });
|
|
326
|
+
|
|
327
|
+
const handle = async (message) => {
|
|
328
|
+
if (!message || typeof message !== 'object' || message.jsonrpc !== '2.0') return failure(message?.id, -32600, 'Invalid request');
|
|
329
|
+
const { id, method, params } = message;
|
|
330
|
+
const isRequest = id !== undefined && id !== null;
|
|
331
|
+
if (!isRequest) return null; // notifications (initialized, cancelled, …) need no answer
|
|
332
|
+
switch (method) {
|
|
333
|
+
case 'initialize':
|
|
334
|
+
return reply(id, {
|
|
335
|
+
protocolVersion: PROTOCOL_VERSIONS.includes(params?.protocolVersion) ? params.protocolVersion : PROTOCOL_VERSIONS[0],
|
|
336
|
+
capabilities: { tools: { listChanged: false } },
|
|
337
|
+
serverInfo: { name: 'previewer', title: 'Previewer', version },
|
|
338
|
+
instructions: INSTRUCTIONS,
|
|
339
|
+
});
|
|
340
|
+
case 'ping':
|
|
341
|
+
return reply(id, {});
|
|
342
|
+
case 'tools/list':
|
|
343
|
+
return reply(id, { tools: TOOLS.map((tool) => Object.fromEntries(Object.entries(tool).filter(([key]) => key !== 'run'))) });
|
|
344
|
+
case 'tools/call': {
|
|
345
|
+
const tool = TOOLS.find((item) => item.name === params?.name);
|
|
346
|
+
if (!tool) return failure(id, -32602, `Unknown tool: ${params?.name}`);
|
|
347
|
+
try {
|
|
348
|
+
const result = await tool.run(params.arguments && typeof params.arguments === 'object' ? params.arguments : {});
|
|
349
|
+
return reply(id, { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] });
|
|
350
|
+
} catch (error) {
|
|
351
|
+
return reply(id, { content: [{ type: 'text', text: errorText(error) }], isError: true });
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
default:
|
|
355
|
+
return failure(id, -32601, `Method not found: ${method}`);
|
|
356
|
+
}
|
|
357
|
+
};
|
|
358
|
+
|
|
359
|
+
return { handle, tools: TOOLS, _login: () => login };
|
|
360
|
+
};
|
|
361
|
+
|
|
362
|
+
/** Serve `server` on newline-delimited JSON over stdio until stdin closes. */
|
|
363
|
+
export const runStdio = (server, { input = process.stdin, output = process.stdout } = {}) =>
|
|
364
|
+
new Promise((resolve) => {
|
|
365
|
+
const lines = createInterface({ input, crlfDelay: Infinity });
|
|
366
|
+
const write = (message) => output.write(`${JSON.stringify(message)}\n`);
|
|
367
|
+
const pending = new Set();
|
|
368
|
+
lines.on('line', (line) => {
|
|
369
|
+
if (!line.trim()) return;
|
|
370
|
+
let message;
|
|
371
|
+
try {
|
|
372
|
+
message = JSON.parse(line);
|
|
373
|
+
} catch {
|
|
374
|
+
write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
const work = (Array.isArray(message) ? Promise.all(message.map(server.handle)) : server.handle(message)).then((answer) => {
|
|
378
|
+
const out = Array.isArray(answer) ? answer.filter(Boolean) : answer;
|
|
379
|
+
if (out && (!Array.isArray(out) || out.length)) write(out);
|
|
380
|
+
});
|
|
381
|
+
pending.add(work);
|
|
382
|
+
work.finally(() => pending.delete(work));
|
|
383
|
+
});
|
|
384
|
+
lines.on('close', () => Promise.allSettled([...pending]).then(resolve));
|
|
385
|
+
});
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "previewer-agency",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Upload HTML5 banners, images and videos to Previewer from any folder or
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Upload HTML5 banners, images and videos to Previewer from any folder, CI job or AI agent (MCP), and check approvals.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"previewer": "bin/previewer.mjs"
|
|
@@ -26,7 +26,9 @@
|
|
|
26
26
|
"html5",
|
|
27
27
|
"preview",
|
|
28
28
|
"ads",
|
|
29
|
-
"previewer"
|
|
29
|
+
"previewer",
|
|
30
|
+
"mcp",
|
|
31
|
+
"mcp-server"
|
|
30
32
|
],
|
|
31
33
|
"homepage": "https://previewer.agency/docs/api",
|
|
32
34
|
"license": "UNLICENSED"
|