sygnal 6.0.0 → 6.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/CHANGELOG.md +70 -0
  2. package/dist/ai.cjs.js +115 -0
  3. package/dist/ai.cjs.js.map +1 -0
  4. package/dist/ai.esm.js +2 -0
  5. package/dist/ai.esm.js.map +1 -0
  6. package/dist/astro/index.cjs.js +599 -4
  7. package/dist/astro/index.cjs.js.map +1 -1
  8. package/dist/astro/index.mjs +599 -4
  9. package/dist/astro/index.mjs.map +1 -1
  10. package/dist/astro/server.cjs.js.map +1 -1
  11. package/dist/astro/server.mjs.map +1 -1
  12. package/dist/devtools.cjs.js +413 -4
  13. package/dist/devtools.cjs.js.map +1 -1
  14. package/dist/devtools.esm.js +413 -5
  15. package/dist/devtools.esm.js.map +1 -1
  16. package/dist/diagnostics.cjs.js +170 -12
  17. package/dist/diagnostics.cjs.js.map +1 -1
  18. package/dist/diagnostics.esm.js +170 -12
  19. package/dist/diagnostics.esm.js.map +1 -1
  20. package/dist/guide/accessibility.md +54 -1
  21. package/dist/guide/agent.md +588 -0
  22. package/dist/guide/ai-chat.md +693 -0
  23. package/dist/guide/ai-decisions.md +330 -0
  24. package/dist/guide/forms-reference.md +28 -0
  25. package/dist/guide/forms.md +2 -1
  26. package/dist/guide/http.md +2 -0
  27. package/dist/guide/mcp-apps.md +272 -0
  28. package/dist/guide/recipes/ai-form-fill.md +163 -0
  29. package/dist/guide/recipes/ai-summarize.md +155 -0
  30. package/dist/guide/recipes/ai-support-inbox.md +190 -0
  31. package/dist/guide/recipes/overview.md +10 -0
  32. package/dist/guide/webmcp.md +226 -0
  33. package/dist/index.cjs.js +7841 -3370
  34. package/dist/index.cjs.js.map +1 -1
  35. package/dist/index.d.ts +1288 -6
  36. package/dist/index.esm.js +7139 -2696
  37. package/dist/index.esm.js.map +1 -1
  38. package/dist/sygnal.min.js +1 -1
  39. package/dist/sygnal.min.js.map +1 -1
  40. package/dist/vike/config/package.json +1 -1
  41. package/dist/vite/plugin.cjs.js +599 -4
  42. package/dist/vite/plugin.cjs.js.map +1 -1
  43. package/dist/vite/plugin.mjs +599 -4
  44. package/dist/vite/plugin.mjs.map +1 -1
  45. package/llms.txt +7 -1
  46. package/package.json +15 -1
  47. package/src/ai.d.ts +1186 -0
  48. package/src/ai.ts +23 -0
  49. package/src/core/hooks.ts +1 -1
  50. package/src/devtools.d.ts +20 -1
  51. package/src/devtools.ts +3 -0
  52. package/src/extra/ai/agent/index.ts +484 -0
  53. package/src/extra/ai/answers.ts +115 -0
  54. package/src/extra/ai/chat/behavior.ts +336 -0
  55. package/src/extra/ai/chat/driver.ts +271 -0
  56. package/src/extra/ai/chat/memoryTransport.ts +61 -0
  57. package/src/extra/ai/chat/output.ts +37 -0
  58. package/src/extra/ai/commandBar.ts +281 -0
  59. package/src/extra/ai/decide.ts +104 -0
  60. package/src/extra/ai/index.ts +42 -0
  61. package/src/extra/ai/link.ts +90 -0
  62. package/src/extra/ai/mcpApp.ts +314 -0
  63. package/src/extra/ai/messages.ts +51 -0
  64. package/src/extra/ai/schema/index.ts +166 -0
  65. package/src/extra/ai/schema/jsonSchema.ts +72 -0
  66. package/src/extra/ai/schema/strict.ts +152 -0
  67. package/src/extra/ai/transports/agui.ts +177 -0
  68. package/src/extra/ai/transports/anthropicMessages.ts +175 -0
  69. package/src/extra/ai/transports/chatCompletions.ts +105 -0
  70. package/src/extra/ai/transports/chromePrompt.ts +77 -0
  71. package/src/extra/ai/transports/encodeOpenResponses.ts +87 -0
  72. package/src/extra/ai/transports/fromAISDK.ts +126 -0
  73. package/src/extra/ai/transports/openResponses.ts +105 -0
  74. package/src/extra/ai/transports/shared.ts +125 -0
  75. package/src/extra/ai/transports/tools.ts +59 -0
  76. package/src/extra/ai/transports/uiMessageStream.ts +107 -0
  77. package/src/extra/ai/webmcp.ts +260 -0
  78. package/src/extra/copyAsTest.ts +2 -2
  79. package/src/extra/devMcp.ts +386 -0
  80. package/src/extra/devtoolsActions.ts +1 -1
  81. package/src/extra/diagnostics/checks/actionLog.ts +3 -3
  82. package/src/extra/diagnostics/checks/chat.ts +71 -0
  83. package/src/extra/diagnostics/checks/forms.ts +8 -0
  84. package/src/extra/diagnostics/checks/index.ts +6 -0
  85. package/src/extra/diagnostics/checks/public.d.ts +19 -2
  86. package/src/extra/diagnostics/checks/wiring.ts +5 -2
  87. package/src/extra/diagnostics/codes.ts +67 -0
  88. package/src/extra/form.ts +22 -6
  89. package/src/extra/formTool.ts +150 -0
  90. package/src/extra/testing.ts +125 -8
  91. package/src/index.d.ts +116 -3
  92. package/src/index.ts +21 -1
  93. package/src/shared.ts +9 -0
  94. package/src/vite/mcp.ts +568 -0
  95. package/src/vite/plugin.d.ts +27 -2
  96. package/src/vite/plugin.ts +43 -4
@@ -55,6 +55,571 @@ function globalThisAlias(userAlias) {
55
55
  return shim ? [{ find: /^globalthis$/, replacement: shim }] : [];
56
56
  }
57
57
 
58
+ /**
59
+ * PLAN-6 E-1: the dev MCP endpoint of sygnal/vite (`sygnal({ mcp: true })`), dev server only.
60
+ *
61
+ * `/__sygnal/mcp` speaks MCP's streamable HTTP transport: JSON-RPC 2.0 over POST, answered as
62
+ * one `application/json` body, in both protocol eras (G-655: a dual-era server):
63
+ *
64
+ * - legacy, the `initialize` revisions (2024-11-05 … 2025-11-25). G-638: JSON replies make a
65
+ * complete server under the spec (the client must accept JSON or SSE; a server without a GET
66
+ * stream answers 405; session ids are optional, "MAY assign"). Methods: initialize, ping,
67
+ * tools/list, tools/call; notifications get 202; batches (2025-03-26) are answered.
68
+ * - modern, the stateless 2026-07-28 revision (no initialize, no sessions, no ping): each request
69
+ * carries `_meta['io.modelcontextprotocol/protocolVersion']` and `.../clientCapabilities`, and
70
+ * the `MCP-Protocol-Version`, `Mcp-Method` and (tools/call) `Mcp-Name` headers, which must
71
+ * match the body (else 400 with -32020 HeaderMismatch; missing `_meta` fields: 400, -32602).
72
+ * Methods: server/discover, tools/list, tools/call; any other gets 404 with -32601. Results
73
+ * carry `resultType: 'complete'` and `_meta['io.modelcontextprotocol/serverInfo']`; tools/list
74
+ * and server/discover are cacheable results (`ttlMs`, `cacheScope`). No subscriptions/listen
75
+ * (the tool list never changes), no MRTR input requests, no logging.
76
+ *
77
+ * The era comes from each request: a 2026-07-28 header or `_meta` version is modern, anything else
78
+ * legacy (no header: 2025-03-26, as the spec allows). An unknown version gets 400 with -32022
79
+ * (UnsupportedProtocolVersion, `data: { supported, requested }`), so a modern client retries
80
+ * with one this server speaks. The server never sends requests or notifications of its own (no
81
+ * sampling, no progress, tools/list never changes), so an SSE stream would carry nothing; without
82
+ * session ids each POST stands alone (the page state lives in the browser, not in a session).
83
+ * GET and DELETE get 405. Spec: modelcontextprotocol.io/specification/2026-07-28/basic/versioning
84
+ * and .../basic/transports/streamable-http. Hand-written like sygnal-check's stdio server (no
85
+ * dependency, D209).
86
+ *
87
+ * Tools that read the page (get_state, dispatch, component_tree, recent_actions,
88
+ * get_diagnostics, copy_as_test, agent_tools) go to an open tab through a PageBridge: in the dev
89
+ * server, Vite's HMR channel (custom events 'sygnal:mcp:*', see src/extra/devMcp.ts), request /
90
+ * response with ids and a timeout. With several tabs the most recently loaded or focused one
91
+ * answers, or the `tab` argument picks one; the result says which (`tab`), and `tabs` lists
92
+ * them with their apps. G-638: every run() app of a page is served: `app` (an index, or the
93
+ * root component's name) picks one on get_state, dispatch, component_tree, copy_as_test and
94
+ * agent_tools (default: the first, or the app that has `component`); `apps` lists them. check / graph / explain run sygnal-check's own MCP server in-process when sygnal-check
95
+ * is installed in the project.
96
+ *
97
+ * Security (the endpoint can read and change the running app): requests must come from the
98
+ * loopback interface; the Host header must be localhost, a *.localhost name, a loopback IP or a
99
+ * name in Vite's `server.allowedHosts`; a request with an Origin header must come from a
100
+ * localhost / loopback origin (a web page elsewhere, or a DNS-rebinding page, gets 403).
101
+ */
102
+ // @ts-ignore
103
+ const MCP_PATH = '/__sygnal/mcp';
104
+ const MCP_HELLO = 'sygnal:mcp:hello';
105
+ const MCP_REQUEST = 'sygnal:mcp:request';
106
+ const MCP_RESPONSE = 'sygnal:mcp:response';
107
+ /** G-655: the stateless revisions (per-request `_meta`, no initialize), newest first */
108
+ const MODERN_VERSIONS = ['2026-07-28'];
109
+ /** the `initialize` revisions, newest first; initialize answers with the client's version when it knows it */
110
+ const LEGACY_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'];
111
+ const SUPPORTED_VERSIONS = [...MODERN_VERSIONS, ...LEGACY_VERSIONS];
112
+ const META = 'io.modelcontextprotocol/';
113
+ const INSTRUCTIONS = 'The running Sygnal apps in the dev server\'s open page: component_tree to orient, get_state / recent_actions / get_diagnostics to read, dispatch or agent_tools to act, copy_as_test to turn a session into a test; apps lists the page\'s run() apps when there are several (`app` picks one). check, graph and explain (when present) are sygnal-check on the sources.';
114
+ /** 2026-07-28 cacheable results (tools/list, server/discover): the list is fixed while the dev server runs, not across restarts */
115
+ const CACHE = { ttlMs: 0, cacheScope: 'private' };
116
+ const MAX_BODY = 1 << 20;
117
+ class ToolError extends Error {
118
+ }
119
+ const isObj = (v) => !!v && typeof v === 'object' && !Array.isArray(v);
120
+ const tabSchema = { type: 'integer', description: 'The tab to ask (see tabs); default: the most recently loaded or focused tab' };
121
+ const componentSchema = { type: ['string', 'integer'], description: 'A component name, or an instance id (see component_tree); default: the root' };
122
+ const appSchema = { type: ['string', 'integer'], description: "The app on the page: an index or the root component's name (see apps); default: the first app, or the one that has `component`" };
123
+ const obj = (properties, required) => ({
124
+ type: 'object', properties: { ...properties, tab: tabSchema }, ...(required ? { required } : {}), additionalProperties: false,
125
+ });
126
+ /** The tools answered by the page */
127
+ const PAGE_TOOLS = [
128
+ {
129
+ name: 'get_state',
130
+ title: 'Get component state',
131
+ description: "The live state of a component instance in the open page (the root by default). With several instances of a component (Collection items) you get each one's id and state. `path` reads one field: 'todos.0.text' or ['todos', 0, 'text'].",
132
+ inputSchema: obj({ component: componentSchema, app: appSchema, path: { type: ['string', 'array'], items: { type: ['string', 'integer'] }, description: "A field path: 'a.b.0' or ['a', 'b', 0]" } }),
133
+ annotations: { readOnlyHint: true },
134
+ },
135
+ {
136
+ name: 'dispatch',
137
+ title: 'Dispatch an action',
138
+ description: "Send an action to a component instance in the open page, as if its intent had produced it (recorded with cause 'agent'), and wait for the render. Returns the instance's new state. The action must be one of the component's model entries (an unknown name lists them).",
139
+ inputSchema: obj({ component: componentSchema, app: appSchema, action: { type: 'string', description: "The action name, e.g. 'ADD'" }, data: { description: 'The action data (any JSON value)' } }, ['action']),
140
+ },
141
+ {
142
+ name: 'component_tree',
143
+ title: 'Component tree (inspect)',
144
+ description: "The running apps' graph from inspect(): component instances (id, parentId, kind), their actions and what triggers them, state keys, context, EVENTS, children, intent selectors (matched or not) and the runtime diagnostics attached to each. `app` keeps one app's instances, `component` only that component's.",
145
+ inputSchema: obj({ component: componentSchema, app: { ...appSchema, description: "Only this app's instances: an index or the root component's name (see apps); default: every app" } }),
146
+ annotations: { readOnlyHint: true },
147
+ },
148
+ {
149
+ name: 'recent_actions',
150
+ title: 'Recent actions',
151
+ description: "The DevTools action log of the open page, newest last: type, data, component, instance, cause ('intent', 'agent', 'reply', ...), the sinks it reached and the state before / after a STATE change.",
152
+ inputSchema: obj({
153
+ limit: { type: 'integer', minimum: 1, maximum: 500, description: 'How many (default 20)' },
154
+ component: { type: 'string', description: 'Only this component' },
155
+ type: { type: 'string', description: 'Only this action type' },
156
+ cause: { type: 'string', enum: ['intent', 'next', 'reply', 'built-in', 'simulateAction', 'behavior', 'agent', 'setState'], description: 'Only this cause' },
157
+ }),
158
+ annotations: { readOnlyHint: true },
159
+ },
160
+ {
161
+ name: 'get_diagnostics',
162
+ title: 'Runtime diagnostics',
163
+ description: 'The runtime diagnostics the open page reported (SYG codes): code, severity, component, message, fix and docsUrl, with a summary. Use explain for a code you do not know.',
164
+ inputSchema: obj({
165
+ code: { type: 'string', description: "Only this code, e.g. 'SYG104'" },
166
+ severity: { type: 'string', enum: ['error', 'warn', 'info'] },
167
+ limit: { type: 'integer', minimum: 1, maximum: 500, description: 'How many, newest (default 100)' },
168
+ }),
169
+ annotations: { readOnlyHint: true },
170
+ },
171
+ {
172
+ name: 'copy_as_test',
173
+ title: 'Copy session as test',
174
+ description: "DevTools' Copy as test: a Vitest + renderComponent test file that replays what happened to a component instance in the open page (default: the root) and asserts its final state. Returns { code, complete, warnings, replayed }.",
175
+ inputSchema: obj({ component: componentSchema, app: appSchema, componentImport: { type: 'string', description: "Where the test imports the component from: a module path ('./App.jsx') or a whole import line" } }),
176
+ annotations: { readOnlyHint: true },
177
+ },
178
+ {
179
+ name: 'agent_tools',
180
+ title: "The app's agent tools",
181
+ description: "The open page's own agent tools (the `agent` statics, sygnal/ai): without `call`, the tools offered now (name, description, inputSchema, annotations) and the readable context; with `call`, runs that tool with `input` under the app's rules (validation, `when`, a consequential tool asks the person in the page first).",
182
+ inputSchema: obj({
183
+ call: { type: 'string', description: 'A tool name from the list' },
184
+ input: { description: 'The tool input' },
185
+ all: { type: 'boolean', description: 'List also the declared tools that are not offered, with why' },
186
+ app: { ...appSchema, description: "The app whose tools to use: an index or the root component's name (see apps); default: the first" },
187
+ }),
188
+ },
189
+ {
190
+ name: 'apps',
191
+ title: 'Apps on the page',
192
+ description: "The Sygnal apps (run() calls) running in the open page: index, root component, root instance id and instance count. The first is the default of the tools' `app` argument.",
193
+ inputSchema: obj({}),
194
+ annotations: { readOnlyHint: true },
195
+ },
196
+ ];
197
+ const TABS_TOOL = {
198
+ name: 'tabs',
199
+ title: 'Open pages',
200
+ description: 'The pages of this dev server connected to the endpoint (id, url, title, apps: { index, component } per run() app); the page tools use the most recently loaded or focused one unless given `tab`.',
201
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
202
+ annotations: { readOnlyHint: true },
203
+ };
204
+ /** sygnal-check's MCP server (its `src/mcp.js`), loaded from the project; undefined when missing */
205
+ async function loadCheckServer(root) {
206
+ try {
207
+ const main = createRequire(path.join(root, 'package.json')).resolve('sygnal-check');
208
+ const file = path.join(path.dirname(main), 'mcp.js');
209
+ if (!fs.existsSync(file))
210
+ return undefined;
211
+ const mod = await import(/* @vite-ignore */ pathToFileURL(file).href);
212
+ if (typeof mod.createMcpServer !== 'function' || !Array.isArray(mod.TOOLS))
213
+ return undefined;
214
+ return { tools: mod.TOOLS, server: mod.createMcpServer({ cwd: root }) };
215
+ }
216
+ catch (_) {
217
+ return undefined;
218
+ }
219
+ }
220
+ /** The JSON-RPC side of the endpoint (transport-free; tests drive it directly) */
221
+ function createDevMcpServer(o) {
222
+ const timeout = o.timeout && o.timeout > 0 ? o.timeout : 10000;
223
+ const result = (id, value) => ({ jsonrpc: '2.0', id, result: value });
224
+ const error = (id, code, message) => ({ jsonrpc: '2.0', id, error: { code, message } });
225
+ let check;
226
+ const getCheck = async () => (check === undefined ? (check = (await o.check) || null) : check);
227
+ const pickTab = (want) => {
228
+ const tabs = o.bridge.tabs();
229
+ if (!tabs.length) {
230
+ const url = o.url?.();
231
+ throw new ToolError(`no page is connected: open the app${url ? ` (${url})` : ''} in a browser, with the dev server running`);
232
+ }
233
+ if (want !== undefined && want !== null) {
234
+ const tab = tabs.find(t => t.id === Number(want));
235
+ if (!tab)
236
+ throw new ToolError(`no tab ${want}; open tabs: ${tabs.map(t => `${t.id} ${t.url}`).join(', ')}`);
237
+ return { tab };
238
+ }
239
+ const tab = tabs.reduce((a, b) => (b.active > a.active ? b : a));
240
+ return { tab, note: tabs.length > 1 ? `${tabs.length} tabs are open; used tab ${tab.id} (the most recently loaded or focused). Pass tab to choose one (see tabs).` : undefined };
241
+ };
242
+ const content = (value, isError = false) => {
243
+ const structured = isObj(value) ? value : { value };
244
+ return { content: [{ type: 'text', text: JSON.stringify(structured, null, 2) }], structuredContent: structured, isError };
245
+ };
246
+ async function callTool(name, args) {
247
+ if (name === 'tabs')
248
+ return content({ tabs: o.bridge.tabs().map(({ id, url, title, apps }) => ({ id, url, title, ...(apps ? { apps } : {}) })) });
249
+ const { tab: want, ...rest } = args;
250
+ const { tab, note } = pickTab(want);
251
+ const value = await o.bridge.request(tab.id, name, rest, timeout);
252
+ const out = isObj(value) ? value : { value };
253
+ return content({ ...out, tab: { id: tab.id, url: tab.url, title: tab.title }, ...(note ? { tabNote: note } : {}) });
254
+ }
255
+ const serverInfo = { name: 'sygnal-dev', title: 'Sygnal dev server', version: o.version || '0.0.0' };
256
+ async function handleMessage(msg, modern) {
257
+ if (!isObj(msg) || msg.jsonrpc !== '2.0' || typeof msg.method !== 'string') {
258
+ return isObj(msg) && 'id' in msg && !('result' in msg || 'error' in msg) ? error(msg.id ?? null, -32600, 'Invalid Request') : null;
259
+ }
260
+ if (!('id' in msg) || msg.id === null)
261
+ return null; // a notification
262
+ const { id, method } = msg;
263
+ const params = isObj(msg.params) ? msg.params : {};
264
+ // G-655: 2026-07-28 removed initialize and ping, and added server/discover
265
+ if (modern ? method === 'initialize' || method === 'ping' : method === 'server/discover')
266
+ return error(id, -32601, `Method not found: ${method}`);
267
+ switch (method) {
268
+ case 'initialize': {
269
+ const requested = params.protocolVersion;
270
+ return result(id, {
271
+ protocolVersion: LEGACY_VERSIONS.includes(requested) ? requested : LEGACY_VERSIONS[0],
272
+ capabilities: { tools: { listChanged: false } },
273
+ serverInfo,
274
+ instructions: INSTRUCTIONS,
275
+ });
276
+ }
277
+ case 'server/discover':
278
+ return result(id, { supportedVersions: SUPPORTED_VERSIONS, capabilities: { tools: {} }, instructions: INSTRUCTIONS, ...CACHE });
279
+ case 'ping':
280
+ return result(id, {});
281
+ case 'tools/list': {
282
+ const c = await getCheck();
283
+ return result(id, { tools: [...PAGE_TOOLS, TABS_TOOL, ...(c ? c.tools : [])], ...(modern ? CACHE : {}) });
284
+ }
285
+ case 'tools/call': {
286
+ const name = params.name;
287
+ const args = isObj(params.arguments) ? params.arguments : {};
288
+ if (name === 'tabs' || PAGE_TOOLS.some(t => t.name === name)) {
289
+ try {
290
+ return result(id, await callTool(name, args));
291
+ }
292
+ catch (err) {
293
+ return result(id, { content: [{ type: 'text', text: err instanceof ToolError ? err.message : `${name} failed: ${err?.message || err}` }], isError: true });
294
+ }
295
+ }
296
+ const c = await getCheck();
297
+ if (c && c.tools.some((t) => t.name === name)) {
298
+ // without `_meta`, sygnal-check's server answers in the initialize era's shape (G-656: it
299
+ // speaks 2026-07-28 too, but this endpoint checked the envelope and adds the fields itself)
300
+ const { _meta, ...rest } = params;
301
+ return { ...c.server.handle({ ...msg, params: { ...rest, arguments: args } }), id };
302
+ }
303
+ return error(id, -32602, `Unknown tool: ${name}`);
304
+ }
305
+ default:
306
+ return error(id, -32601, `Method not found: ${method}`);
307
+ }
308
+ }
309
+ /**
310
+ * One message (or a legacy batch); never throws. `modern`: a 2026-07-28 request whose envelope
311
+ * (version, headers, `_meta` fields) the transport checked (see mcpMiddleware); its result is
312
+ * marked `resultType: 'complete'` and names the server in `_meta`.
313
+ */
314
+ async function handle(msg, modern = false) {
315
+ if (Array.isArray(msg)) {
316
+ if (modern)
317
+ return error(null, -32600, 'Invalid Request: one JSON-RPC message per POST');
318
+ const out = (await Promise.all(msg.map((m) => handle(m)))).filter(Boolean);
319
+ return out.length ? out : null;
320
+ }
321
+ try {
322
+ const out = await handleMessage(msg, modern);
323
+ if (modern && out && isObj(out.result)) {
324
+ const meta = isObj(out.result._meta) ? out.result._meta : {};
325
+ out.result = { resultType: 'complete', ...out.result, _meta: { ...meta, [META + 'serverInfo']: serverInfo } };
326
+ }
327
+ return out;
328
+ }
329
+ catch (err) {
330
+ return error(isObj(msg) && 'id' in msg ? msg.id ?? null : null, -32603, `Internal error: ${err?.message || err}`);
331
+ }
332
+ }
333
+ return { handle };
334
+ }
335
+ // ---------------------------------------------------------------- security
336
+ const LOOPBACK_IP = /^(127\.\d{1,3}\.\d{1,3}\.\d{1,3}|::1|::ffff:127\.\d{1,3}\.\d{1,3}\.\d{1,3})$/;
337
+ /** The host part of a Host header value or URL host ('[::1]:5173' → '::1') */
338
+ function hostname(host) {
339
+ const h = host.trim().toLowerCase();
340
+ if (h.startsWith('['))
341
+ return h.slice(1, h.indexOf(']') > 0 ? h.indexOf(']') : undefined);
342
+ const i = h.lastIndexOf(':');
343
+ return i > 0 && h.indexOf(':') === i ? h.slice(0, i) : h;
344
+ }
345
+ const isLocalName = (h) => h === 'localhost' || h.endsWith('.localhost') || LOOPBACK_IP.test(h);
346
+ /** Vite's allowedHosts entries: 'example.test', or '.example.test' for it and its subdomains */
347
+ function inAllowed(h, allowed) {
348
+ if (!Array.isArray(allowed))
349
+ return false;
350
+ return allowed.some((a) => {
351
+ if (typeof a !== 'string' || !a)
352
+ return false;
353
+ const e = a.toLowerCase();
354
+ return e.startsWith('.') ? h === e.slice(1) || h.endsWith(e) : h === e;
355
+ });
356
+ }
357
+ /** Why the request is refused (403), or null */
358
+ function refusal(req, allowedHosts) {
359
+ const remote = String(req?.socket?.remoteAddress || '');
360
+ if (!LOOPBACK_IP.test(remote))
361
+ return `the Sygnal MCP endpoint only answers requests from this machine (not ${remote || 'an unknown address'})`;
362
+ const host = req?.headers?.host;
363
+ if (typeof host !== 'string' || !host)
364
+ return 'missing Host header';
365
+ const h = hostname(host);
366
+ if (!isLocalName(h) && !inAllowed(h, allowedHosts))
367
+ return `Host ${host} is not a local name (add it to server.allowedHosts to allow it)`;
368
+ const origin = req?.headers?.origin;
369
+ if (origin !== undefined && origin !== 'null') {
370
+ let oh = '';
371
+ try {
372
+ oh = new URL(String(origin)).hostname.replace(/^\[|\]$/g, '').toLowerCase();
373
+ }
374
+ catch (_) { }
375
+ if (!oh || (!isLocalName(oh) && !inAllowed(oh, allowedHosts)))
376
+ return `Origin ${origin} is not allowed`;
377
+ }
378
+ else if (origin === 'null') {
379
+ return 'Origin null is not allowed';
380
+ }
381
+ return null;
382
+ }
383
+ // ---------------------------------------------------------------- HTTP
384
+ function send(res, status, body, headers = {}) {
385
+ res.statusCode = status;
386
+ for (const k in headers)
387
+ res.setHeader(k, headers[k]);
388
+ if (body === undefined)
389
+ return res.end();
390
+ res.setHeader('Content-Type', 'application/json');
391
+ res.end(JSON.stringify(body));
392
+ }
393
+ function readBody(req) {
394
+ return new Promise((resolve, reject) => {
395
+ let size = 0;
396
+ const chunks = [];
397
+ req.on('data', (c) => {
398
+ size += c.length;
399
+ if (size > MAX_BODY) {
400
+ reject(new Error('too large'));
401
+ req.destroy?.();
402
+ }
403
+ else
404
+ chunks.push(c);
405
+ });
406
+ req.on('end', () => resolve(globalThis.Buffer.concat(chunks).toString('utf8')));
407
+ req.on('error', reject);
408
+ });
409
+ }
410
+ /** An `Mcp-Name` value: plain, or the spec's `=?base64?…?=` sentinel for one that isn't header-safe */
411
+ function headerValue(v) {
412
+ const m = /^=\?base64\?(.*)\?=$/.exec(v);
413
+ return m ? globalThis.Buffer.from(m[1], 'base64').toString('utf8') : v;
414
+ }
415
+ /**
416
+ * G-655: why a 2026-07-28 request's envelope is refused, as [code, message], or null. The spec
417
+ * (basic/index "_meta", transports/streamable-http "Server Validation"): `_meta` must carry the
418
+ * protocol version and the client capabilities (-32602), and the MCP-Protocol-Version, Mcp-Method
419
+ * and (tools/call, resources/read, prompts/get) Mcp-Name headers must be there and match the body
420
+ * (-32020 HeaderMismatch). This server marks no parameter with `x-mcp-header`, so no
421
+ * Mcp-Param-* header is required.
422
+ */
423
+ function modernEnvelope(msg, headers) {
424
+ const params = isObj(msg.params) ? msg.params : {};
425
+ const meta = isObj(params._meta) ? params._meta : {};
426
+ if (typeof meta[META + 'protocolVersion'] !== 'string')
427
+ return [-32602, `Invalid params: _meta["${META}protocolVersion"] is required`];
428
+ if (!isObj(meta[META + 'clientCapabilities']))
429
+ return [-32602, `Invalid params: _meta["${META}clientCapabilities"] is required`];
430
+ const header = headers['mcp-protocol-version'];
431
+ if (header !== meta[META + 'protocolVersion']) {
432
+ return [-32020, header === undefined ? 'Header mismatch: MCP-Protocol-Version header is required' : `Header mismatch: MCP-Protocol-Version header value '${header}' does not match body value '${meta[META + 'protocolVersion']}'`];
433
+ }
434
+ const method = headers['mcp-method'];
435
+ if (method !== msg.method)
436
+ return [-32020, method === undefined ? 'Header mismatch: Mcp-Method header is required' : `Header mismatch: Mcp-Method header value '${method}' does not match body value '${msg.method}'`];
437
+ if (msg.method === 'tools/call' || msg.method === 'prompts/get' || msg.method === 'resources/read') {
438
+ const want = msg.method === 'resources/read' ? params.uri : params.name;
439
+ const name = headers['mcp-name'];
440
+ if (typeof name !== 'string')
441
+ return [-32020, 'Header mismatch: Mcp-Name header is required'];
442
+ if (headerValue(name) !== want)
443
+ return [-32020, `Header mismatch: Mcp-Name header value '${name}' does not match body value '${want}'`];
444
+ }
445
+ return null;
446
+ }
447
+ /** The connect middleware for MCP_PATH */
448
+ function mcpMiddleware(server, allowedHosts) {
449
+ return async (req, res, next) => {
450
+ const url = String(req.url || '').replace(/[?#].*$/, '');
451
+ if (url !== MCP_PATH && url !== MCP_PATH + '/')
452
+ return next();
453
+ const why = refusal(req, allowedHosts());
454
+ if (why)
455
+ return send(res, 403, { jsonrpc: '2.0', id: null, error: { code: -32000, message: `Forbidden: ${why}` } });
456
+ // G-638: no SSE stream on GET (the spec's "MUST ... return 405" for a server that offers none), no sessions to DELETE
457
+ if (req.method !== 'POST')
458
+ return send(res, 405, { jsonrpc: '2.0', id: null, error: { code: -32000, message: 'Method not allowed: this endpoint takes JSON-RPC over POST and answers with application/json (no SSE stream, no sessions)' } }, { Allow: 'POST' });
459
+ let msg;
460
+ try {
461
+ msg = JSON.parse(await readBody(req));
462
+ }
463
+ catch (err) {
464
+ if (err?.message === 'too large')
465
+ return send(res, 413, { jsonrpc: '2.0', id: null, error: { code: -32600, message: 'Request too large' } });
466
+ return send(res, 400, { jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } });
467
+ }
468
+ // G-655: the era is per request: a 2026-07-28 version in the header or in `_meta` is modern
469
+ // (stateless), anything else the initialize era (no header: 2025-03-26)
470
+ const id = isObj(msg) && 'id' in msg ? msg.id ?? null : null;
471
+ const fail = (status, code, message, data) => send(res, status, { jsonrpc: '2.0', id, error: { code, message, ...(data ? { data } : {}) } });
472
+ const header = req.headers['mcp-protocol-version'];
473
+ const meta = isObj(msg) && isObj(msg.params) && isObj(msg.params._meta) ? msg.params._meta : {};
474
+ const metaVersion = meta[META + 'protocolVersion'];
475
+ for (const requested of [header, metaVersion]) {
476
+ if (requested !== undefined && !SUPPORTED_VERSIONS.includes(requested)) {
477
+ return fail(400, -32022, 'Unsupported protocol version', { supported: SUPPORTED_VERSIONS, requested });
478
+ }
479
+ }
480
+ const modern = MODERN_VERSIONS.includes(header) || MODERN_VERSIONS.includes(metaVersion);
481
+ if (modern) {
482
+ if (!isObj(msg))
483
+ return fail(400, -32600, 'Invalid Request: one JSON-RPC message per POST');
484
+ if ('id' in msg && msg.id !== null) {
485
+ const why = modernEnvelope(msg, req.headers);
486
+ if (why)
487
+ return fail(400, why[0], why[1]);
488
+ }
489
+ }
490
+ const out = await server.handle(msg, modern);
491
+ if (out === null || out === undefined)
492
+ return send(res, 202);
493
+ // 2026-07-28: a method this server doesn't implement is 404 (the JSON-RPC body tells it from a missing endpoint)
494
+ send(res, modern && out.error?.code === -32601 ? 404 : 200, out);
495
+ };
496
+ }
497
+ // ---------------------------------------------------------------- the page bridge (Vite's HMR channel)
498
+ /** A PageBridge over the dev server's HMR channel (server.ws / environments.client.hot) */
499
+ function hmrBridge(server) {
500
+ const ws = server?.ws || server?.environments?.client?.hot;
501
+ const tabs = new Map();
502
+ const pending = new Map();
503
+ let nextTab = 1;
504
+ let nextReq = 1;
505
+ let clock = 0;
506
+ const fail = (client) => {
507
+ const t = tabs.get(client);
508
+ tabs.delete(client);
509
+ if (!t)
510
+ return;
511
+ for (const [id, p] of pending) {
512
+ if (p.client !== client)
513
+ continue;
514
+ clearTimeout(p.timer);
515
+ pending.delete(id);
516
+ p.reject(new ToolError(`tab ${t.id} closed before it answered`));
517
+ }
518
+ };
519
+ if (ws && typeof ws.on === 'function') {
520
+ ws.on(MCP_HELLO, (data, client) => {
521
+ if (!client)
522
+ return;
523
+ let t = tabs.get(client);
524
+ if (!t) {
525
+ tabs.set(client, t = { id: nextTab++, url: '', title: '', active: 0 });
526
+ // Vite's socket client carries its WebSocket: a closed tab leaves at once
527
+ try {
528
+ client.socket?.once?.('close', () => fail(client));
529
+ }
530
+ catch (_) { }
531
+ }
532
+ t.url = String(data?.url || '');
533
+ t.title = String(data?.title || '');
534
+ if (Array.isArray(data?.apps))
535
+ t.apps = data.apps.map((a) => ({ index: Number(a?.index), component: String(a?.component ?? '') }));
536
+ // an apps update (an HMR swap, a second run()) is not a focus
537
+ if (!data?.update || !t.active)
538
+ t.active = ++clock;
539
+ });
540
+ ws.on(MCP_RESPONSE, (data, client) => {
541
+ const p = data && pending.get(data.id);
542
+ if (!p || p.client !== client)
543
+ return;
544
+ if (data.waiting) {
545
+ clearTimeout(p.timer);
546
+ p.timer = setTimeout(() => expire(data.id), 5 * 60000);
547
+ return;
548
+ }
549
+ clearTimeout(p.timer);
550
+ pending.delete(data.id);
551
+ if (data.ok)
552
+ p.resolve(data.result);
553
+ else
554
+ p.reject(new ToolError(String(data.error || 'the page reported an error')));
555
+ });
556
+ }
557
+ /** tabs whose socket is still open (when the channel tells) */
558
+ const live = () => {
559
+ let open;
560
+ try {
561
+ open = ws?.clients;
562
+ }
563
+ catch (_) { }
564
+ for (const c of [...tabs.keys()]) {
565
+ const closed = c.socket && typeof c.socket.readyState === 'number' && c.socket.readyState > 1;
566
+ if (closed || (open instanceof Set && c.socket && !open.has(c)))
567
+ fail(c);
568
+ }
569
+ return tabs;
570
+ };
571
+ function expire(id) {
572
+ const p = pending.get(id);
573
+ if (!p)
574
+ return;
575
+ pending.delete(id);
576
+ p.reject(new ToolError(`tab ${p.tab} did not answer in time (is the page frozen, or a dialog open?)`));
577
+ }
578
+ return {
579
+ tabs: () => [...live().values()].map(t => ({ ...t, ...(t.apps ? { apps: t.apps.map(a => ({ ...a })) } : {}) })),
580
+ request(tabId, tool, args, ms) {
581
+ const client = [...live().entries()].find(([, t]) => t.id === tabId)?.[0];
582
+ if (!client)
583
+ return Promise.reject(new ToolError(`no tab ${tabId}`));
584
+ const id = nextReq++;
585
+ return new Promise((resolve, reject) => {
586
+ const timer = setTimeout(() => expire(id), ms);
587
+ pending.set(id, { tab: tabId, resolve, reject, timer, client });
588
+ try {
589
+ client.send({ type: 'custom', event: MCP_REQUEST, data: { id, tool, args } });
590
+ }
591
+ catch (err) {
592
+ clearTimeout(timer);
593
+ pending.delete(id);
594
+ fail(client);
595
+ reject(new ToolError(`tab ${tabId} is gone: ${err?.message || err}`));
596
+ }
597
+ });
598
+ },
599
+ };
600
+ }
601
+ /** Wire the endpoint into a Vite dev server */
602
+ function attachMcp(server, root, options, version) {
603
+ const bridge = hmrBridge(server);
604
+ const mcp = createDevMcpServer({
605
+ ...options,
606
+ bridge,
607
+ version,
608
+ check: loadCheckServer(root),
609
+ url: () => server?.resolvedUrls?.local?.[0],
610
+ });
611
+ server.middlewares.use(mcpMiddleware(mcp, () => server?.config?.server?.allowedHosts));
612
+ return mcp;
613
+ }
614
+ /** 'virtual:sygnal/mcp': connects the page (dev only) */
615
+ function mcpClientModule(options) {
616
+ const confirm = options.confirm === undefined ? 'page' : options.confirm;
617
+ return `import { agentTools } from 'sygnal';
618
+ import { installMcpBridge } from 'sygnal/devtools';
619
+ if (import.meta.hot) installMcpBridge(import.meta.hot, { agentTools, confirm: ${JSON.stringify(confirm)} });
620
+ `;
621
+ }
622
+
58
623
  /**
59
624
  * Sygnal Vite Plugin
60
625
  *
@@ -161,6 +726,10 @@ function globalThisAlias(userAlias) {
161
726
  * Vitest: production builds carry no DevTools code. `devtools: false`
162
727
  * injects nothing. PLAN-4 3-E: `devtools: { redux: true }` also calls
163
728
  * connectReduxDevtools() (actions + state to the Redux DevTools extension).
729
+ * 10. `mcp` option (PLAN-6 E-1, default false): the dev server serves an MCP endpoint at
730
+ * /__sygnal/mcp (./mcp.ts: streamable HTTP, loopback / local Host / local Origin only)
731
+ * and the dev entries also import 'virtual:sygnal/mcp', which connects the page over the
732
+ * HMR channel (installMcpBridge from 'sygnal/devtools'). Never in `vite build` or Vitest.
164
733
  *
165
734
  * Why not Vite's `define`? Vite's dependency optimizer does not apply user
166
735
  * `define` replacements to pre-bundled dependencies (only process.env.NODE_ENV),
@@ -201,6 +770,9 @@ const CHECK_EVENT = 'sygnal:check';
201
770
  // Sent by the dev client when it loads: the server answers that client only
202
771
  const CHECK_REQUEST = 'sygnal:check:request';
203
772
  const OVERLAY_PLUGIN = 'sygnal-check';
773
+ // PLAN-6 E-1: the page side of the dev MCP endpoint
774
+ const MCP_CLIENT = 'virtual:sygnal/mcp';
775
+ const MCP_CLIENT_ID = '\0' + MCP_CLIENT;
204
776
  // Register the runtime checks with the core that loaded last (see the Vike wrapper)
205
777
  const REINSTALL_IMPORT = `import { installChecks as __sygnalInstallChecks } from 'sygnal/diagnostics';`;
206
778
  const REINSTALL_CALL = 'try { __sygnalInstallChecks() } catch (e) { console.warn(e) }\n';
@@ -219,11 +791,14 @@ function sygnal(options = {}) {
219
791
  const flags = DEV_FLAG + (diagnostics.strict ? STRICT_FLAG : '');
220
792
  const devImports = `import 'sygnal/diagnostics';import '${DEV_CLIENT}';`;
221
793
  // D77: the DevTools bridge, dev only. First, so the diagnostics entry finds it.
222
- const devtoolsOn = options.devtools !== false;
794
+ // E-1: the MCP endpoint needs the bridge, so `mcp` turns it on
795
+ const mcpOn = !!options.mcp;
796
+ const mcpOptions = typeof options.mcp === 'object' && options.mcp ? options.mcp : {};
797
+ const devtoolsOn = options.devtools !== false || mcpOn;
223
798
  const redux = typeof options.devtools == 'object' && !!options.devtools?.redux;
224
- const devtoolsImport = !devtoolsOn ? ''
799
+ const devtoolsImport = (!devtoolsOn ? ''
225
800
  : redux ? `import { connectReduxDevtools as __sygnalReduxDevtools } from 'sygnal/devtools';__sygnalReduxDevtools();`
226
- : `import 'sygnal/devtools';`;
801
+ : `import 'sygnal/devtools';`) + (mcpOn ? `import '${MCP_CLIENT}';` : '');
227
802
  // What a dev entry gets: DevTools, then (unless diagnostics are 'off') flags + checks
228
803
  const devSnippet = devtoolsImport + (devOn ? flags + devImports : '');
229
804
  const devInject = devOn || devtoolsOn;
@@ -336,6 +911,8 @@ function sygnal(options = {}) {
336
911
  return null;
337
912
  if (source === DEV_CLIENT)
338
913
  return DEV_CLIENT_ID;
914
+ if (source === MCP_CLIENT && mcpOn)
915
+ return MCP_CLIENT_ID;
339
916
  if (source === 'sygnal' && importer && wrapRun && runtimeImporters.has(cleanId(importer))) {
340
917
  return RUNTIME_ID;
341
918
  }
@@ -356,6 +933,8 @@ function sygnal(options = {}) {
356
933
  load(id) {
357
934
  if (id === DEV_CLIENT_ID)
358
935
  return devClientModule();
936
+ if (id === MCP_CLIENT_ID && mcpOn)
937
+ return mcpClientModule(mcpOptions);
359
938
  if (id === RUNTIME_ID)
360
939
  return runtimeModule(diagnostics);
361
940
  // The checks register again once the real entry has loaded: a
@@ -369,7 +948,13 @@ function sygnal(options = {}) {
369
948
  return null;
370
949
  },
371
950
  configureServer(server) {
372
- if (isVitest || options.check === false)
951
+ if (isVitest)
952
+ return;
953
+ // E-1: the MCP endpoint (a middleware ahead of Vite's own; it does its own host checks)
954
+ if (mcpOn && server?.middlewares) {
955
+ attachMcp(server, root, mcpOptions, sygnalVersion(root));
956
+ }
957
+ if (options.check === false)
373
958
  return;
374
959
  const checkOptions = typeof options.check === 'object' && options.check ? options.check : {};
375
960
  // Deferred: the dev server doesn't wait for the first check
@@ -644,6 +1229,16 @@ function sygnalPackageDir(root) {
644
1229
  catch (_) { }
645
1230
  return undefined;
646
1231
  }
1232
+ /** The version of the 'sygnal' package the project resolves */
1233
+ function sygnalVersion(root) {
1234
+ const dir = sygnalPackageDir(root);
1235
+ try {
1236
+ return dir ? JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')).version : undefined;
1237
+ }
1238
+ catch (_) {
1239
+ return undefined;
1240
+ }
1241
+ }
647
1242
  /** Real paths of sygnal's 'astro/client' ESM file. */
648
1243
  function astroClientFiles(root) {
649
1244
  const files = new Set();