@runtime-inspector/client-mcp 0.0.0-stage → 0.1.0-alpha.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Giulio Amato
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.
package/README.md CHANGED
@@ -1,3 +1,44 @@
1
- # Temporary Holding Version
1
+ # @runtime-inspector/client-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
+ An [MCP](https://modelcontextprotocol.io/) server that lets a compatible AI client read and tune controls exposed by a running [Runtime Inspector](https://github.com/AmatoGiulio/runtime-inspector) app.
4
+
5
+ ## Install and run
6
+
7
+ Start `npx runtime-inspector dev` from the app root (after installing the CLI and SDK as described in [Getting started](https://github.com/AmatoGiulio/runtime-inspector/blob/main/docs/getting-started.md)). Then configure your MCP client to launch:
8
+
9
+ ~~~bash
10
+ npx -y @runtime-inspector/client-mcp@alpha
11
+ ~~~
12
+
13
+ For clients that use a JSON `mcpServers` map, an example entry is:
14
+
15
+ ~~~json
16
+ {
17
+ "mcpServers": {
18
+ "runtime-inspector": {
19
+ "command": "npx",
20
+ "args": ["-y", "@runtime-inspector/client-mcp@alpha"]
21
+ }
22
+ }
23
+ }
24
+ ~~~
25
+
26
+ Your MCP client's actual configuration format may differ. On startup the server uses the CLI session file at `~/.runtime-inspector/session.json` to locate the broker. Explicit `RI_BROKER_URL` and `RI_TOKEN` environment variables override automatic discovery.
27
+
28
+ ## Available tools
29
+
30
+ - `get_schema` — inspect exposed controls and current values.
31
+ - `set_control_value` — update one control.
32
+ - `batch_set` — validate and apply multiple values.
33
+ - `trigger` — run an exposed action.
34
+ - `list_scenes` and `open_scene` — inspect and replay available motion scenes.
35
+
36
+ Use `get_schema` before editing values. This client tunes the running app; **Apply to code** is handled by the web panel, not by an MCP tool.
37
+
38
+ Only connect trusted MCP clients to your local development broker. Session tokens grant control of the running app.
39
+
40
+ ## Links
41
+
42
+ [Repository](https://github.com/AmatoGiulio/runtime-inspector) · [Getting started](https://github.com/AmatoGiulio/runtime-inspector/blob/main/docs/getting-started.md) · [Issues](https://github.com/AmatoGiulio/runtime-inspector/issues)
43
+
44
+ **Status:** alpha, APIs may change. MIT license.
@@ -0,0 +1,51 @@
1
+ #!/usr/bin/env node
2
+ import { PanelSchema, SceneStatus, RuntimeAnimationStarted } from '@runtime-inspector/protocol';
3
+
4
+ interface BrokerClientOptions {
5
+ url: string;
6
+ token?: string;
7
+ clientId?: string;
8
+ }
9
+ /** A scene published in the reserved `scenes` schema (RFC 0006). Same shape as panel-core's SceneEntry. */
10
+ interface SceneEntry {
11
+ id: string;
12
+ title: string;
13
+ group: string;
14
+ description?: string;
15
+ url?: string;
16
+ active: boolean;
17
+ reachable: boolean;
18
+ stale: boolean;
19
+ }
20
+ interface BrokerClient {
21
+ connect(): Promise<void>;
22
+ /** True while the broker socket is open. */
23
+ isConnected(): boolean;
24
+ getSchemas(): PanelSchema[];
25
+ /**
26
+ * Resolves once at least one schema is cached, or after `timeoutMs`. The broker replays
27
+ * cached schemas right after `handshake.accept`, but they can arrive after `connect()`
28
+ * resolves; a first read without this wait can wrongly report "no schema".
29
+ */
30
+ waitForSchemas(timeoutMs: number): Promise<void>;
31
+ getValues(schemaId: string): Record<string, unknown>;
32
+ isStale(schemaId: string): boolean;
33
+ setValue(schemaId: string, controlId: string, value: unknown): void;
34
+ batchSet(schemaId: string, values: Record<string, unknown>): void;
35
+ fireTrigger(schemaId: string, controlId: string): void;
36
+ /** Scenes from the cached `scenes` schema, in group/control order. */
37
+ getScenes(): SceneEntry[];
38
+ /** Latest `scene.status` received for a scene, if any. */
39
+ getSceneStatus(sceneId: string): SceneStatus | undefined;
40
+ /** Subscribes to every incoming `scene.status`. Returns an unsubscribe function. */
41
+ onSceneStatus(listener: (status: SceneStatus) => void): () => void;
42
+ /**
43
+ * Buffered `animation.started` messages whose call time
44
+ * (`startedAtRuntimeMs - (startDelayMs ?? 0)`) is >= callTimeMs - 1.
45
+ */
46
+ getAnimationsSince(callTimeMs: number): RuntimeAnimationStarted[];
47
+ close(): void;
48
+ }
49
+ declare function createBrokerClient(options: BrokerClientOptions): BrokerClient;
50
+
51
+ export { type BrokerClient, type BrokerClientOptions, type SceneEntry, createBrokerClient };
package/dist/index.js ADDED
@@ -0,0 +1,644 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/index.ts
4
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import { z } from "zod";
7
+ import {
8
+ SCENES_SCHEMA_ID as SCENES_SCHEMA_ID2,
9
+ isValueControl as isValueControl2
10
+ } from "@runtime-inspector/protocol";
11
+
12
+ // src/broker-client.ts
13
+ import { randomUUID } from "crypto";
14
+ import { WebSocket } from "ws";
15
+ import {
16
+ RIP_VERSION,
17
+ SCENES_SCHEMA_ID,
18
+ isValueControl,
19
+ safeParseRIPMessage,
20
+ validateControlValue
21
+ } from "@runtime-inspector/protocol";
22
+ var HANDSHAKE_TIMEOUT_MS = 5e3;
23
+ var ANIMATION_BUFFER_LIMIT = 300;
24
+ function createBrokerClient(options) {
25
+ const clientId = options.clientId ?? `client-mcp-${randomUUID()}`;
26
+ const schemas = /* @__PURE__ */ new Map();
27
+ const values = /* @__PURE__ */ new Map();
28
+ const staleSchemaIds = /* @__PURE__ */ new Set();
29
+ const sceneStatuses = /* @__PURE__ */ new Map();
30
+ const sceneListeners = /* @__PURE__ */ new Set();
31
+ const animations = [];
32
+ const schemaWaiters = /* @__PURE__ */ new Set();
33
+ let socket;
34
+ function connect() {
35
+ return new Promise((resolve, reject) => {
36
+ const ws = new WebSocket(options.url);
37
+ socket = ws;
38
+ let settled = false;
39
+ const timer = setTimeout(() => {
40
+ if (settled) return;
41
+ settled = true;
42
+ ws.close();
43
+ reject(new Error(`Timed out connecting to broker at ${options.url}.`));
44
+ }, HANDSHAKE_TIMEOUT_MS);
45
+ ws.on("open", () => {
46
+ ws.send(
47
+ JSON.stringify({
48
+ type: "handshake.hello",
49
+ protocolVersion: RIP_VERSION,
50
+ role: "panel",
51
+ clientId,
52
+ clientName: "Runtime Inspector MCP Client",
53
+ token: options.token
54
+ })
55
+ );
56
+ });
57
+ ws.on("message", (data) => {
58
+ const message = safeParseRIPMessage(data);
59
+ if (!message) return;
60
+ if (!settled) {
61
+ if (message.type === "handshake.accept") {
62
+ settled = true;
63
+ clearTimeout(timer);
64
+ resolve();
65
+ } else if (message.type === "error") {
66
+ settled = true;
67
+ clearTimeout(timer);
68
+ reject(new Error(`${message.code}: ${message.message}`));
69
+ ws.close();
70
+ return;
71
+ }
72
+ }
73
+ handleMessage(message);
74
+ });
75
+ ws.on("error", (error) => {
76
+ if (settled) return;
77
+ settled = true;
78
+ clearTimeout(timer);
79
+ reject(error instanceof Error ? error : new Error(String(error)));
80
+ });
81
+ ws.on("close", () => {
82
+ if (settled) return;
83
+ settled = true;
84
+ clearTimeout(timer);
85
+ reject(new Error("Broker closed the connection before accepting the handshake."));
86
+ });
87
+ });
88
+ }
89
+ function handleMessage(message) {
90
+ if (message.type === "scene.status") {
91
+ sceneStatuses.set(message.sceneId, message);
92
+ for (const listener of Array.from(sceneListeners)) {
93
+ listener(message);
94
+ }
95
+ return;
96
+ }
97
+ if (message.type === "animation.started") {
98
+ animations.push(message);
99
+ if (animations.length > ANIMATION_BUFFER_LIMIT) {
100
+ animations.splice(0, animations.length - ANIMATION_BUFFER_LIMIT);
101
+ }
102
+ return;
103
+ }
104
+ if (message.type === "schema.publish") {
105
+ schemas.set(message.schema.id, message.schema);
106
+ values.set(message.schema.id, collectInitialValues(message.schema));
107
+ staleSchemaIds.delete(message.schema.id);
108
+ for (const wake of Array.from(schemaWaiters)) wake();
109
+ return;
110
+ }
111
+ if (message.type === "schema.dispose") {
112
+ schemas.delete(message.schemaId);
113
+ values.delete(message.schemaId);
114
+ staleSchemaIds.delete(message.schemaId);
115
+ return;
116
+ }
117
+ if (message.type === "runtime.status" && message.schemaId) {
118
+ if (message.online) {
119
+ staleSchemaIds.delete(message.schemaId);
120
+ } else if (schemas.has(message.schemaId)) {
121
+ staleSchemaIds.add(message.schemaId);
122
+ }
123
+ return;
124
+ }
125
+ if (message.type === "control.patch") {
126
+ const schemaValues = values.get(message.schemaId);
127
+ if (!schemaValues) return;
128
+ schemaValues[message.controlId] = message.value;
129
+ return;
130
+ }
131
+ if (message.type === "control.commit") {
132
+ const schemaValues = values.get(message.schemaId);
133
+ if (!schemaValues) return;
134
+ schemaValues[message.controlId] = message.value;
135
+ return;
136
+ }
137
+ if (message.type === "control.batchPatch") {
138
+ const schemaValues = values.get(message.schemaId);
139
+ if (!schemaValues) return;
140
+ for (const patch of message.patches) {
141
+ schemaValues[patch.controlId] = patch.value;
142
+ }
143
+ }
144
+ }
145
+ function getSchemas() {
146
+ return Array.from(schemas.values());
147
+ }
148
+ function getValues(schemaId) {
149
+ return { ...values.get(schemaId) ?? {} };
150
+ }
151
+ function isStale(schemaId) {
152
+ return staleSchemaIds.has(schemaId);
153
+ }
154
+ function assertSchemaLive(schemaId) {
155
+ if (staleSchemaIds.has(schemaId)) {
156
+ throw new Error(`Schema "${schemaId}" is stale because its runtime disconnected. Wait for it to reconnect before sending controls.`);
157
+ }
158
+ }
159
+ function findControl(schemaId, controlId) {
160
+ const schema = schemas.get(schemaId);
161
+ if (!schema) {
162
+ throw new Error(`Unknown schema "${schemaId}". Call get_schema first.`);
163
+ }
164
+ const control = schema.groups.flatMap((group) => group.controls).find((candidate) => candidate.id === controlId);
165
+ if (!control) {
166
+ throw new Error(`Unknown control "${controlId}" in schema "${schemaId}".`);
167
+ }
168
+ return control;
169
+ }
170
+ function send(message) {
171
+ if (!socket || socket.readyState !== WebSocket.OPEN) {
172
+ throw new Error("Not connected to broker. Call connect() first.");
173
+ }
174
+ socket.send(JSON.stringify(message));
175
+ }
176
+ function setValue(schemaId, controlId, value) {
177
+ const control = findControl(schemaId, controlId);
178
+ assertSchemaLive(schemaId);
179
+ const result = validateControlValue(control, value);
180
+ if (!result.ok) {
181
+ throw new Error(
182
+ `Invalid value for control "${controlId}": ${result.code}: ${result.message}`
183
+ );
184
+ }
185
+ send({
186
+ type: "control.commit",
187
+ schemaId,
188
+ controlId,
189
+ value,
190
+ source: "panel",
191
+ timestamp: Date.now()
192
+ });
193
+ if (isValueControl(control)) {
194
+ const schemaValues = values.get(schemaId) ?? {};
195
+ schemaValues[controlId] = value;
196
+ values.set(schemaId, schemaValues);
197
+ }
198
+ }
199
+ function batchSet(schemaId, patchValues) {
200
+ assertSchemaLive(schemaId);
201
+ const entries = Object.entries(patchValues);
202
+ for (const [controlId, value] of entries) {
203
+ const control = findControl(schemaId, controlId);
204
+ const result = validateControlValue(control, value);
205
+ if (!result.ok) {
206
+ throw new Error(
207
+ `Invalid value for control "${controlId}": ${result.code}: ${result.message}`
208
+ );
209
+ }
210
+ }
211
+ const timestamp = Date.now();
212
+ send({
213
+ type: "control.batchPatch",
214
+ schemaId,
215
+ source: "panel",
216
+ timestamp,
217
+ patches: entries.map(([controlId, value]) => ({ controlId, value })),
218
+ committed: true
219
+ });
220
+ const schemaValues = values.get(schemaId) ?? {};
221
+ for (const [controlId, value] of entries) {
222
+ schemaValues[controlId] = value;
223
+ }
224
+ values.set(schemaId, schemaValues);
225
+ }
226
+ function fireTrigger(schemaId, controlId) {
227
+ const control = findControl(schemaId, controlId);
228
+ assertSchemaLive(schemaId);
229
+ if (control.kind !== "trigger") {
230
+ throw new Error(`Control "${controlId}" is not a trigger (kind "${control.kind}").`);
231
+ }
232
+ send({
233
+ type: "control.trigger",
234
+ schemaId,
235
+ controlId,
236
+ source: "panel",
237
+ timestamp: Date.now()
238
+ });
239
+ }
240
+ function getScenes() {
241
+ const schema = schemas.get(SCENES_SCHEMA_ID);
242
+ if (!schema) return [];
243
+ const stale = staleSchemaIds.has(SCENES_SCHEMA_ID);
244
+ const entries = [];
245
+ for (const group of schema.groups) {
246
+ for (const control of group.controls) {
247
+ if (control.kind !== "trigger" || !control.scene) continue;
248
+ entries.push({
249
+ id: control.id,
250
+ title: control.label,
251
+ group: group.label,
252
+ ...control.description !== void 0 ? { description: control.description } : {},
253
+ ...control.scene.url !== void 0 ? { url: control.scene.url } : {},
254
+ active: control.scene.active,
255
+ reachable: control.scene.reachable,
256
+ stale
257
+ });
258
+ }
259
+ }
260
+ return entries;
261
+ }
262
+ function getSceneStatus(sceneId) {
263
+ return sceneStatuses.get(sceneId);
264
+ }
265
+ function onSceneStatus(listener) {
266
+ sceneListeners.add(listener);
267
+ return () => {
268
+ sceneListeners.delete(listener);
269
+ };
270
+ }
271
+ function getAnimationsSince(callTimeMs) {
272
+ return animations.filter(
273
+ (animation) => animation.startedAtRuntimeMs - (animation.startDelayMs ?? 0) >= callTimeMs - 1
274
+ );
275
+ }
276
+ function isConnected() {
277
+ return socket?.readyState === WebSocket.OPEN;
278
+ }
279
+ function close() {
280
+ socket?.close();
281
+ socket = void 0;
282
+ }
283
+ function waitForSchemas(timeoutMs) {
284
+ if (schemas.size > 0) return Promise.resolve();
285
+ return new Promise((resolve) => {
286
+ const done = () => {
287
+ clearTimeout(timer);
288
+ schemaWaiters.delete(done);
289
+ resolve();
290
+ };
291
+ const timer = setTimeout(done, timeoutMs);
292
+ schemaWaiters.add(done);
293
+ });
294
+ }
295
+ return {
296
+ connect,
297
+ isConnected,
298
+ getSchemas,
299
+ waitForSchemas,
300
+ getValues,
301
+ isStale,
302
+ setValue,
303
+ batchSet,
304
+ fireTrigger,
305
+ getScenes,
306
+ getSceneStatus,
307
+ onSceneStatus,
308
+ getAnimationsSince,
309
+ close
310
+ };
311
+ }
312
+ function collectInitialValues(schema) {
313
+ return Object.fromEntries(
314
+ schema.groups.flatMap(
315
+ (group) => group.controls.filter(isValueControl).map((control) => [control.id, control.value ?? control.defaultValue])
316
+ )
317
+ );
318
+ }
319
+
320
+ // src/session-file.ts
321
+ import { readFileSync } from "fs";
322
+ import { homedir } from "os";
323
+ import { join } from "path";
324
+ var DEFAULT_BROKER_URL = "ws://127.0.0.1:4577";
325
+ var NO_BROKER_MESSAGE = "No Runtime Inspector session found. Start `runtime-inspector dev` (it writes ~/.runtime-inspector/session.json) or set RI_TOKEN/RI_BROKER_URL.";
326
+ function sessionFilePath(env = process.env) {
327
+ return join(env.RUNTIME_INSPECTOR_HOME ?? join(homedir(), ".runtime-inspector"), "session.json");
328
+ }
329
+ function readSessionFile(env = process.env) {
330
+ let value;
331
+ try {
332
+ value = JSON.parse(readFileSync(sessionFilePath(env), "utf-8"));
333
+ } catch {
334
+ return void 0;
335
+ }
336
+ if (!value || typeof value !== "object") return void 0;
337
+ const session = value;
338
+ if (session.version !== 1 || typeof session.brokerUrl !== "string" || typeof session.token !== "string" || typeof session.panelUrl !== "string" || typeof session.workspaceRoot !== "string" || typeof session.pid !== "number" || !Number.isInteger(session.pid) || session.pid <= 0 || typeof session.startedAt !== "string" || session.lanBrokerUrl !== void 0 && typeof session.lanBrokerUrl !== "string") {
339
+ return void 0;
340
+ }
341
+ return isProcessAlive(session.pid) ? session : void 0;
342
+ }
343
+ function resolveBrokerTarget(env = process.env) {
344
+ if (env.RI_BROKER_URL !== void 0 || env.RI_TOKEN !== void 0) {
345
+ return { url: env.RI_BROKER_URL ?? DEFAULT_BROKER_URL, token: env.RI_TOKEN, source: "env" };
346
+ }
347
+ const session = readSessionFile(env);
348
+ if (session) {
349
+ return { url: session.brokerUrl, token: session.token, source: "session" };
350
+ }
351
+ throw new Error(NO_BROKER_MESSAGE);
352
+ }
353
+ function isProcessAlive(pid) {
354
+ try {
355
+ process.kill(pid, 0);
356
+ return true;
357
+ } catch (error) {
358
+ return error.code === "EPERM";
359
+ }
360
+ }
361
+
362
+ // src/index.ts
363
+ var SCHEMA_REPLAY_WAIT_MS = 500;
364
+ var client;
365
+ var connecting;
366
+ async function getConnectedClient() {
367
+ if (client && client.isConnected()) return client;
368
+ if (client) {
369
+ client.close();
370
+ client = void 0;
371
+ }
372
+ if (!connecting) {
373
+ const target = resolveBrokerTarget();
374
+ const created = createBrokerClient({ url: target.url, token: target.token });
375
+ connecting = created.connect().then(() => created.waitForSchemas(SCHEMA_REPLAY_WAIT_MS)).then(() => {
376
+ client = created;
377
+ return created;
378
+ }).finally(() => {
379
+ connecting = void 0;
380
+ });
381
+ }
382
+ return connecting;
383
+ }
384
+ function resolveSchemaId(activeClient, schemaId) {
385
+ const schemas = activeClient.getSchemas();
386
+ if (schemaId) return schemaId;
387
+ if (schemas.length === 1) return schemas[0].id;
388
+ if (schemas.length === 0) {
389
+ throw new Error("No runtime schema has been published yet. Start the app's runtime and try again.");
390
+ }
391
+ throw new Error(
392
+ `schemaId is required: multiple schemas are cached (${schemas.map((schema) => schema.id).join(", ")}).`
393
+ );
394
+ }
395
+ function schemaWithValues(activeClient, schema) {
396
+ const values = activeClient.getValues(schema.id);
397
+ return {
398
+ ...schema,
399
+ stale: activeClient.isStale(schema.id),
400
+ groups: schema.groups.map((group) => ({
401
+ ...group,
402
+ controls: group.controls.map((control) => ({
403
+ ...control,
404
+ currentValue: isValueControl2(control) ? values[control.id] ?? control.defaultValue : void 0
405
+ }))
406
+ }))
407
+ };
408
+ }
409
+ var server = new McpServer({
410
+ name: "runtime-inspector-mcp",
411
+ version: "0.1.0"
412
+ });
413
+ server.registerTool(
414
+ "get_schema",
415
+ {
416
+ title: "Get Runtime Inspector schema",
417
+ description: "Read the control schema(s) published by the running app's runtime, merged with current values. Always call this first before tuning: it tells you which controls (sliders, toggles, colors, bezier curves, springs, triggers) are available, their ids, ranges, and current values. Returns a message if no runtime has published a schema yet.",
418
+ inputSchema: {}
419
+ },
420
+ async () => {
421
+ try {
422
+ const activeClient = await getConnectedClient();
423
+ const schemas = activeClient.getSchemas();
424
+ if (schemas.length === 0) {
425
+ return {
426
+ content: [
427
+ {
428
+ type: "text",
429
+ text: "No runtime schema has been published yet. Start the app's runtime and try again."
430
+ }
431
+ ]
432
+ };
433
+ }
434
+ const payload = schemas.map((schema) => schemaWithValues(activeClient, schema));
435
+ return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
436
+ } catch (error) {
437
+ return errorResult(error);
438
+ }
439
+ }
440
+ );
441
+ server.registerTool(
442
+ "set_control_value",
443
+ {
444
+ title: "Set a control value",
445
+ description: "Set a single control's value on the running app (e.g. tweak a spring's damping, a slider, a color). Call get_schema first to see valid control ids and ranges. After setting values, consider calling trigger on a replay control to observe the effect. schemaId is optional if exactly one schema is cached.",
446
+ inputSchema: {
447
+ schemaId: z.string().optional().describe("Schema id. Optional if only one schema is cached."),
448
+ controlId: z.string().describe("The control id to update."),
449
+ value: z.unknown().describe("The new value, matching the control's kind (number, boolean, string, etc).")
450
+ }
451
+ },
452
+ async ({ schemaId, controlId, value }) => {
453
+ try {
454
+ const activeClient = await getConnectedClient();
455
+ const resolvedSchemaId = resolveSchemaId(activeClient, schemaId);
456
+ activeClient.setValue(resolvedSchemaId, controlId, value);
457
+ return {
458
+ content: [
459
+ {
460
+ type: "text",
461
+ text: `Set ${controlId} = ${JSON.stringify(value)} on schema "${resolvedSchemaId}".`
462
+ }
463
+ ]
464
+ };
465
+ } catch (error) {
466
+ return errorResult(error);
467
+ }
468
+ }
469
+ );
470
+ server.registerTool(
471
+ "batch_set",
472
+ {
473
+ title: "Batch set control values",
474
+ description: "Set multiple control values at once, atomically (all values are validated before anything is sent). Useful for applying a whole tuned preset in one step before firing a replay trigger to observe it.",
475
+ inputSchema: {
476
+ schemaId: z.string().optional().describe("Schema id. Optional if only one schema is cached."),
477
+ values: z.record(z.unknown()).describe("Map of controlId to new value.")
478
+ }
479
+ },
480
+ async ({ schemaId, values }) => {
481
+ try {
482
+ const activeClient = await getConnectedClient();
483
+ const resolvedSchemaId = resolveSchemaId(activeClient, schemaId);
484
+ activeClient.batchSet(resolvedSchemaId, values);
485
+ return {
486
+ content: [
487
+ {
488
+ type: "text",
489
+ text: `Applied ${Object.keys(values).length} value(s) on schema "${resolvedSchemaId}": ${JSON.stringify(values)}.`
490
+ }
491
+ ]
492
+ };
493
+ } catch (error) {
494
+ return errorResult(error);
495
+ }
496
+ }
497
+ );
498
+ server.registerTool(
499
+ "trigger",
500
+ {
501
+ title: "Fire a trigger control",
502
+ description: 'Fire a trigger control (e.g. "replay transition") to re-run an animation on the device after changing values, so you can observe the effect of your tuning without touching the app. Scenes are triggers in the "scenes" schema, but prefer open_scene: it navigates, waits for the motion to play and reports what ran.',
503
+ inputSchema: {
504
+ schemaId: z.string().optional().describe("Schema id. Optional if only one schema is cached."),
505
+ controlId: z.string().describe("The trigger control id to fire.")
506
+ }
507
+ },
508
+ async ({ schemaId, controlId }) => {
509
+ try {
510
+ const activeClient = await getConnectedClient();
511
+ const resolvedSchemaId = resolveSchemaId(activeClient, schemaId);
512
+ activeClient.fireTrigger(resolvedSchemaId, controlId);
513
+ return {
514
+ content: [{ type: "text", text: `Fired trigger "${controlId}" on schema "${resolvedSchemaId}".` }]
515
+ };
516
+ } catch (error) {
517
+ return errorResult(error);
518
+ }
519
+ }
520
+ );
521
+ server.registerTool(
522
+ "list_scenes",
523
+ {
524
+ title: "List motion scenes",
525
+ description: "List the app's motion scenes (named moments such as a product reveal or a sheet opening). Each can be opened with open_scene: the app navigates there and plays the motion.",
526
+ inputSchema: {}
527
+ },
528
+ async () => {
529
+ try {
530
+ const activeClient = await getConnectedClient();
531
+ const scenes = activeClient.getScenes();
532
+ if (scenes.length === 0) {
533
+ return {
534
+ content: [
535
+ {
536
+ type: "text",
537
+ text: "The app publishes no scenes. Declare them with defineScene/useScene in the app's Runtime Inspector SDK and make sure the app is running."
538
+ }
539
+ ]
540
+ };
541
+ }
542
+ const payload = scenes.map((scene) => ({
543
+ id: scene.id,
544
+ title: scene.title,
545
+ group: scene.group,
546
+ ...scene.description !== void 0 ? { description: scene.description } : {},
547
+ url: scene.url,
548
+ active: scene.active,
549
+ reachable: scene.reachable,
550
+ stale: scene.stale
551
+ }));
552
+ return { content: [{ type: "text", text: JSON.stringify(payload, null, 2) }] };
553
+ } catch (error) {
554
+ return errorResult(error);
555
+ }
556
+ }
557
+ );
558
+ var OPEN_SCENE_CAP_MS = 8e3;
559
+ server.registerTool(
560
+ "open_scene",
561
+ {
562
+ title: "Open a motion scene",
563
+ description: "Open a motion scene: the app navigates to it, waits until the screen is mounted and plays the motion. Returns the animations that started in the moment after the scene played (target, kind, start/call time relative to the play, duration, config, the controls that tune them, source). Tune them with set_control_value/batch_set on the referenced controls; committing then re-opening the scene replays it with the new values. Call list_scenes first for valid ids.",
564
+ inputSchema: {
565
+ sceneId: z.string().describe("The scene id from list_scenes."),
566
+ observeMs: z.number().min(0).max(5e3).optional().describe("How long to keep observing animations after the scene plays, in ms. Default 1500.")
567
+ }
568
+ },
569
+ async ({ sceneId, observeMs }) => {
570
+ try {
571
+ const activeClient = await getConnectedClient();
572
+ const scene = activeClient.getScenes().find((entry) => entry.id === sceneId);
573
+ if (!scene) {
574
+ throw new Error(`Unknown scene "${sceneId}". Call list_scenes to see the available scenes.`);
575
+ }
576
+ let resolveOutcome;
577
+ const outcome = new Promise((resolve) => {
578
+ resolveOutcome = resolve;
579
+ });
580
+ let lastPhase;
581
+ const unsubscribe = activeClient.onSceneStatus((status2) => {
582
+ if (status2.sceneId !== sceneId) return;
583
+ lastPhase = status2.phase;
584
+ if (status2.phase === "playing" || status2.phase === "failed") {
585
+ resolveOutcome(status2);
586
+ }
587
+ });
588
+ const cap = setTimeout(() => resolveOutcome(void 0), OPEN_SCENE_CAP_MS);
589
+ let status;
590
+ try {
591
+ activeClient.fireTrigger(SCENES_SCHEMA_ID2, sceneId);
592
+ status = await outcome;
593
+ } finally {
594
+ clearTimeout(cap);
595
+ unsubscribe();
596
+ }
597
+ if (!status) {
598
+ return errorResult(
599
+ new Error(
600
+ `Scene "${sceneId}" did not start playing within ${OPEN_SCENE_CAP_MS} ms` + (lastPhase ? ` (last phase: ${lastPhase}).` : " (the app sent no status; is it running a Runtime Inspector version with scenes?).")
601
+ )
602
+ );
603
+ }
604
+ if (status.phase === "failed") {
605
+ return errorResult(new Error(`Scene "${sceneId}" failed: ${status.code}: ${status.reason}`));
606
+ }
607
+ const playedAt = status.atRuntimeMs;
608
+ await new Promise((resolve) => setTimeout(resolve, observeMs ?? 1500));
609
+ const animations = activeClient.getAnimationsSince(playedAt).map((animation) => {
610
+ const callTime = animation.startedAtRuntimeMs - (animation.startDelayMs ?? 0);
611
+ return {
612
+ target: animation.target,
613
+ kind: animation.animationKind,
614
+ startMs: Math.round(animation.startedAtRuntimeMs - playedAt),
615
+ callMs: Math.round(callTime - playedAt),
616
+ durationMs: typeof animation.config.duration === "number" ? animation.config.duration : null,
617
+ config: animation.config,
618
+ parameterControls: animation.parameterControls,
619
+ startControl: animation.startControl,
620
+ source: animation.source ? `${animation.source.file}:${animation.source.line}` : void 0
621
+ };
622
+ }).sort((a, b) => a.startMs - b.startMs);
623
+ return {
624
+ content: [
625
+ {
626
+ type: "text",
627
+ text: JSON.stringify({ scene: sceneId, playedAtRuntimeMs: playedAt, animations }, null, 2)
628
+ }
629
+ ]
630
+ };
631
+ } catch (error) {
632
+ return errorResult(error);
633
+ }
634
+ }
635
+ );
636
+ function errorResult(error) {
637
+ const message = error instanceof Error ? error.message : String(error);
638
+ return { content: [{ type: "text", text: `Error: ${message}` }], isError: true };
639
+ }
640
+ var transport = new StdioServerTransport();
641
+ await server.connect(transport);
642
+ export {
643
+ createBrokerClient
644
+ };
package/package.json CHANGED
@@ -1,6 +1,48 @@
1
1
  {
2
2
  "name": "@runtime-inspector/client-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0-alpha.2",
4
+ "description": "MCP server that lets an AI agent tune a running app through the Runtime Inspector broker.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/AmatoGiulio/runtime-inspector.git",
9
+ "directory": "packages/client-mcp"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "bin": {
15
+ "runtime-inspector-mcp": "./dist/index.js"
16
+ },
17
+ "exports": {
18
+ ".": {
19
+ "types": "./dist/index.d.ts",
20
+ "import": "./dist/index.js"
21
+ }
22
+ },
23
+ "files": [
24
+ "dist"
25
+ ],
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "dependencies": {
30
+ "@modelcontextprotocol/sdk": "^1.32.1",
31
+ "ws": "^8.18.0",
32
+ "zod": "^3.24.1",
33
+ "@runtime-inspector/protocol": "0.1.0-alpha.2"
34
+ },
35
+ "devDependencies": {
36
+ "@types/ws": "^8.5.13",
37
+ "tsup": "^8.3.5",
38
+ "vitest": "^4.1.9",
39
+ "@runtime-inspector/transport-ws": "0.1.0-alpha.2"
40
+ },
41
+ "scripts": {
42
+ "build": "tsup src/index.ts --format esm --dts",
43
+ "test": "vitest run",
44
+ "typecheck": "tsc --noEmit",
45
+ "lint": "tsc --noEmit",
46
+ "clean": "rm -rf dist"
47
+ }
6
48
  }