bitwrench 2.0.22 → 2.0.23

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.
Files changed (88) hide show
  1. package/LICENSE.txt +1 -1
  2. package/README.md +4 -3
  3. package/bin/bwmcp.js +3 -0
  4. package/dist/bitwrench-bccl.cjs.js +1 -1
  5. package/dist/bitwrench-bccl.cjs.min.js +1 -1
  6. package/dist/bitwrench-bccl.cjs.min.js.gz +0 -0
  7. package/dist/bitwrench-bccl.esm.js +1 -1
  8. package/dist/bitwrench-bccl.esm.min.js +1 -1
  9. package/dist/bitwrench-bccl.esm.min.js.gz +0 -0
  10. package/dist/bitwrench-bccl.umd.js +1 -1
  11. package/dist/bitwrench-bccl.umd.min.js +1 -1
  12. package/dist/bitwrench-bccl.umd.min.js.gz +0 -0
  13. package/dist/bitwrench-code-edit.cjs.js +1 -1
  14. package/dist/bitwrench-code-edit.cjs.min.js +1 -1
  15. package/dist/bitwrench-code-edit.es5.js +1 -1
  16. package/dist/bitwrench-code-edit.es5.min.js +1 -1
  17. package/dist/bitwrench-code-edit.esm.js +1 -1
  18. package/dist/bitwrench-code-edit.esm.min.js +1 -1
  19. package/dist/bitwrench-code-edit.umd.js +1 -1
  20. package/dist/bitwrench-code-edit.umd.min.js +1 -1
  21. package/dist/bitwrench-code-edit.umd.min.js.gz +0 -0
  22. package/dist/bitwrench-debug.js +1 -1
  23. package/dist/bitwrench-debug.min.js +1 -1
  24. package/dist/bitwrench-lean.cjs.js +3 -3
  25. package/dist/bitwrench-lean.cjs.min.js +2 -2
  26. package/dist/bitwrench-lean.cjs.min.js.gz +0 -0
  27. package/dist/bitwrench-lean.es5.js +3 -3
  28. package/dist/bitwrench-lean.es5.min.js +2 -2
  29. package/dist/bitwrench-lean.es5.min.js.gz +0 -0
  30. package/dist/bitwrench-lean.esm.js +3 -3
  31. package/dist/bitwrench-lean.esm.min.js +2 -2
  32. package/dist/bitwrench-lean.esm.min.js.gz +0 -0
  33. package/dist/bitwrench-lean.umd.js +3 -3
  34. package/dist/bitwrench-lean.umd.min.js +2 -2
  35. package/dist/bitwrench-lean.umd.min.js.gz +0 -0
  36. package/dist/bitwrench-util-css.cjs.js +1 -1
  37. package/dist/bitwrench-util-css.cjs.min.js +1 -1
  38. package/dist/bitwrench-util-css.es5.js +1 -1
  39. package/dist/bitwrench-util-css.es5.min.js +1 -1
  40. package/dist/bitwrench-util-css.esm.js +1 -1
  41. package/dist/bitwrench-util-css.esm.min.js +1 -1
  42. package/dist/bitwrench-util-css.umd.js +1 -1
  43. package/dist/bitwrench-util-css.umd.min.js +1 -1
  44. package/dist/bitwrench-util-css.umd.min.js.gz +0 -0
  45. package/dist/bitwrench.cjs.js +3 -3
  46. package/dist/bitwrench.cjs.min.js +2 -2
  47. package/dist/bitwrench.cjs.min.js.gz +0 -0
  48. package/dist/bitwrench.css +1 -1
  49. package/dist/bitwrench.es5.js +3 -3
  50. package/dist/bitwrench.es5.min.js +2 -2
  51. package/dist/bitwrench.es5.min.js.gz +0 -0
  52. package/dist/bitwrench.esm.js +3 -3
  53. package/dist/bitwrench.esm.min.js +2 -2
  54. package/dist/bitwrench.esm.min.js.gz +0 -0
  55. package/dist/bitwrench.umd.js +3 -3
  56. package/dist/bitwrench.umd.min.js +2 -2
  57. package/dist/bitwrench.umd.min.js.gz +0 -0
  58. package/dist/builds.json +57 -57
  59. package/dist/bwserve.cjs.js +2 -2
  60. package/dist/bwserve.esm.js +2 -2
  61. package/dist/sri.json +45 -45
  62. package/docs/README.md +76 -0
  63. package/docs/app-patterns.md +264 -0
  64. package/docs/bitwrench-mcp.md +426 -0
  65. package/docs/bitwrench_api.md +2232 -0
  66. package/docs/bw-attach.md +399 -0
  67. package/docs/bwserve.md +841 -0
  68. package/docs/cli.md +307 -0
  69. package/docs/component-cheatsheet.md +144 -0
  70. package/docs/component-library.md +1099 -0
  71. package/docs/framework-translation-table.md +33 -0
  72. package/docs/llm-bitwrench-guide.md +672 -0
  73. package/docs/routing.md +562 -0
  74. package/docs/state-management.md +767 -0
  75. package/docs/taco-format.md +373 -0
  76. package/docs/theming.md +309 -0
  77. package/docs/thinking-in-bitwrench.md +1457 -0
  78. package/docs/tutorial-bwserve.md +297 -0
  79. package/docs/tutorial-embedded.md +314 -0
  80. package/docs/tutorial-website.md +255 -0
  81. package/package.json +11 -3
  82. package/readme.html +5 -4
  83. package/src/mcp/knowledge.js +231 -0
  84. package/src/mcp/live.js +226 -0
  85. package/src/mcp/server.js +216 -0
  86. package/src/mcp/tools.js +369 -0
  87. package/src/mcp/transport.js +55 -0
  88. package/src/version.js +3 -3
@@ -0,0 +1,264 @@
1
+ # App Patterns
2
+
3
+ Five canonical layouts for bitwrench apps. Each section shows when to use it, directory structure, a code skeleton, and state flow.
4
+
5
+ ---
6
+
7
+ ## Pattern 1: Single-Page Dashboard
8
+
9
+ One page, multiple widgets, shared data. Stat cards, tables, and charts react to the same store. Good for monitoring dashboards and admin panels.
10
+
11
+ ```
12
+ my-dashboard/
13
+ index.html <- loads bitwrench, includes app.js
14
+ app.js <- store, widgets, render functions
15
+ ```
16
+
17
+ ```javascript
18
+ // app.js
19
+ bw.loadStyles({ primary: '#1e40af', secondary: '#059669' });
20
+
21
+ // Store: plain object + scoped pub/sub
22
+ var store = { users: 128, revenue: 48200, orders: [] };
23
+
24
+ function updateStore(key, value) {
25
+ store[key] = value;
26
+ bw.pub('store:' + key, value);
27
+ }
28
+
29
+ // Widgets -- each subscribes to its own data slice
30
+ function renderStats() {
31
+ bw.DOM('#stats', { t: 'div', c: [
32
+ bw.makeStatCard({ label: 'Users', value: store.users }),
33
+ bw.makeStatCard({ label: 'Revenue', value: '$' + store.revenue })
34
+ ]});
35
+ }
36
+
37
+ function renderTable() {
38
+ bw.DOM('#orders', bw.makeTable({ data: store.orders, sortable: true }));
39
+ }
40
+
41
+ // Layout
42
+ bw.DOM('#app', { t: 'div', c: [
43
+ bw.makeNavbar({ brand: 'Dashboard' }),
44
+ { t: 'div', a: { id: 'stats' } },
45
+ { t: 'div', a: { id: 'orders' } }
46
+ ]});
47
+
48
+ // Wire up
49
+ bw.sub('store:users', renderStats);
50
+ bw.sub('store:revenue', renderStats);
51
+ bw.sub('store:orders', renderTable);
52
+ renderStats();
53
+ renderTable();
54
+ ```
55
+
56
+ **State flow:** `store` is a plain object. `updateStore()` sets values and publishes scoped topics (`store:users`, `store:orders`). Each widget subscribes only to its own topics and re-renders itself. Widgets never read each other -- they read from the shared store. See [state-management.md](state-management.md).
57
+
58
+ ---
59
+
60
+ ## Pattern 2: Multi-Page SPA
61
+
62
+ Client-side navigation between views with a persistent nav/footer and shared state. URL changes without full page reloads.
63
+
64
+ ```
65
+ my-spa/
66
+ index.html
67
+ app.js <- router, nav, footer
68
+ views/
69
+ home.js, users.js, settings.js
70
+ store.js <- shared state
71
+ ```
72
+
73
+ ```javascript
74
+ // store.js
75
+ var store = { user: { name: 'Alice' }, items: [] };
76
+ function updateStore(key, value) {
77
+ store[key] = value;
78
+ bw.pub('store:' + key, value);
79
+ }
80
+
81
+ // views/home.js
82
+ function homeView() {
83
+ return { t: 'div', c: [
84
+ bw.makeHero({ title: 'Welcome, ' + store.user.name }),
85
+ bw.makeCard({ title: 'Recent', content: store.items.length + ' items' })
86
+ ]};
87
+ }
88
+
89
+ // views/users.js
90
+ function usersView(params) {
91
+ if (params.id) return bw.makeCard({ title: 'User ' + params.id });
92
+ return bw.makeTable({ data: store.items, sortable: true });
93
+ }
94
+
95
+ // app.js
96
+ bw.loadStyles({ primary: '#2563eb', secondary: '#7c3aed' });
97
+
98
+ bw.DOM('#app', { t: 'div', c: [
99
+ bw.makeNavbar({ brand: 'My App', items: [
100
+ { text: 'Home', href: '#/' },
101
+ { text: 'Users', href: '#/users' },
102
+ { text: 'Settings', href: '#/settings' }
103
+ ]}),
104
+ { t: 'div', a: { id: 'view' } },
105
+ { t: 'footer', a: { style: 'padding:1rem; text-align:center' }, c: '(c) 2026' }
106
+ ]});
107
+
108
+ bw.router({
109
+ target: '#view',
110
+ routes: {
111
+ '/': function() { return homeView(); },
112
+ '/users': function() { return usersView({}); },
113
+ '/users/:id': function(params) { return usersView(params); },
114
+ '/settings': function() { return settingsView(); },
115
+ '*': function() { return { t: 'h1', c: '404 Not Found' }; }
116
+ },
117
+ after: function(to) { bw.pub('nav:changed', { path: to }); }
118
+ });
119
+ ```
120
+
121
+ **State flow:** `bw.router()` listens for hash changes. Each route handler returns a TACO mounted into `#view`. Nav and footer stay in the DOM -- only `#view` swaps. Views subscribe via `bw.sub('store:key', fn, el)` -- the `el` param auto-unsubscribes when the view unmounts. See [routing.md](routing.md), [state-management.md](state-management.md#shared-state-across-views).
122
+
123
+ ---
124
+
125
+ ## Pattern 3: bwserve Server-Driven App
126
+
127
+ Server owns all state and pushes UI over SSE. The client is thin -- it renders whatever the server sends. Good for internal tools, LLM-driven UIs, and apps with no client-side logic. No client files needed -- bwserve auto-generates the HTML shell.
128
+
129
+ ```
130
+ my-bwserve-app/
131
+ server.js <- Node.js server (the only file)
132
+ ```
133
+
134
+ ```javascript
135
+ // server.js
136
+ import bwserve from 'bitwrench/bwserve';
137
+
138
+ var app = bwserve.create({ port: 7902 });
139
+ var count = 0;
140
+
141
+ app.page('/', function(client) {
142
+ client.render('#app', {
143
+ t: 'div', c: [
144
+ { t: 'h1', c: 'Server Counter' },
145
+ { t: 'span', a: { id: 'val' }, c: '0' },
146
+ { t: 'button', a: { 'data-bw-action': 'inc' }, c: '+1' }
147
+ ]
148
+ });
149
+
150
+ client.on('inc', function() {
151
+ count++;
152
+ client.patch('val', String(count));
153
+ });
154
+ });
155
+
156
+ app.listen();
157
+ ```
158
+
159
+ **State flow:** Browser requests `/` => server returns HTML shell. Shell opens SSE => server sends TACO via `client.render()`. User clicks `data-bw-action` => browser POSTs to server. Server calls `client.patch()` => browser updates. All state stays on the server. See [bwserve.md](bwserve.md).
160
+
161
+ ---
162
+
163
+ ## Pattern 4: Embedded / IoT Dashboard
164
+
165
+ A microcontroller (ESP32, Raspberry Pi) serves a static HTML page and pushes sensor data as JSON. Minimal footprint, works on constrained hardware.
166
+
167
+ ```
168
+ firmware/
169
+ main.ino <- serves HTML + sensor data
170
+ data/
171
+ index.html <- dashboard page
172
+ bitwrench.umd.min.js
173
+ ```
174
+
175
+ ```javascript
176
+ // Inside data/index.html <script> block
177
+ bw.loadStyles({ primary: '#0d9488' });
178
+
179
+ // Static layout -- rendered once
180
+ bw.DOM('#app', { t: 'div', c: [
181
+ { t: 'h1', c: 'Sensor Dashboard' },
182
+ { t: 'div', a: { id: 'readings' } },
183
+ bw.makeButton({ text: 'LED On', onclick: function() {
184
+ fetch('/api/command', {
185
+ method: 'POST',
186
+ headers: { 'Content-Type': 'application/json' },
187
+ body: JSON.stringify({ cmd: 'led', val: 'on' })
188
+ });
189
+ }})
190
+ ]});
191
+
192
+ // Poll the device -- re-render readings section each cycle
193
+ setInterval(function() {
194
+ fetch('/api/sensors').then(function(r) { return r.json(); })
195
+ .then(function(data) {
196
+ bw.DOM('#readings', { t: 'div', c: [
197
+ bw.makeStatCard({ label: 'Temperature', value: data.temp + ' C' }),
198
+ bw.makeStatCard({ label: 'Humidity', value: data.humidity + ' %' })
199
+ ]});
200
+ });
201
+ }, 2000);
202
+ ```
203
+
204
+ **State flow:** Device serves files from flash (SPIFFS/LittleFS). Page renders a static layout, then a `setInterval` polls `/api/sensors`. On each response, `bw.DOM()` re-renders the readings. For SSE push instead of polling, use `new EventSource('/events')` and call `bw.patch()` on each message. See [tutorial-embedded.md](tutorial-embedded.md).
205
+
206
+ ---
207
+
208
+ ## Pattern 5: Static Site (bwcli)
209
+
210
+ Convert Markdown or HTML to styled pages at build time. No runtime JavaScript required. Good for docs, blogs, and project pages.
211
+
212
+ ```
213
+ my-docs/
214
+ content/
215
+ index.md, guide.md, api.md
216
+ styles.css <- optional custom CSS
217
+ build.sh
218
+ dist/ <- generated output
219
+ ```
220
+
221
+ ```bash
222
+ #!/bin/bash
223
+ # build.sh
224
+ for f in content/*.md; do
225
+ name=$(basename "$f" .md)
226
+ bwcli "$f" \
227
+ --standalone \
228
+ --theme ocean \
229
+ --highlight \
230
+ -c styles.css \
231
+ -o "dist/${name}.html"
232
+ done
233
+ ```
234
+
235
+ Each output is self-contained with bitwrench embedded inline. No CDN, no toolchain beyond `bwcli`.
236
+
237
+ **State flow:** There is none at runtime. `bwcli` reads Markdown, converts to HTML, applies a theme, and writes a static file. For pages that need interactivity, add `--standalone` and include a `<script>` block using bitwrench at runtime. See [cli.md](cli.md).
238
+
239
+ ---
240
+
241
+ ## Choosing a Pattern
242
+
243
+ | Use case | Pattern | Key API |
244
+ |----------|---------|---------|
245
+ | Monitoring dashboard, admin panel | Single-Page Dashboard | `bw.pub/sub`, `bw.DOM()`, `makeStatCard` |
246
+ | Multi-view app with URL navigation | Multi-Page SPA | `bw.router()`, `bw.navigate()` |
247
+ | Server owns all logic (internal tool, LLM UI) | bwserve Server-Driven | `client.render()`, `client.patch()` |
248
+ | Microcontroller or constrained device | Embedded / IoT | `bw.DOM()`, `fetch()` polling or SSE |
249
+ | Documentation, blog, project pages | Static Site (bwcli) | `bwcli`, `--theme`, `--standalone` |
250
+ | Prototype or quick one-off | Single-Page Dashboard | One HTML file, no build step |
251
+
252
+ Patterns compose: a bwserve app can include a client-side router, an embedded dashboard can use pub/sub, and a static site can include runtime bitwrench for interactive sections.
253
+
254
+ ---
255
+
256
+ ## Related
257
+
258
+ - [State Management](state-management.md) -- levels 0-2, pub/sub, shared state
259
+ - [Routing](routing.md) -- `bw.router()` full API
260
+ - [Component Library](component-library.md) -- all `make*()` factories
261
+ - [bwserve](bwserve.md) -- server-driven UI protocol
262
+ - [Tutorial: Embedded](tutorial-embedded.md) -- ESP32 walkthrough
263
+ - [CLI](cli.md) -- `bwcli` command reference
264
+ - [Thinking in Bitwrench](thinking-in-bitwrench.md) -- design philosophy
@@ -0,0 +1,426 @@
1
+ # bwmcp -- MCP Server for Bitwrench
2
+
3
+ bwmcp is an MCP (Model Context Protocol) server that lets AI agents build
4
+ and control live browser UI through bitwrench. An agent connects via MCP,
5
+ calls tools to compose TACO components, and the result renders live in a
6
+ browser window. The agent can screenshot, inspect, and iterate.
7
+
8
+ ## Quick Start
9
+
10
+ ### 1. Configure in Claude Code
11
+
12
+ Add to your Claude Code MCP settings (`~/.claude/settings.json` or project `.mcp.json`):
13
+
14
+ ```json
15
+ {
16
+ "mcpServers": {
17
+ "bitwrench": {
18
+ "command": "node",
19
+ "args": ["/path/to/bitwrench/bin/bwmcp.js"]
20
+ }
21
+ }
22
+ }
23
+ ```
24
+
25
+ Or if bitwrench is installed globally (`npm install -g bitwrench`):
26
+
27
+ ```json
28
+ {
29
+ "mcpServers": {
30
+ "bitwrench": {
31
+ "command": "bwmcp"
32
+ }
33
+ }
34
+ }
35
+ ```
36
+
37
+ ### 2. Configure in Cursor / VS Code
38
+
39
+ In your project's `.cursor/mcp.json` or VS Code MCP settings:
40
+
41
+ ```json
42
+ {
43
+ "mcpServers": {
44
+ "bitwrench": {
45
+ "command": "node",
46
+ "args": ["/path/to/bitwrench/bin/bwmcp.js", "--open"]
47
+ }
48
+ }
49
+ }
50
+ ```
51
+
52
+ ### 3. Use It
53
+
54
+ Ask the AI agent:
55
+
56
+ > "Build me a dashboard with stat cards showing revenue, users, and orders."
57
+
58
+ The agent will:
59
+ 1. Call `bitwrench_start_here` to learn the workflow
60
+ 2. Call `make_stat_card` three times with appropriate props
61
+ 3. Compose the cards into a grid layout
62
+ 4. Call `build_page` with a theme to produce a standalone HTML file
63
+
64
+ With `--open` or live rendering, the agent can also push UI to a browser
65
+ and iterate visually using screenshots.
66
+
67
+ ## CLI Options
68
+
69
+ ```
70
+ bwmcp [options]
71
+
72
+ Options:
73
+ --port <n> bwserve port for live browser rendering (default: 7910)
74
+ --theme <name> Default theme preset (ocean, forest, sunset, etc.)
75
+ --open Open browser automatically on start
76
+ --no-browser Skip starting bwserve (testing/offline mode)
77
+ --help, -h Show help
78
+ ```
79
+
80
+ ## How It Works
81
+
82
+ ```
83
+ AI Agent (Claude, Cursor, etc.)
84
+ |
85
+ | JSON-RPC 2.0 over stdio
86
+ |
87
+ bwmcp ──────────────────────────────────────
88
+ | |
89
+ | MCP Protocol Handler |
90
+ | tools/list -> 21 tools |
91
+ | tools/call -> execute tool |
92
+ | |
93
+ | Knowledge Tools (5) |
94
+ | Read docs from disk, serve to LLM |
95
+ | |
96
+ | Component Tools (10) |
97
+ | Call bw.makeCard(), etc. |
98
+ | Return TACO JSON |
99
+ | |
100
+ | Utility Tools (3) |
101
+ | render_taco, build_page, make_styles |
102
+ | |
103
+ | Live Tools (3) |
104
+ | Push to browser via bwserve SSE |
105
+ | |
106
+ | bwserve instance (port 7910) |
107
+ | HTTP server + SSE streaming |
108
+ ────|────────────────────────────────────────
109
+ |
110
+ | HTTP / SSE
111
+ |
112
+ Browser Window
113
+ Renders TACO, captures screenshots
114
+ ```
115
+
116
+ ## The Core Loop
117
+
118
+ The primary value of bwmcp is the iterative render-screenshot-adjust loop:
119
+
120
+ ```
121
+ Agent bwmcp Browser
122
+ | | |
123
+ |-- bitwrench_start_here ----->| |
124
+ |<-- orientation text ---------| |
125
+ | | |
126
+ |-- make_stat_card {...} ----->| |
127
+ |<-- TACO JSON ----------------| |
128
+ | | |
129
+ |-- render_live {taco} ------->|-- SSE: replace #app -------->|
130
+ |<-- {rendered, clientCount} --| |-- UI visible
131
+ | | |
132
+ |-- screenshot {} ------------>|-- screenshot request -------->|
133
+ |<-- PNG image data -----------|<-- html2canvas capture ------|
134
+ | | |
135
+ | (agent evaluates image, | |
136
+ | decides to adjust) | |
137
+ | | |
138
+ |-- render_live {patch} ------>|-- SSE: patch ---------------->|
139
+ |<-- {rendered} ---------------| |-- UI updated
140
+ ```
141
+
142
+
143
+ ## Tool Reference
144
+
145
+ ### Knowledge Tools
146
+
147
+ These return documentation text. They teach the LLM how to use bitwrench.
148
+
149
+ | Tool | Description | When to Call |
150
+ |------|-------------|--------------|
151
+ | `bitwrench_start_here` | 30-line orientation: TACO, workflow, key rules | Always first |
152
+ | `bitwrench_guide` | Full developer guide (629 lines). Optional `section` filter. | Before building UI |
153
+ | `bitwrench_components` | Props reference for all 50+ make*() components. Optional `component` filter. | When configuring components |
154
+ | `bitwrench_server_guide` | bwserve tutorial for server-driven UI | Only for live/streaming UI |
155
+ | `bitwrench_themes` | Theme presets, palettes, color utilities | When choosing/customizing themes |
156
+
157
+ **Section filter** for `bitwrench_guide`:
158
+ ```
159
+ taco, levels, events, css, components, bwserve, routing, api-reference, rules
160
+ ```
161
+
162
+ **Component filter** for `bitwrench_components`:
163
+ ```
164
+ makeCard, makeButton, makeTable, makeTabs, makeAccordion, makeAlert,
165
+ makeNav, makeHero, makeStatCard, makeFormGroup, ... (47+ total)
166
+ ```
167
+
168
+ ### Component Tools
169
+
170
+ Each returns a TACO object (JSON) that can be composed or rendered.
171
+
172
+ | Tool | Props | Description |
173
+ |------|-------|-------------|
174
+ | `make_card` | title, subtitle, content, footer, image, variant, ... | Card with optional header image |
175
+ | `make_button` | text, variant, size, disabled, type | Button with color variant |
176
+ | `make_table` | data, columns, striped, hover, sortable | Data table with sorting |
177
+ | `make_tabs` | tabs: [{label, content}], activeIndex | Tabbed interface |
178
+ | `make_accordion` | items: [{title, content}], multiOpen | Collapsible sections |
179
+ | `make_alert` | content, variant, dismissible | Alert/notification box |
180
+ | `make_nav` | items: [{text, href, active}], pills, vertical | Navigation links |
181
+ | `make_hero` | title, subtitle, content, variant, size, actions | Full-width hero section |
182
+ | `make_stat_card` | label, value, change, prefix, suffix, icon, variant | KPI stat card |
183
+ | `make_form_group` | label, input, help, id, required, validation | Label + input wrapper |
184
+
185
+ **Variants:** primary, secondary, success, danger, warning, info
186
+
187
+ ### Utility Tools
188
+
189
+ | Tool | Input | Output |
190
+ |------|-------|--------|
191
+ | `render_taco` | `{taco, indent}` | HTML string |
192
+ | `build_page` | `{title, content, theme, runtime}` | Complete standalone HTML page |
193
+ | `make_styles` | `{primary, secondary, background, surface}` | CSS text |
194
+
195
+ ### Live Rendering Tools
196
+
197
+ These require a browser connected to the bwserve instance.
198
+
199
+ | Tool | Input | Output |
200
+ |------|-------|--------|
201
+ | `render_live` | `{target, taco, action}` | Push TACO to browser. Actions: replace, append, patch, remove |
202
+ | `screenshot` | `{selector}` | Base64 PNG image of browser viewport |
203
+ | `query_dom` | `{code}` | Execute JS in browser, return result |
204
+
205
+
206
+ ## Guide for LLM Agents
207
+
208
+ This section is written for you, the AI agent. When you connect to bwmcp
209
+ via MCP, follow this workflow.
210
+
211
+ ### Step 1: Orient Yourself
212
+
213
+ Call `bitwrench_start_here`. It returns a 30-line cheat sheet covering:
214
+ - What bitwrench is (zero-dep JS UI library)
215
+ - The TACO format: `{t: 'div', a: {class: 'x'}, c: 'content'}`
216
+ - Your 5-step workflow
217
+ - Key rules (compose TACOs, use grid, pick a theme)
218
+ - Which other knowledge tools to call
219
+
220
+ This costs about 200 tokens. Always call it first.
221
+
222
+ ### Step 2: Learn (Optional but Recommended)
223
+
224
+ If you have not used bitwrench before, call `bitwrench_guide`. This is the
225
+ full tutorial (about 4000 tokens). It covers TACO nesting, the three-level
226
+ component model, events, CSS/theming, all component categories, debugging,
227
+ bwserve, routing, and API reference tables.
228
+
229
+ If you only need info on specific topics, use the section filter:
230
+ ```
231
+ bitwrench_guide({section: 'css'}) // just CSS and theming
232
+ bitwrench_guide({section: 'components'}) // component categories
233
+ ```
234
+
235
+ ### Step 3: Look Up Component Props
236
+
237
+ When you need exact props for a component, call:
238
+ ```
239
+ bitwrench_components({component: 'makeStatCard'})
240
+ ```
241
+ This returns the detailed signature, props, variants, and examples for
242
+ that specific component. Much cheaper than loading the full catalog.
243
+
244
+ ### Step 4: Build Components
245
+
246
+ Call the make_* tools to create TACO objects:
247
+ ```
248
+ make_stat_card({label: 'Revenue', value: '$12,345', variant: 'primary'})
249
+ make_stat_card({label: 'Users', value: '1,234', variant: 'success'})
250
+ make_table({data: [...], columns: [{key:'name', label:'Name'}, ...]})
251
+ ```
252
+
253
+ Each returns a TACO object in `structuredContent`. Save these for composition.
254
+
255
+ ### Step 5: Compose Layout
256
+
257
+ Nest the TACOs into a grid layout. The bitwrench grid uses three classes:
258
+ ```
259
+ bw_container > bw_row > bw_col
260
+ ```
261
+
262
+ Build a layout TACO by nesting:
263
+ ```json
264
+ {
265
+ "t": "div", "a": {"class": "bw_container"}, "c": [
266
+ {"t": "h1", "c": "Dashboard"},
267
+ {"t": "div", "a": {"class": "bw_row"}, "c": [
268
+ {"t": "div", "a": {"class": "bw_col"}, "c": [<stat1 taco>]},
269
+ {"t": "div", "a": {"class": "bw_col"}, "c": [<stat2 taco>]},
270
+ {"t": "div", "a": {"class": "bw_col"}, "c": [<stat3 taco>]}
271
+ ]},
272
+ <table taco>
273
+ ]
274
+ }
275
+ ```
276
+
277
+ ### Step 6: Generate Output
278
+
279
+ **For a standalone HTML file** (the typical case):
280
+ ```
281
+ build_page({
282
+ title: 'My Dashboard',
283
+ theme: 'ocean',
284
+ content: <your composed layout TACO>
285
+ })
286
+ ```
287
+ Returns a complete `.html` file with bitwrench inlined. Works offline.
288
+ Save it to disk with your file-writing tool.
289
+
290
+ **For live browser rendering:**
291
+ ```
292
+ render_live({target: '#app', taco: <your layout TACO>})
293
+ ```
294
+ The UI appears immediately in the browser at http://localhost:7910.
295
+
296
+ ### Step 7: Iterate (Live Mode)
297
+
298
+ If using live rendering:
299
+ ```
300
+ screenshot({}) // see what the browser shows
301
+ screenshot({selector: '.bw_stat_card:first-child'}) // zoom in on one element
302
+ query_dom({code: 'document.querySelectorAll(".bw_card").length'}) // count cards
303
+ ```
304
+
305
+ Evaluate the screenshot, decide what to change, and call `render_live` again.
306
+
307
+ ### Key Rules
308
+
309
+ 1. Every make*() tool returns a TACO object, NOT HTML
310
+ 2. Compose by nesting TACOs in the `c` field: `{t:'div', c: [taco1, taco2]}`
311
+ 3. Grid layout: `bw_container > bw_row > bw_col`
312
+ 4. Always use a theme with `build_page` (ocean, forest, sunset, midnight, etc.)
313
+ 5. Call `render_taco` to preview a single TACO as HTML
314
+ 6. Call `build_page` as the final step to get a standalone file
315
+ 7. The `structuredContent` field in tool results contains the TACO as a parsed object -- use it directly when composing
316
+ 8. Do NOT generate raw HTML strings -- always work with TACO objects
317
+
318
+ ### Common Mistakes
319
+
320
+ - **Stacking everything vertically.** Use the grid (bw_container/bw_row/bw_col).
321
+ - **Calling build_page per component.** Build all components first, compose into one layout, then call build_page once.
322
+ - **Ignoring themes.** `build_page` with no theme produces unstyled output. Always pass a theme name.
323
+ - **Generating HTML strings.** The tools return TACO objects. Compose TACOs, not HTML. Call render_taco or build_page only at the end.
324
+ - **Not calling start_here first.** Without orientation, you will misuse the tools.
325
+
326
+ ### Token Budget
327
+
328
+ | Knowledge Tool | Tokens | When Needed |
329
+ |---------------|--------|-------------|
330
+ | bitwrench_start_here | ~200 | Always (first call) |
331
+ | bitwrench_guide | ~4,000 | Usually (first session) |
332
+ | bitwrench_guide (section) | ~300-600 | When refreshing one topic |
333
+ | bitwrench_components | ~6,500 | When configuring components |
334
+ | bitwrench_components (one) | ~100-300 | When looking up one component |
335
+ | bitwrench_server_guide | ~1,800 | Only for server-driven UI |
336
+ | bitwrench_themes | ~1,900 | Only when theming matters |
337
+
338
+ Minimal session: start_here (200) + a few make_* calls = under 1K tokens of context.
339
+ Typical session: start_here (200) + guide (4K) + components (6.5K) = about 11K tokens.
340
+
341
+
342
+ ## Programmatic Usage (Node.js)
343
+
344
+ ```javascript
345
+ import { createMcpServer } from 'bitwrench/mcp';
346
+
347
+ var server = createMcpServer({
348
+ port: 7910,
349
+ theme: 'ocean',
350
+ open: true
351
+ });
352
+
353
+ server.listen();
354
+ ```
355
+
356
+ ## Programmatic Usage (Python)
357
+
358
+ Two example projects demonstrate Python integration:
359
+
360
+ - **`examples/mcp-agent/`** -- Scripted agent that builds a dashboard and
361
+ saves a standalone HTML file. Demonstrates the full tool workflow
362
+ (orient, build, compose, export, screenshot, inspect).
363
+
364
+ - **`examples/mcp-agent-live/`** -- Connects a local LLM (ollama, lmstudio,
365
+ openrouter, or openai) to bwmcp. You type a prompt, the LLM decides what
366
+ to build, and you watch components appear one by one in the browser with a
367
+ live progress bar. Run `python3 live_builder.py --no-llm` for a demo
368
+ without any LLM.
369
+
370
+ The pattern works with any language -- bwmcp speaks JSON-RPC
371
+ 2.0 over stdin/stdout.
372
+
373
+ ```python
374
+ import subprocess, json
375
+
376
+ proc = subprocess.Popen(
377
+ ['node', '/path/to/bin/bwmcp.js', '--no-browser'],
378
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
379
+ text=True
380
+ )
381
+
382
+ def call_tool(name, args={}):
383
+ msg = {"jsonrpc": "2.0", "id": 1, "method": "tools/call",
384
+ "params": {"name": name, "arguments": args}}
385
+ proc.stdin.write(json.dumps(msg) + "\n")
386
+ proc.stdin.flush()
387
+ return json.loads(proc.stdout.readline())
388
+
389
+ # Orient
390
+ orientation = call_tool("bitwrench_start_here")
391
+ print(orientation["result"]["content"][0]["text"][:200])
392
+
393
+ # Build a card
394
+ card = call_tool("make_card", {"title": "Hello", "content": "World"})
395
+ taco = card["result"]["structuredContent"]
396
+
397
+ # Build a full page
398
+ page = call_tool("build_page", {
399
+ "title": "My Page", "theme": "ocean", "content": taco
400
+ })
401
+ html = page["result"]["content"][0]["text"]
402
+
403
+ with open("output.html", "w") as f:
404
+ f.write(html)
405
+ ```
406
+
407
+
408
+ ## Architecture Notes
409
+
410
+ - bwmcp runs as a single Node.js process
411
+ - MCP protocol is JSON-RPC 2.0 over stdio (newline-delimited)
412
+ - bwserve runs as an embedded HTTP+SSE server on port 7910
413
+ - Knowledge tools read docs from disk at call time (always fresh)
414
+ - Component tools call `bw.makeCard()` etc. from source directly (not dist)
415
+ - No runtime dependencies beyond Node.js stdlib
416
+ - No build step needed -- bwmcp runs from source
417
+
418
+
419
+ ## Related Documentation
420
+
421
+ - [LLM Guide](llm-bitwrench-guide.md) -- The full developer guide served by `bitwrench_guide`
422
+ - [Component Library](component-library.md) -- Full props reference served by `bitwrench_components`
423
+ - [Theming](theming.md) -- Theme configuration served by `bitwrench_themes`
424
+ - [bwserve Tutorial](tutorial-bwserve.md) -- Server-driven UI served by `bitwrench_server_guide`
425
+ - [bwserve Protocol](bwserve.md) -- Wire protocol details (SSE message types)
426
+ - [MCP Server Design](../dev/bitwrench-mcp-server-design.md) -- Internal design document