ContentBox.js · Guide
Let the people who use your site ask Claude to change the page they have open in the ContentBox.js editor. Claude adds, rewrites and removes sections while they watch, and the editor's Undo takes any change back. In this guide we add it to a Node.js site that already has the editor and a login.
Live editing comes in two parts:
The connector
An MCP connector that runs on your server at /mcp. Claude connects to it, the user logs in with their own account, and Claude gets the tools to work on that user's open page.
The bridge
A small script on the editor page. It receives Claude's changes and makes them with the editor's own methods, so they behave like the user's own edits.
In this guide
Before the code, here is what happens when a user asks Claude for a change. The prompt: "Make the title bigger, then add a paragraph under it, and save."
get_section needs a section number./mcp/bridge and keeps it openonSave code, the same as clicking its Save buttonSteps 2 to 6 are one loop: Claude calls a tool, reads the result, and decides the next call. A prompt with several requests is simply more turns of that loop, all within the same reply.
Step 1
The connector is written for Node.js with Express. Install the MCP SDK (the standard way Claude talks to a connector), the WebSocket library and Zod:
npm install @modelcontextprotocol/sdk ws zod@3Your site already has Express, a session middleware (for example express-session) and the ContentBox.js editor.
Then copy the docs/context folder from the ContentBox.js ZIP package, which you can download from your user area, into your project. These are the framework guides Claude reads before it writes markup (step 4).
The files you will add:
mcp/site.js the connector
mcp/tools.js what Claude can do on the page
mcp/docs.js the framework guides, for Claude
mcp/store.js where Claude's keys are kept
docs/context/ from the ContentBox.js package
public/mcp/bridge.js the bridge, loaded by the editor pageStep 2
mcp/site.js adds the routes Claude uses: the Connect and Allow pages, the keys, the tool calls at /mcp, and the live link to the editor page at /mcp/bridge. It does no logins itself: your site tells it who is logged in (step 6).
After the user clicks Allow, Claude gets an access key (one hour) and a renewal key (90 days). Your database keeps only their fingerprints, so a stolen database copy holds no usable keys.
/*
The Claude connector: lets a user's Claude (claude.ai > Settings > Connectors >
Add custom connector > https://<site>/mcp) edit that user's open editor page.
It does no logins itself. The site tells it, through these hooks:
getUser(req) the logged-in user { id, email } of a request, or null
loginUrl(returnTo) the site's login page, coming back to returnTo after
session the site's session middleware, so the editor page's
WebSocket sees the same login as every other request
store where Claude's apps and keys are kept, in your database,
including hasKeys(userId): has this user connected Claude?
renderAllow({ user, requestId }) optional: the "Allow Claude" page
attachMcp(app, httpServer, { getUser, loginUrl, session, store })
How the keys work: on Allow, the site gives Claude an access key (1 hour, sent
with every tool call) and a renewal key (90 days, used only to get new keys).
Claude keeps both; the store keeps only their fingerprints, with the user.
Routes added: /mcp (tool calls), /mcp/authorize (Connect page), /mcp/allow,
/mcp/token (gives out keys), /mcp/register, /mcp/revoke, /mcp/bridge (the
editor page's WebSocket) and the two OAuth discovery documents under /.well-known/.
*/
import express from 'express';
import { randomBytes, createHash } from 'node:crypto';
import http from 'node:http';
import { WebSocketServer } from 'ws';
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
import { authorizationHandler } from '@modelcontextprotocol/sdk/server/auth/handlers/authorize.js';
import { tokenHandler } from '@modelcontextprotocol/sdk/server/auth/handlers/token.js';
import { clientRegistrationHandler } from '@modelcontextprotocol/sdk/server/auth/handlers/register.js';
import { revocationHandler } from '@modelcontextprotocol/sdk/server/auth/handlers/revoke.js';
import { InvalidGrantError, InvalidTokenError } from '@modelcontextprotocol/sdk/server/auth/errors.js';
import { createMcpServer, createPageLink } from './tools.js';
const ACCESS_TTL = 60 * 60; // 1 hour
const RENEWAL_TTL = 90 * 24 * 60 * 60; // 90 days
const CODE_TTL = 5 * 60;
const REQUEST_TTL = 10 * 60;
const fingerprint = (key) => createHash('sha256').update(key).digest('hex');
const newKey = () => randomBytes(32).toString('base64url');
const now = () => Math.floor(Date.now() / 1000);
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', '\'': ''' }[c]));
const defaultAllowPage = ({ user, requestId }) => `<!DOCTYPE html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Connect Claude</title></head>
<body style="font-family:system-ui,sans-serif;max-width:360px;margin:10vh auto;padding:0 16px">
<form method="post" action="/mcp/allow">
<h1 style="font-size:20px;font-weight:500">Connect Claude</h1>
<p>Logged in as <b>${esc(user.email || user.id)}</b>. Claude is asking to edit your pages on this website.</p>
<input type="hidden" name="request" value="${esc(requestId)}">
<button type="submit" name="answer" value="deny">Cancel</button>
<button type="submit" name="answer" value="allow" autofocus>Allow</button>
</form>
</body></html>`;
export function attachMcp(app, httpServer, { getUser, loginUrl, session, store, renderAllow = defaultAllowPage }) {
const codes = new Map(); // one-time code after Allow -> { clientId, userId, params, expiresAt }
const requests = new Map(); // Connect request waiting for Allow -> { clientId, userId, params, expiresAt }
/* ---- keys ---- */
const issueKeys = (clientId, userId, scopes) => {
const access = newKey();
const renewal = newKey();
const t = now();
store.saveKey(fingerprint(access), { kind: 'access', clientId, userId, scopes, expiresAt: t + ACCESS_TTL });
store.saveKey(fingerprint(renewal), { kind: 'renewal', clientId, userId, scopes, expiresAt: t + RENEWAL_TTL });
return {
access_token: access,
token_type: 'bearer',
expires_in: ACCESS_TTL, // this is how Claude knows when to renew
refresh_token: renewal,
scope: scopes.join(' '),
};
};
const findKey = (key, kind) => {
const record = store.getKey(fingerprint(key));
return record && record.kind === kind && record.expiresAt > now() ? record : null;
};
/* ---- what the OAuth handlers from the MCP SDK call ---- */
const provider = {
clientsStore: {
getClient: async (id) => store.getClient(id),
registerClient: async (client) => { store.saveClient(client); return client; },
},
// The Connect page. Not logged in: off to the site's login, and back here after.
async authorize(client, params, res) {
const req = res.req;
const user = await getUser(req);
if(!user) {
res.redirect(loginUrl(req.originalUrl));
return;
}
const requestId = newKey();
requests.set(requestId, { clientId: client.client_id, userId: String(user.id), params, expiresAt: now() + REQUEST_TTL });
res.type('html').send(renderAllow({ user, requestId }));
},
async challengeForAuthorizationCode(client, code) {
const c = codes.get(code);
if(!c || c.clientId !== client.client_id || c.expiresAt < now()) throw new InvalidGrantError('Invalid authorization code');
return c.params.codeChallenge;
},
// The first pair of keys, right after Allow.
async exchangeAuthorizationCode(client, code) {
const c = codes.get(code);
codes.delete(code);
if(!c || c.clientId !== client.client_id || c.expiresAt < now()) throw new InvalidGrantError('Invalid authorization code');
const keys = issueKeys(client.client_id, c.userId, c.params.scopes || []);
linkFor(c.userId).tell({ status: { claude: true } }); // an open editor shows "connected" right away
return keys;
},
// Renewal: Claude shows its renewal key and gets a new pair. The old renewal key stops working.
async exchangeRefreshToken(client, renewalKey) {
const r = findKey(renewalKey, 'renewal');
if(!r || r.clientId !== client.client_id) throw new InvalidGrantError('Invalid renewal key');
store.deleteKey(fingerprint(renewalKey));
return issueKeys(client.client_id, r.userId, r.scopes);
},
async verifyAccessToken(accessKey) {
const a = findKey(accessKey, 'access');
if(!a) throw new InvalidTokenError('This key has expired or is not valid');
return { token: accessKey, clientId: a.clientId, scopes: a.scopes, expiresAt: a.expiresAt, extra: { userId: a.userId } };
},
async revokeToken(client, { token }) {
const record = store.getKey(fingerprint(token));
if(record && record.clientId === client.client_id) store.deleteKey(fingerprint(token));
},
};
const baseUrl = (req) => `${req.protocol}://${req.get('host')}`;
/* ---- discovery: how Claude finds the Connect page and the key endpoint ---- */
app.get('/.well-known/oauth-protected-resource/mcp', (req, res) => {
const base = baseUrl(req);
res.json({ resource: `${base}/mcp`, authorization_servers: [base], resource_name: 'ContentBox' });
});
app.get('/.well-known/oauth-authorization-server', (req, res) => {
const base = baseUrl(req);
res.json({
issuer: base,
authorization_endpoint: `${base}/mcp/authorize`,
token_endpoint: `${base}/mcp/token`,
registration_endpoint: `${base}/mcp/register`,
revocation_endpoint: `${base}/mcp/revoke`,
response_types_supported: ['code'],
grant_types_supported: ['authorization_code', 'refresh_token'],
code_challenge_methods_supported: ['S256'],
token_endpoint_auth_methods_supported: ['client_secret_post', 'none'],
revocation_endpoint_auth_methods_supported: ['client_secret_post'],
});
});
app.use('/mcp/authorize', authorizationHandler({ provider }));
app.use('/mcp/token', tokenHandler({ provider }));
app.use('/mcp/register', clientRegistrationHandler({ clientsStore: provider.clientsStore }));
app.use('/mcp/revoke', revocationHandler({ provider }));
// The Allow page posts here.
app.post('/mcp/allow', express.urlencoded({ extended: false }), async (req, res) => {
const requestId = req.body && req.body.request;
const r = requestId && requests.get(requestId);
requests.delete(requestId);
const user = await getUser(req);
if(!r || r.expiresAt < now() || !user || String(user.id) !== r.userId) {
res.status(400).type('text').send('This request has expired. Connect again from Claude.');
return;
}
const target = new URL(r.params.redirectUri);
if(r.params.state !== undefined) target.searchParams.set('state', r.params.state);
if(req.body.answer !== 'allow') {
target.searchParams.set('error', 'access_denied');
res.redirect(target.href);
return;
}
const code = newKey();
codes.set(code, { clientId: r.clientId, userId: r.userId, params: r.params, expiresAt: now() + CODE_TTL });
target.searchParams.set('code', code);
res.redirect(target.href);
});
/* ---- one editor page link per user ---- */
const links = new Map(); // userId -> link to that user's open editor page
const linkFor = (userId) => {
if(!links.has(userId)) {
links.set(userId, createPageLink({
notConnected: 'No editor page is open. Open one of your pages in the editor, then try again.',
}));
}
return links.get(userId);
};
/* ---- tool calls: every one carries the access key ---- */
const requireKey = async (req, res, next) => {
const m = /^Bearer (.+)$/i.exec(req.headers.authorization || '');
try {
if(!m) throw new InvalidTokenError('Missing key');
req.auth = await provider.verifyAccessToken(m[1]);
next();
} catch(e) {
res.set('WWW-Authenticate', `Bearer error="invalid_token", resource_metadata="${baseUrl(req)}/.well-known/oauth-protected-resource/mcp"`);
res.status(401).json({ error: 'invalid_token', error_description: e.message });
}
};
app.post('/mcp', express.json({ limit: '10mb' }), requireKey, async (req, res) => {
const server = createMcpServer(linkFor(req.auth.extra.userId).call);
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
res.on('close', () => { transport.close(); server.close(); });
try {
await server.connect(transport);
await transport.handleRequest(req, res, req.body);
} catch(e) {
if(!res.headersSent) res.status(500).json({ jsonrpc: '2.0', error: { code: -32603, message: 'Internal error' }, id: null });
}
});
app.all('/mcp', (req, res) => res.status(405).set('Allow', 'POST').end());
/* ---- the editor page connects here, as the logged-in user ---- */
const sameSite = (req) => {
try { return new URL(req.headers.origin).host === req.headers.host; } catch(e) { return false; }
};
const refuse = (socket) => {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
};
const wss = new WebSocketServer({ noServer: true });
httpServer.on('upgrade', (req, socket, head) => {
if(new URL(req.url, 'http://x').pathname !== '/mcp/bridge') return;
if(!sameSite(req)) return refuse(socket);
// The site's session middleware reads the login cookie, exactly as on a normal request.
session(req, new http.ServerResponse(req), async () => {
const user = await getUser(req);
if(!user) return refuse(socket);
wss.handleUpgrade(req, socket, head, (ws) => {
const link = linkFor(String(user.id));
link.attach(ws);
link.tell({ status: { claude: store.hasKeys(String(user.id)) } });
});
});
});
}Step 3
mcp/tools.js lists what Claude can do. Each tool is forwarded to the bridge on the user's editor page, which makes the change. Claude works on one section at a time, so the rest of the page stays exactly as it was. The instructions at the top tell Claude how to work with ContentBox.js markup.
/*
The tools Claude gets (used by mcp/site.js).
`call(command, args)` forwards a command to the editor page and resolves with
its answer (public/mcp/bridge.js is the page side).
*/
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
import { z } from 'zod';
import { topics, topicList } from './docs.js';
export const instructions = `Edits the page currently open in the ContentBox editor, live.
HOW TO WORK
- Call get_outline first, and read a section with get_section before changing it.
- Make the smallest change: replace one section rather than rebuilding the page.
- New content matches what is already there (palette, spacing, type scale): read an existing section first.
- Changes are not saved until save is called. Every change can be undone.
MARKUP (Content.css and Box framework, NOT Tailwind)
- A page is a series of sections: <div class="is-section ...">. Every section tool takes or returns exactly one section, including its own tag.
- Use only documented classes; inline styles are allowed, invented classes are not.
- Keep animation attributes (data-fx-*) already on markup you edit, unless the request is about motion.
- Before writing markup that uses classes you have not seen on this page, load the needed topics with get_framework_docs: "box" and "design" before adding or restructuring a section, "animation" before any motion. Load each topic once per conversation.`;
export function createMcpServer(call) {
const server = new McpServer({ name: 'contentbox', version: '1.0.0' }, { instructions });
const tool = (name, description, inputSchema, run) => {
server.registerTool(name, { description, inputSchema }, async (args) => {
try {
const result = await run(args || {});
const text = typeof result === 'string' ? result : JSON.stringify(result, null, 2);
return { content: [{ type: 'text', text: text || 'OK' }] };
} catch(err) {
return { content: [{ type: 'text', text: err.message }], isError: true };
}
});
};
const sectionIndex = z.number().int().min(1).describe('1-based section number, as listed by get_outline');
const sectionMarkup = z.string().describe('A single <div class="is-section ...">...</div>');
tool('get_outline',
'List every section of the page, one line each: number, type, heading, background, image.',
{}, () => call('get_outline'));
tool('get_selection',
'What the user has selected in the editor: the section number and the element being edited.',
{}, () => call('get_selection'));
tool('get_section',
'Read the full HTML of one section.',
{ section: sectionIndex }, (a) => call('get_section', a));
tool('replace_section',
'Replace one section with new HTML. Every other section is left untouched.',
{ section: sectionIndex, html: sectionMarkup }, (a) => call('replace_section', a));
tool('insert_section',
'Add a new section. "at" is the position it should end up at (1 = top); omit it to add at the end.',
{ html: sectionMarkup, at: z.number().int().min(1).optional() },
(a) => call('insert_section', a));
tool('delete_section',
'Remove one section.',
{ section: sectionIndex }, (a) => call('delete_section', a));
tool('get_page_styles',
'The page\'s saved global CSS (mainCss and sectionCss). Only needed for site-wide styling; a section\'s look is better learned by reading it.',
{}, () => call('get_page_styles'));
tool('get_framework_docs',
`Framework reference. Ask only for the topics the task needs; several in one call:\n${topicList}`,
{ topics: z.array(z.enum(Object.keys(topics))).min(1) },
({ topics: wanted }) => wanted.map(k => topics[k].text).join('\n\n'));
tool('undo', 'Undo the last change.', {}, () => call('undo'));
tool('redo', 'Redo the last undone change.', {}, () => call('redo'));
tool('save',
'Save the page the way the editor page saves it (same as clicking its Save button).',
{}, () => call('save'));
return server;
}
/*
Holds the connection to the editor page and forwards commands to it. One page
at a time: the most recently opened one.
*/
export function createPageLink({ notConnected }) {
const TIMEOUT = 30000;
let page = null;
let nextId = 1;
const pending = new Map(); // id -> { resolve, reject, timer }
const attach = (ws) => {
page = ws;
ws.on('message', (data) => {
let msg;
try { msg = JSON.parse(data.toString()); } catch(e) { return; }
const p = pending.get(msg.id);
if(!p) return;
pending.delete(msg.id);
clearTimeout(p.timer);
if(msg.error) p.reject(new Error(msg.error));
else p.resolve(msg.result);
});
ws.on('close', () => {
if(page === ws) page = null;
});
};
const call = (command, args = {}) => new Promise((resolve, reject) => {
if(!page || page.readyState !== 1) {
reject(new Error(typeof notConnected === 'function' ? notConnected() : notConnected));
return;
}
const id = nextId++;
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`The editor page did not answer "${command}" within ${TIMEOUT / 1000}s.`));
}, TIMEOUT);
pending.set(id, { resolve, reject, timer });
page.send(JSON.stringify({ id, command, args }));
});
// A message that is not an answer to a command, e.g. { status: { claude: true } }.
const tell = (msg) => {
if(page && page.readyState === 1) page.send(JSON.stringify(msg));
};
return { attach, call, tell };
}Step 4
mcp/docs.js reads the docs/context folder you copied in step 1: the same text the editor's built-in AI assistant reads. Claude loads only the topics a request needs, so a change to a title does not cost the whole framework.
/*
The framework guides for Claude: the docs/context folder that comes with the
editor package (the same text the editor's built-in AI assistant reads).
Point CONTEXT_DIR at that folder. When you update the editor, copy its new
docs/context folder too, so Claude writes markup for the version your site runs.
content.md is split at its "## " headings into small topics, so Claude loads
only what a request needs (a title size needs "typography", not the whole
framework). The other files are one topic each.
*/
import fs from 'node:fs';
import path from 'node:path';
const CONTEXT_DIR = path.resolve('docs/context');
// What each file is for, shown to Claude in the topic list.
const titles = {
box: 'Box framework: section and box structure, layout, width, backgrounds, light and dark. Load before adding or restructuring a section',
animation: 'Animation framework (data-fx): scroll and pinned motion. Load before adding, changing or removing any animation',
'motion-path': 'Motion path (data-fx-path): an object travelling a route. Also load it when markup you edit has data-fx-path',
design: 'Design guide: output format and quality bar for new content',
code: 'Code blocks (data-cb-code): elements that need JavaScript',
'3d': '3D scenes with three.js',
games: 'Building games, 2D and 3D',
};
const slug = (heading) => heading.toLowerCase().replace(/\bsystem\b/, '').trim().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
const splitSections = (text) => {
const parts = {};
for(const chunk of text.split(/^## /m).slice(1)) {
const heading = chunk.slice(0, chunk.indexOf('\n')).trim();
// Sub-headings go in the title, so a topic's whole content is visible from the list.
const subs = (chunk.match(/^### .+$/gm) || []).map(h => h.slice(4).trim());
parts[slug(heading)] = {
title: subs.length ? `${heading}: ${subs.join(', ')}` : heading,
text: ('## ' + chunk).replace(/\n---\s*$/, '').trim(),
};
}
return parts;
};
const read = (file) => fs.readFileSync(path.join(CONTEXT_DIR, file), 'utf8').trim();
const guides = {};
for(const file of fs.readdirSync(CONTEXT_DIR).sort()) {
if(!file.endsWith('.md') || file === 'README.md' || file === 'content.md') continue;
const key = file === 'design-core.md' ? 'design' : file.slice(0, -3);
const text = read(file);
guides[key] = { title: titles[key] || text.split('\n')[0].replace(/^#+\s*/, ''), text };
}
// Content.css has its own "Animation" (hover and transition classes); it must not take the animation framework's name.
const contentTopics = {};
for(const [key, t] of Object.entries(splitSections(read('content.md')))) {
if(guides[key]) contentTopics['content-' + key] = { ...t, title: t.title + ' (Content.css classes)' };
else contentTopics[key] = t;
}
export const topics = { ...contentTopics, ...guides };
// "typography (~450 tokens)" for each topic, for the tool description.
export const topicList = Object.entries(topics)
.map(([key, t]) => `- ${key}: ${t.title} (~${Math.round(t.text.length / 4 / 50) * 50 || 50} tokens)`)
.join('\n');When you update ContentBox.js, copy its new docs/context folder too. Claude then writes markup for the version your site runs.
Step 5
mcp/store.js is where the connector keeps the apps that connect (Claude registers itself the first time) and the fingerprints of their keys. The example keeps them in memory; on your site, keep the same six functions on your database, so users stay connected when the server restarts.
/*
Where the connector keeps Claude's apps and keys. Shown here with Maps, which
forget everything on a restart (users would have to connect Claude again).
On your site, keep the same six functions on your database.
*/
const clients = new Map(); // client_id -> the app's registration
const keys = new Map(); // key fingerprint -> { kind, clientId, userId, scopes, expiresAt }
export const mcpStore = {
getClient: (id) => clients.get(id),
saveClient: (client) => { clients.set(client.client_id, client); },
getKey: (fingerprint) => keys.get(fingerprint) || null,
saveKey: (fingerprint, record) => { keys.set(fingerprint, record); },
deleteKey: (fingerprint) => { keys.delete(fingerprint); },
// Has this user connected Claude? Any renewal key that has not run out.
hasKeys: (userId) => [...keys.values()].some(k => k.userId === userId && k.kind === 'renewal' && k.expiresAt * 1000 > Date.now()),
};Step 6
In your server, attach the connector to your Express app and its HTTP server, and pass four things from your own site:
import { attachMcp } from './mcp/site.js';
import { mcpStore } from './mcp/store.js';
// Behind a proxy (nginx, a tunnel), trust it, so the connector sees https.
app.set('trust proxy', 'loopback');
app.use(sessionMiddleware);
const httpServer = app.listen(PORT);
attachMcp(app, httpServer, {
getUser: (req) => currentUser(req), // the logged-in user { id, email }, or null
loginUrl: (returnTo) => '/login?next=' + encodeURIComponent(returnTo), // your login page, coming back after
session: sessionMiddleware, // your session middleware
store: mcpStore, // step 5
});returnTo after logging in.{ user, requestId } and must post the form fields shown in defaultAllowPage.Step 7
Save this as public/mcp/bridge.js:
/*
Connects this editor page to the website's Claude connector (mcp/site.js), so
Claude can edit the page live.
<script src="mcp/bridge.js"></script>
<script>
connectClaudeBridge(() => builder, {
onSave: () => saveMyPage(), // your save code
onStatus: (connected) => { ... }, // optional: whether Claude is connected
});
</script>
The first argument returns the current ContentBox instance (a function, so
a destroyed and re-created builder keeps working).
*/
(function() {
function connectClaudeBridge(getBuilder, opts) {
opts = opts || {};
const url = location.origin.replace(/^http/, 'ws') + (opts.url || '/mcp/bridge');
let ws = null;
let retry = 1000;
const need = () => {
const builder = getBuilder();
if(!builder) throw new Error('The editor is not running on the page.');
return builder;
};
const sectionAt = (builder, n) => {
const node = builder.getSectionNodes()[n - 1];
if(!node) throw new Error(`There is no section ${n}. The page has ${builder.getSectionNodes().length} sections.`);
return node;
};
/*
Checks that the HTML is one section and adds the editor's defaults:
a text size on every container, autofit boxes, and a hover fill that
reaches the edge of outline buttons.
*/
const prepare = (html) => {
const holder = document.createElement('div');
holder.innerHTML = String(html || '').trim();
const found = holder.querySelectorAll('.is-section');
if(found.length !== 1) throw new Error('The HTML must contain exactly one <div class="is-section ...">.');
const section = found[0];
section.querySelectorAll('div.is-container').forEach(c => {
if(![...c.classList].some(x => /^size-\d/.test(x))) c.classList.add('size-17');
if(![...c.classList].some(x => /^leading-\d/.test(x))) c.classList.add('leading-17');
});
section.querySelectorAll('.is-box').forEach(box => {
box.classList.add('box-autofit');
if(box.querySelector('.is-overlay-bg')) box.classList.add('min-height-70');
});
section.querySelectorAll('a[role="button"], button').forEach(el => {
if(!el.classList.contains('border-current')) return;
if([...el.classList].some(c => c.startsWith('hover:border-'))) return;
if((el.getAttribute('data-cb-hover') || '').split(/\s+/).includes('border')) return;
el.classList.add('hover:border-transparent');
});
return section.outerHTML;
};
const commands = {
get_outline() {
return need().sectionSkeleton() || '(the page is empty)';
},
get_selection() {
const builder = need();
const sections = builder.getSectionNodes();
const active = builder.activeSection && builder.resolveSection(builder.activeSection);
const index = active ? sections.indexOf(active) + 1 : 0;
const el = builder.editor && builder.editor.activeElement;
if(!index && !(el && el.isConnected)) return 'Nothing is selected.';
const result = { section: index || null };
if(el && el.isConnected) {
const text = (el.textContent || '').trim().replace(/\s+/g, ' ');
result.element = {
tag: el.tagName.toLowerCase(),
class: Array.from(el.classList).filter(c => c !== 'elm-active').join(' '),
text: text.length > 200 ? text.slice(0, 200) + '…' : text,
};
}
return result;
},
get_section({ section }) {
const builder = need();
return builder.sectionHtml(sectionAt(builder, section));
},
replace_section({ section, html }) {
const builder = need();
const node = sectionAt(builder, section);
builder.applySectionHtml(node, prepare(html));
return `Section ${section} replaced.`;
},
insert_section({ html, at }) {
const builder = need();
const node = builder.insertSectionHtml(prepare(html), at);
if(!node) throw new Error('The HTML did not contain a section.');
return `Section added at position ${builder.getSectionNodes().indexOf(node) + 1}.`;
},
delete_section({ section }) {
const builder = need();
builder.deleteSection(sectionAt(builder, section));
return `Section ${section} removed.`;
},
get_page_styles() {
const builder = need();
return { mainCss: builder.mainCss(), sectionCss: builder.sectionCss() };
},
undo() {
need().undo();
return 'Undone.';
},
redo() {
need().redo();
return 'Redone.';
},
save() {
need();
if(!opts.onSave) throw new Error('This page has no save action.');
return Promise.resolve(opts.onSave()).then(() => 'Saved.');
},
};
const connect = () => {
ws = new WebSocket(url);
ws.onopen = () => {
retry = 1000;
// The site then says whether this user has connected Claude (below).
};
ws.onmessage = async (e) => {
let msg;
try { msg = JSON.parse(e.data); } catch(err) { return; }
if(msg.status) {
if(opts.onStatus) opts.onStatus(!!msg.status.claude);
return;
}
const reply = { id: msg.id };
try {
const fn = commands[msg.command];
if(!fn) throw new Error(`Unknown command: ${msg.command}`);
reply.result = await fn(msg.args || {});
} catch(err) {
reply.error = err.message || String(err);
}
ws.send(JSON.stringify(reply));
};
// The site may restart or the network drop: keep trying quietly.
ws.onclose = () => {
if(opts.onStatus) opts.onStatus(false);
setTimeout(connect, retry);
retry = Math.min(retry * 2, 10000);
};
};
connect();
}
window.connectClaudeBridge = connectClaudeBridge;
})();Load it on your editor page, after the editor, and give it your save code:
<script src="/mcp/bridge.js"></script>
<script>
connectClaudeBridge(() => builder, {
onSave: () => saveMyPage(), // your save code, the same as your Save button
onStatus: (connected) => { // optional: show whether Claude is connected
document.querySelector('#claude-status').textContent = connected ? 'Claude: connected' : '';
},
});
</script>builder is your ContentBox.js instance. Claude's changes are saved only through onSave: when the user saves, or asks Claude to.
Step 8
Claude connects to websites on the internet, not to a computer. On your live site, use its own address. To test on your computer, give the site a temporary public address with a tunnel, for example Cloudflare's free tunnel:
cloudflared tunnel --url http://localhost:3000/mcp, for example https://www.example.com/mcp.Claude Code connects to the same address:
claude mcp add --transport http mysite https://www.example.com/mcpThen run /mcp in Claude Code, choose the site, log in and click Allow.
If you need help, we provide a custom support service (setting up the connector for you, making sure it is safe, and adding the tools you need). Email support@innovastudio.com.