@divlet/mcp 0.0.0-stage → 0.0.2

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 CHANGED
@@ -1,3 +1,13 @@
1
- # Temporary Holding Version
1
+ # @divlet/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
+ The MCP stdio adapter for divlet. This package owns its implementation and depends on the exact matching `@divlet/core` product version; the core does not contain another copy.
4
+
5
+ Install:
6
+
7
+ ```bash
8
+ npx -y @divlet/mcp@0.0.1 --cwd ./workspace
9
+ ```
10
+
11
+ The installed binary is `divlet-mcp`. Importing the package exposes `runMcp` without starting a service; the executable starts it explicitly. Protocol output uses stdout; diagnostics use stderr. Checkout commands use `node scripts/source.mjs mcp/index.js` from the repository root.
12
+
13
+ Shared development, release notes and publication guidance live in the [divlet repository](https://github.com/llblab/divlet).
package/dist/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 divlet contributors
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.
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ export function runMcp(argv?: string[]): {
3
+ session: import("@divlet/core/contract").Session;
4
+ server: {
5
+ receive(line: any): Promise<void>;
6
+ readonly sampling: boolean;
7
+ request: (method: any, params: any, { timeout }?: {
8
+ timeout?: number | undefined;
9
+ }) => Promise<any>;
10
+ readonly initialized: boolean;
11
+ tools: import("@divlet/core/contract").Tool[];
12
+ };
13
+ };
14
+ export let session: any;
15
+ export let server: any;
package/dist/index.js ADDED
@@ -0,0 +1,132 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ * divlet over MCP (stdio), for any MCP client: Claude Desktop, an editor, a script.
4
+ *
5
+ * npx -y @divlet/mcp [--cwd <dir>] [--project <file.divlet>] [--port <0..65535>] [--no-demo]
6
+ *
7
+ * Nothing starts at import time: the board opens when a tool asks for it, and the process ends when stdin closes or a
8
+ * termination signal arrives, closing only the boards it owns (a board another client owns keeps running for that client).
9
+ */
10
+ import path from 'node:path';
11
+ import { createSession } from '@divlet/core/contract';
12
+ import { createMcpServer, localBoardOpener, wireBoardAgent } from './lib/server.js';
13
+ import metadata from '#package' with { type: 'json' };
14
+ const VERSION = metadata.version;
15
+ function parseArgs(argv) {
16
+ const options = { cwd: process.cwd(), project: undefined, port: 0, createDemo: true };
17
+ for (let i = 0; i < argv.length; i++) {
18
+ const arg = argv[i];
19
+ if (arg === '--help' || arg === '-h') {
20
+ options.help = true;
21
+ continue;
22
+ }
23
+ if (arg === '--version' || arg === '-v') {
24
+ options.version = true;
25
+ continue;
26
+ }
27
+ const value = argv[i + 1];
28
+ if (arg === '--cwd' && value) {
29
+ options.cwd = path.resolve(value);
30
+ i++;
31
+ continue;
32
+ }
33
+ if (arg === '--project' && value) {
34
+ options.project = value;
35
+ i++;
36
+ continue;
37
+ }
38
+ if (arg === '--port' && value) {
39
+ options.port = Number(value);
40
+ i++;
41
+ continue;
42
+ }
43
+ if (arg === '--no-demo') {
44
+ options.createDemo = false;
45
+ continue;
46
+ }
47
+ if (arg.startsWith('--'))
48
+ throw new Error(`Unknown option: ${arg}`);
49
+ }
50
+ if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535)
51
+ throw new Error('--port takes 0..65535.');
52
+ return options;
53
+ }
54
+ const HELP = `divlet-mcp — divlet over MCP (stdio)
55
+
56
+ Usage: divlet-mcp [options]
57
+ --cwd <dir> working directory for relative paths and the default project (default: the current one)
58
+ --project <path> open this project the first time a tool needs one
59
+ --port <n> port for the board the first open starts (0 picks a free one)
60
+ --no-demo do not seed a starter frame when a new project is created
61
+ --help, --version
62
+
63
+ Speaks MCP on stdin/stdout; diagnostics go to stderr. The board is the single writer of its project: if another client
64
+ already opened it, tool calls are forwarded to that board instead of opening a second one.`;
65
+ let session, server;
66
+ export function runMcp(argv = process.argv.slice(2)) {
67
+ const options = (() => {
68
+ try {
69
+ return parseArgs(argv);
70
+ }
71
+ catch (error) {
72
+ process.stderr.write(`divlet-mcp: ${error.message}\n`);
73
+ process.exit(2);
74
+ }
75
+ })();
76
+ if (options.help) {
77
+ process.stdout.write(HELP + '\n');
78
+ process.exit(0);
79
+ }
80
+ if (options.version) {
81
+ process.stdout.write(VERSION + '\n');
82
+ process.exit(0);
83
+ }
84
+ const log = message => process.stderr.write(`${message}\n`);
85
+ session = createSession({
86
+ cwd: options.cwd,
87
+ openBoard: localBoardOpener(),
88
+ // A board this server owns gets this client as its agent: a request typed on the board becomes a sampling request.
89
+ onRuntime: runtime => wireBoardAgent(runtime, server, { log }),
90
+ });
91
+ server = createMcpServer({ session, send: chunk => process.stdout.write(chunk), log, argv: { ...options, version: VERSION } });
92
+ let stopping = false;
93
+ async function stop(code = 0) {
94
+ if (stopping)
95
+ return;
96
+ stopping = true;
97
+ try {
98
+ await session.close();
99
+ }
100
+ catch { /* the process is going away */ }
101
+ process.exit(code);
102
+ }
103
+ process.stdout.on('error', () => stop(0));
104
+ process.on('SIGTERM', () => stop(0));
105
+ process.on('SIGINT', () => stop(0));
106
+ process.on('uncaughtException', error => { log(`divlet-mcp: ${error?.stack || error}`); stop(1); });
107
+ process.on('unhandledRejection', error => { log(`divlet-mcp: ${error?.stack || error}`); });
108
+ let pending = '';
109
+ process.stdin.setEncoding('utf8');
110
+ process.stdin.on('data', chunk => {
111
+ pending += chunk;
112
+ let at;
113
+ while ((at = pending.indexOf('\n')) >= 0) {
114
+ const line = pending.slice(0, at);
115
+ pending = pending.slice(at + 1);
116
+ if (!line.trim())
117
+ continue;
118
+ server.receive(line).catch(error => log(`divlet-mcp: ${error?.message || error}`));
119
+ }
120
+ });
121
+ process.stdin.on('end', () => {
122
+ // A last message may arrive without its newline.
123
+ if (pending.trim())
124
+ server.receive(pending).catch(() => { });
125
+ stop(0);
126
+ });
127
+ log(`divlet-mcp ${VERSION} ready (stdio${options.project ? `, project ${path.resolve(options.cwd, options.project)}` : ''})`);
128
+ return { session, server };
129
+ }
130
+ export { session, server };
131
+ if (import.meta.main)
132
+ runMcp();
@@ -0,0 +1,39 @@
1
+ /** Start (or reuse) a board in this process; it registers itself, so other clients attach to it. */
2
+ export function localBoardOpener({ hubs }?: {
3
+ hubs?: Map<any, any> | undefined;
4
+ }): ({ file, args }?: {
5
+ args?: {} | undefined;
6
+ }) => Promise<any>;
7
+ /**
8
+ * The MCP server: reads newline-delimited JSON-RPC messages, writes one response per request. `send` is injected so tests and
9
+ * hosts can capture traffic; the entry point passes a stdout writer.
10
+ */
11
+ export function createMcpServer({ session, argv, send, log }: {
12
+ session: any;
13
+ argv?: {} | undefined;
14
+ send: any;
15
+ log?: (() => void) | undefined;
16
+ }): {
17
+ /** Feed one line (a JSON-RPC message) and await its handling. */
18
+ receive(line: any): Promise<void>;
19
+ /** Whether the connected client said it can run a prompt for us (`sampling`). */
20
+ readonly sampling: boolean;
21
+ request: (method: any, params: any, { timeout }?: {
22
+ timeout?: number | undefined;
23
+ }) => Promise<any>;
24
+ readonly initialized: boolean;
25
+ tools: import("@divlet/core/contract").Tool[];
26
+ };
27
+ /** The text of a `sampling/createMessage` result (a client may answer with one block or a list of them). */
28
+ export function samplingText(result: any): any;
29
+ /**
30
+ * Make this server the agent of a board it owns: the Agent tab on that board becomes a real conversation, answered by the MCP
31
+ * client through `sampling/createMessage`. Without client sampling support the board keeps saying that no agent is connected.
32
+ */
33
+ export function wireBoardAgent(runtime: any, server: any, { log }?: {
34
+ log?: (() => void) | undefined;
35
+ }): void;
36
+ import { createSession } from '@divlet/core/contract';
37
+ import { S } from '@divlet/core/contract';
38
+ import { optional } from '@divlet/core/contract';
39
+ export { createSession, S, optional };
@@ -0,0 +1,190 @@
1
+ /*
2
+ * The MCP side of the shared contract: JSON-RPC 2.0 over stdio (MCP's stdio transport), with `tools/list` rendered from
3
+ * `core/lib/contract.ts` and `tools/call` running the same operations Pi runs. Nothing here knows about layouts: it translates
4
+ * MCP's messages into contract calls and the results back into MCP content blocks.
5
+ *
6
+ * When the client supports `sampling`, a request typed on the board is sent to that client as `sampling/createMessage` and the
7
+ * answer is written back to the board, so the Agent tab works with an MCP client as the agent.
8
+ *
9
+ * MCP traffic never touches the browser preview channel. When this process owns a board it also registers it (runtime.js), so a
10
+ * Pi session, another MCP client or the CLI attaches to the same board instead of opening a second writer; when it does not own
11
+ * the board, tool calls are forwarded to the owner over that board's token-scoped HTTP API.
12
+ */
13
+ import { createSession, forAgent, inputSchema, openView, toolList, S, optional } from '@divlet/core/contract';
14
+ import { makeHost, openRuntime } from '@divlet/core';
15
+ const PROTOCOL_VERSION = '2025-06-18';
16
+ const SUPPORTED = new Set(['2024-11-05', '2025-03-26', '2025-06-18']);
17
+ const SERVER_NAME = 'divlet';
18
+ /** The result envelope every MCP tool call returns: the same agent vocabulary Pi uses, as text. */
19
+ const answer = value => ({ content: [{ type: 'text', text: JSON.stringify(forAgent(value), null, 2) }] });
20
+ /** A domain refusal is a tool error, not a protocol error: the code and the message travel in the text. */
21
+ const refusal = error => ({ content: [{ type: 'text', text: `${error.code || 'ERROR'}: ${error.message}${error.details ? `\n${JSON.stringify(error.details, null, 2)}` : ''}` }], isError: true });
22
+ /** Start (or reuse) a board in this process; it registers itself, so other clients attach to it. */
23
+ export function localBoardOpener({ hubs = new Map() } = {}) {
24
+ const boards = new Map();
25
+ const opening = new Map();
26
+ const open = async ({ file, args = {} } = {}) => {
27
+ const key = file;
28
+ if (boards.has(key))
29
+ return boards.get(key);
30
+ if (!opening.has(key)) {
31
+ opening.set(key, openRuntime({ cwd: file ? undefined : process.cwd(), file, port: args.port ?? 0, createDemo: args.createDemo ?? true, externalFiles: args.externalFiles })
32
+ .then(runtime => { runtime.host = makeHost({ openBoard: location => open(location), hubs }); boards.set(key, runtime); return runtime; })
33
+ .finally(() => opening.delete(key)));
34
+ }
35
+ return opening.get(key);
36
+ };
37
+ return open;
38
+ }
39
+ /**
40
+ * The MCP server: reads newline-delimited JSON-RPC messages, writes one response per request. `send` is injected so tests and
41
+ * hosts can capture traffic; the entry point passes a stdout writer.
42
+ */
43
+ export function createMcpServer({ session, argv = {}, send, log = () => { } }) {
44
+ const tools = toolList();
45
+ const toolByName = new Map(tools.map(tool => [tool.name, tool]));
46
+ let initialized = false;
47
+ let sampling = false;
48
+ let nextRequestId = 1;
49
+ const pending = new Map();
50
+ const write = (message) => send(JSON.stringify(message) + '\n');
51
+ /** A request *to* the client (MCP is bidirectional): resolves with its result, rejects with its error. */
52
+ function request(method, params, { timeout = 120_000 } = {}) {
53
+ const id = `divlet-${nextRequestId++}`;
54
+ return new Promise((resolve, reject) => {
55
+ const timer = setTimeout(() => { pending.delete(id); reject(Object.assign(new Error(`${method} timed out.`), { code: 'TIMEOUT' })); }, timeout);
56
+ timer.unref?.();
57
+ pending.set(id, { resolve: value => { clearTimeout(timer); resolve(value); }, reject: error => { clearTimeout(timer); reject(error); } });
58
+ write({ jsonrpc: '2.0', id, method, params });
59
+ });
60
+ }
61
+ const result = (id, value) => write({ jsonrpc: '2.0', id, result: value });
62
+ const failure = (id, code, message, data) => write({ jsonrpc: '2.0', id, error: { code, message, ...(data !== undefined ? { data } : {}) } });
63
+ async function dispatch(message) {
64
+ const { id, method, params } = message ?? {};
65
+ const notification = id === undefined || id === null;
66
+ if (typeof method !== 'string') {
67
+ if (!notification)
68
+ failure(id, -32600, 'Invalid request: method must be a string.');
69
+ return;
70
+ }
71
+ switch (method) {
72
+ case 'initialize': {
73
+ const requested = params?.protocolVersion;
74
+ initialized = true;
75
+ sampling = !!params?.capabilities?.sampling;
76
+ return result(id, {
77
+ protocolVersion: SUPPORTED.has(requested) ? requested : PROTOCOL_VERSION,
78
+ capabilities: { tools: { listChanged: false } },
79
+ serverInfo: { name: SERVER_NAME, version: argv.version || '0.0.0' },
80
+ instructions: 'divlet edits a local layout project (one .divlet file of HTML elements with Tailwind classes). Call open_divlet first, then read_divlet before patch_divlet or edit_divlet.',
81
+ });
82
+ }
83
+ case 'notifications/initialized':
84
+ case 'notifications/cancelled':
85
+ case 'notifications/roots/list_changed':
86
+ return;
87
+ case 'ping':
88
+ return result(id, {});
89
+ case 'tools/list':
90
+ return result(id, { tools: tools.map(tool => ({ name: tool.name, title: tool.title, description: tool.description, inputSchema: inputSchema(tool) })) });
91
+ case 'tools/call': {
92
+ const name = params?.name;
93
+ const tool = toolByName.get(name);
94
+ if (!tool)
95
+ return failure(id, -32602, `Unknown tool: ${name}.`);
96
+ try {
97
+ // `open_divlet` inherits the server's own defaults (--project, --port, --no-demo) unless the call overrides them.
98
+ const args = name === 'open_divlet'
99
+ ? { path: argv.project, port: argv.port, createDemo: argv.createDemo, ...(params?.arguments ?? {}) }
100
+ : (params?.arguments ?? {});
101
+ const value = await session.call(name, args, { cwd: argv.cwd });
102
+ return result(id, answer(name === 'open_divlet' ? openView(value) : value));
103
+ }
104
+ catch (error) {
105
+ return result(id, refusal(error));
106
+ }
107
+ }
108
+ case 'resources/list':
109
+ return result(id, { resources: [] });
110
+ case 'prompts/list':
111
+ return result(id, { prompts: [] });
112
+ default:
113
+ return failure(id, -32601, `Unknown method: ${method}.`);
114
+ }
115
+ }
116
+ let queue = Promise.resolve();
117
+ return {
118
+ /** Feed one line (a JSON-RPC message) and await its handling. */
119
+ async receive(line) {
120
+ const text = String(line).trim();
121
+ if (!text)
122
+ return;
123
+ let message;
124
+ try {
125
+ message = JSON.parse(text);
126
+ }
127
+ catch {
128
+ write({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error.' } });
129
+ return;
130
+ }
131
+ // A reply to one of our own requests (sampling) is not a method call: settle it here.
132
+ if (message && typeof message.method !== 'string' && message.id !== undefined) {
133
+ const waiter = pending.get(message.id);
134
+ pending.delete(message.id);
135
+ if (!waiter)
136
+ return;
137
+ if (message.error)
138
+ waiter.reject(Object.assign(new Error(message.error.message || 'The client refused the request.'), { code: message.error.code, data: message.error.data }));
139
+ else
140
+ waiter.resolve(message.result);
141
+ return;
142
+ }
143
+ queue = queue.then(() => dispatch(message)).catch(error => { log(`divlet mcp: ${error?.message || error}`); });
144
+ await queue;
145
+ },
146
+ /** Whether the connected client said it can run a prompt for us (`sampling`). */
147
+ get sampling() { return sampling; },
148
+ request,
149
+ get initialized() { return initialized; },
150
+ tools,
151
+ };
152
+ }
153
+ /** The text of a `sampling/createMessage` result (a client may answer with one block or a list of them). */
154
+ export function samplingText(result) {
155
+ const blocks = Array.isArray(result?.content) ? result.content : result?.content ? [result.content] : [];
156
+ return blocks.filter(block => block?.type === 'text' && typeof block.text === 'string').map(block => block.text).join('\n').trim();
157
+ }
158
+ /**
159
+ * Make this server the agent of a board it owns: the Agent tab on that board becomes a real conversation, answered by the MCP
160
+ * client through `sampling/createMessage`. Without client sampling support the board keeps saying that no agent is connected.
161
+ */
162
+ export function wireBoardAgent(runtime, server, { log = () => { } } = {}) {
163
+ if (!runtime || typeof runtime.on !== 'function')
164
+ return;
165
+ runtime.setAgent({ connected: true, busy: false, activity: null });
166
+ runtime.on('ask', async ({ message, seq }) => {
167
+ if (!server.sampling) {
168
+ runtime.say({ text: 'This MCP client does not support sampling, so it cannot answer board requests. Connect a client that does, or open the board from Pi.', seq });
169
+ return;
170
+ }
171
+ runtime.setAgent({ busy: true, activity: 'thinking' });
172
+ try {
173
+ const result = await server.request('sampling/createMessage', {
174
+ messages: [{ role: 'user', content: { type: 'text', text: message } }],
175
+ maxTokens: 4096,
176
+ systemPrompt: 'You are the agent of a divlet layout board. Answer in a few sentences. Use the divlet tools (read_divlet, patch_divlet, edit_divlet) when the request asks for a change; style with Tailwind classes.',
177
+ });
178
+ const text = samplingText(result);
179
+ runtime.say({ text: text || 'The client returned no text answer.', seq });
180
+ }
181
+ catch (error) {
182
+ log(`divlet mcp: sampling failed: ${error?.message || error}`);
183
+ runtime.say({ text: `The MCP client could not answer: ${error?.message || error}`, seq });
184
+ }
185
+ finally {
186
+ runtime.setAgent({ busy: false, activity: null });
187
+ }
188
+ });
189
+ }
190
+ export { createSession, S, optional };
@@ -0,0 +1,42 @@
1
+ {
2
+ "name": "@divlet/mcp",
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "description": "The divlet MCP stdio adapter",
6
+ "bin": {
7
+ "divlet-mcp": "./dist/index.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=22.19.0"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/llblab/divlet.git",
15
+ "directory": "mcp"
16
+ },
17
+ "homepage": "https://github.com/llblab/divlet#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/llblab/divlet/issues"
20
+ },
21
+ "license": "MIT",
22
+ "main": "./dist/index.js",
23
+ "exports": {
24
+ ".": {
25
+ "divlet-source": "./index.js",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "imports": {
30
+ "#package": "./package.json"
31
+ },
32
+ "dependencies": {
33
+ "@divlet/core": "0.0.2"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md"
38
+ ],
39
+ "scripts": {
40
+ "prepack": "node ../scripts/build.mjs"
41
+ }
42
+ }
package/package.json CHANGED
@@ -1,6 +1,42 @@
1
1
  {
2
2
  "name": "@divlet/mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "type": "module",
5
+ "description": "The divlet MCP stdio adapter",
6
+ "bin": {
7
+ "divlet-mcp": "./dist/index.js"
8
+ },
9
+ "engines": {
10
+ "node": ">=22.19.0"
11
+ },
12
+ "repository": {
13
+ "type": "git",
14
+ "url": "git+https://github.com/llblab/divlet.git",
15
+ "directory": "mcp"
16
+ },
17
+ "homepage": "https://github.com/llblab/divlet#readme",
18
+ "bugs": {
19
+ "url": "https://github.com/llblab/divlet/issues"
20
+ },
21
+ "license": "MIT",
22
+ "main": "./dist/index.js",
23
+ "exports": {
24
+ ".": {
25
+ "divlet-source": "./index.js",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "imports": {
30
+ "#package": "./package.json"
31
+ },
32
+ "dependencies": {
33
+ "@divlet/core": "0.0.2"
34
+ },
35
+ "files": [
36
+ "dist",
37
+ "README.md"
38
+ ],
39
+ "scripts": {
40
+ "prepack": "node ../scripts/build.mjs"
41
+ }
42
+ }