@logictan/dsh-stitch-designer 0.0.0-stage → 1.0.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.
- package/LICENSE +21 -0
- package/README.md +91 -2
- package/cordis.patch.yml +22 -0
- package/lib/client.js +533 -0
- package/lib/index.js +153 -0
- package/lib/routes.js +250 -0
- package/lib/stitch.js +113 -0
- package/lib/store.js +229 -0
- package/lib/tools.js +165 -0
- package/package.json +71 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-stitch-designer — host half.
|
|
3
|
+
*
|
|
4
|
+
* Google Stitch (AI UI generation) as a first-class part of the harness. It
|
|
5
|
+
* registers the same 15 `mcp__stitch__*` tools the retired `mcp-stitch` patch
|
|
6
|
+
* row used to provide, and serves the preview panel's HTTP API.
|
|
7
|
+
*
|
|
8
|
+
* Three design choices are load-bearing, and each replaces something that was
|
|
9
|
+
* tried and failed elsewhere in this repository:
|
|
10
|
+
*
|
|
11
|
+
* - **The Stitch transport lives here, not in `@deepseek-ai/dsh-mcp-client`.**
|
|
12
|
+
* Stitch's tool schemas are outside the subset `dsh-tools` accepts — 11 of
|
|
13
|
+
* 15 input schemas and 13 of 15 output schemas are rejected by
|
|
14
|
+
* `assertSupportedJsonSchema` — so the bridge has to decide per field what
|
|
15
|
+
* to keep. Owning the transport is also what keeps the API key out of a
|
|
16
|
+
* patch row (see below) and what lets the tools and the panel share one
|
|
17
|
+
* client.
|
|
18
|
+
*
|
|
19
|
+
* - **The API key is a credential, not configuration.** It lives in
|
|
20
|
+
* `$DSH_HOME/.credentials.yaml` under the ref `STITCH_API_KEY`, resolved
|
|
21
|
+
* through `ctx.credentials` on every call. A `role('secret')` Config field
|
|
22
|
+
* would have been the obvious alternative, but it stores the value in the
|
|
23
|
+
* profile's `cordis.patch.yml` as plaintext — which is exactly how the
|
|
24
|
+
* previous generation leaked secrets into config-sync snapshots. As a
|
|
25
|
+
* credential it is still carried by config sync (the `credentialsStatus`
|
|
26
|
+
* section exports refs from the credentials file), and it never appears in a
|
|
27
|
+
* patch row.
|
|
28
|
+
*
|
|
29
|
+
* - **Each half waits for the services it needs; `credentials` is read per
|
|
30
|
+
* call.** `ctx.get(name)` returns only a service whose providing fiber is
|
|
31
|
+
* already ACTIVE, and providers come up asynchronously — `webServer` waits on
|
|
32
|
+
* `webStartup`, so at `apply` time it is still `undefined` even though its
|
|
33
|
+
* row precedes this one in the patch list. Reading it once in `apply`
|
|
34
|
+
* silently dropped the entire panel API. The registrations therefore nest
|
|
35
|
+
* under `ctx.inject` so each waits for its own providers; the tools half
|
|
36
|
+
* additionally waits for `credentials`, because its first `tools/list` needs
|
|
37
|
+
* the key and nothing re-fires that fetch at boot (the initial attempt ran
|
|
38
|
+
* before the credential store was live and failed as "key not configured").
|
|
39
|
+
* The key itself is read at call time, so setting it later still works.
|
|
40
|
+
*
|
|
41
|
+
* @module @logictan/dsh-stitch-designer
|
|
42
|
+
*/
|
|
43
|
+
import { makeRoutes } from './routes.js';
|
|
44
|
+
import { createStitchClient } from './stitch.js';
|
|
45
|
+
import { createToolDefinition, publicToolName } from './tools.js';
|
|
46
|
+
|
|
47
|
+
/** Plugin row id; must equal the row id in `cordis.patch.yml`. */
|
|
48
|
+
export const name = 'stitch-designer';
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Credential reference holding the Stitch API key.
|
|
52
|
+
*
|
|
53
|
+
* The reference grammar is `/^[A-Za-z_][A-Za-z0-9_]*$/`, so a POSIX-shell-style
|
|
54
|
+
* name is required; `STITCH_API_KEY` also matches the convention the other
|
|
55
|
+
* providers in this repository use for their keys.
|
|
56
|
+
*/
|
|
57
|
+
export const API_KEY_REF = 'STITCH_API_KEY';
|
|
58
|
+
|
|
59
|
+
/** Server namespace embedded in every public tool name (`mcp__stitch__*`). */
|
|
60
|
+
export const SERVER_NAME = 'stitch';
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* Register the Stitch tools and the panel API.
|
|
64
|
+
*
|
|
65
|
+
* @param ctx - the plugin context.
|
|
66
|
+
*/
|
|
67
|
+
export function apply(ctx) {
|
|
68
|
+
/**
|
|
69
|
+
* Resolve the Stitch API key at each call.
|
|
70
|
+
*
|
|
71
|
+
* Read per call rather than captured: the credential can be set, replaced or
|
|
72
|
+
* removed from the Plugins page while the process runs, and a captured value
|
|
73
|
+
* would keep signing with a revoked key until the next restart.
|
|
74
|
+
*
|
|
75
|
+
* @returns the key, or `''` when unset.
|
|
76
|
+
*/
|
|
77
|
+
const resolveApiKey = async () => {
|
|
78
|
+
const credentials = ctx.get('credentials');
|
|
79
|
+
if (credentials === undefined) return '';
|
|
80
|
+
const resolved = await credentials.resolve(API_KEY_REF);
|
|
81
|
+
return resolved?.value ?? '';
|
|
82
|
+
};
|
|
83
|
+
|
|
84
|
+
const stitch = createStitchClient({ resolveApiKey });
|
|
85
|
+
|
|
86
|
+
// ---------------------------------------------------------------- tools
|
|
87
|
+
// The upstream descriptors ARE the tool contract — names, descriptions and
|
|
88
|
+
// input schemas all come from Stitch — so registration follows a successful
|
|
89
|
+
// `tools/list` rather than a copy of the list kept in this repository.
|
|
90
|
+
//
|
|
91
|
+
// That fetch needs the API key, which means a freshly installed plugin has
|
|
92
|
+
// no tools until a key exists. The credential-change event is what closes
|
|
93
|
+
// that gap: setting the key in the Plugins page registers the tools in the
|
|
94
|
+
// running process, with no restart. Without it the tools would appear only
|
|
95
|
+
// after the user happened to restart, which reads as "the plugin is broken".
|
|
96
|
+
ctx.inject(['tools', 'credentials'], (toolsCtx) => {
|
|
97
|
+
const tools = toolsCtx.get('tools');
|
|
98
|
+
|
|
99
|
+
toolsCtx.effect(() => {
|
|
100
|
+
let disposed = false;
|
|
101
|
+
let disposers = [];
|
|
102
|
+
|
|
103
|
+
const sync = async () => {
|
|
104
|
+
const listed = await stitch.listTools();
|
|
105
|
+
if (disposed) return;
|
|
106
|
+
const next = listed.map((tool) =>
|
|
107
|
+
createToolDefinition({
|
|
108
|
+
name: publicToolName(SERVER_NAME, tool.name),
|
|
109
|
+
description: tool.description ?? '',
|
|
110
|
+
inputSchema: tool.inputSchema,
|
|
111
|
+
outputSchema: tool.outputSchema,
|
|
112
|
+
call: (args, exec) => stitch.callTool(tool.name, args, exec),
|
|
113
|
+
}),
|
|
114
|
+
);
|
|
115
|
+
for (const dispose of disposers) dispose();
|
|
116
|
+
disposers = next.map((definition) => tools.register(definition));
|
|
117
|
+
toolsCtx.logger.info(`stitch-designer: registered ${disposers.length} mcp__${SERVER_NAME}__* tools`);
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
const report = (error) => {
|
|
121
|
+
if (disposed) return;
|
|
122
|
+
toolsCtx.logger.warn(
|
|
123
|
+
`stitch-designer: the mcp__${SERVER_NAME}__* tools are not registered yet (${error?.message ?? error})`,
|
|
124
|
+
);
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
sync().catch(report);
|
|
128
|
+
const offCredential = toolsCtx.on('credentials/reference-updated', (ref) => {
|
|
129
|
+
if (ref !== API_KEY_REF || disposers.length > 0) return;
|
|
130
|
+
sync().catch(report);
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
return () => {
|
|
134
|
+
disposed = true;
|
|
135
|
+
offCredential();
|
|
136
|
+
for (const dispose of disposers) dispose();
|
|
137
|
+
disposers = [];
|
|
138
|
+
};
|
|
139
|
+
}, 'stitch-designer: Stitch tools');
|
|
140
|
+
});
|
|
141
|
+
|
|
142
|
+
// --------------------------------------------------------------- routes
|
|
143
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
144
|
+
const webServer = webCtx.get('webServer');
|
|
145
|
+
|
|
146
|
+
webCtx.effect(() => {
|
|
147
|
+
const disposers = makeRoutes({ stitch }).map((route) => webServer.register(route));
|
|
148
|
+
return () => {
|
|
149
|
+
for (const dispose of disposers) dispose();
|
|
150
|
+
};
|
|
151
|
+
}, 'stitch-designer: panel routes');
|
|
152
|
+
});
|
|
153
|
+
}
|
package/lib/routes.js
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP routes behind the preview panel.
|
|
3
|
+
*
|
|
4
|
+
* Four routes, and only the four the panel actually calls (the reference
|
|
5
|
+
* plugin's `POST /stitch/api/generate` and `POST /stitch/api/edit` are
|
|
6
|
+
* deliberately not ported: they existed so an agent could drive Stitch over
|
|
7
|
+
* HTTP, and in this plugin the agent calls `mcp__stitch__*` tools directly, so
|
|
8
|
+
* those two routes would have no caller at all).
|
|
9
|
+
*
|
|
10
|
+
* Two of the four are plain file servers over the local cache, and both take
|
|
11
|
+
* their filename from the request path — the only genuinely untrusted input in
|
|
12
|
+
* this plugin. Each therefore validates the segment against a strict
|
|
13
|
+
* character-class pattern before touching the filesystem, so `..` and any other
|
|
14
|
+
* traversal attempt fails as a 404 rather than resolving a path outside
|
|
15
|
+
* `~/.stitch`.
|
|
16
|
+
*
|
|
17
|
+
* @module @logictan/dsh-stitch-designer/routes
|
|
18
|
+
*/
|
|
19
|
+
import { readFile } from 'node:fs/promises';
|
|
20
|
+
import { join } from 'node:path';
|
|
21
|
+
|
|
22
|
+
import {
|
|
23
|
+
HTML_DIR,
|
|
24
|
+
SCREENS_DIR,
|
|
25
|
+
cacheScreenAssets,
|
|
26
|
+
downloadTo,
|
|
27
|
+
knownScreenIds,
|
|
28
|
+
loadState,
|
|
29
|
+
rememberScreenId,
|
|
30
|
+
saveState,
|
|
31
|
+
toPanelScreen,
|
|
32
|
+
} from './store.js';
|
|
33
|
+
|
|
34
|
+
/** Path prefix of the panel's JSON API. */
|
|
35
|
+
export const STATE_API = '/stitch/api/state';
|
|
36
|
+
/** Path prefix of the 1:1 HTML export endpoint. */
|
|
37
|
+
export const HTML_API = '/stitch/api/html';
|
|
38
|
+
/** Path prefix of the cached screenshot files. */
|
|
39
|
+
export const SCREENS_PATH = '/stitch/screens';
|
|
40
|
+
/** Path prefix of the exported HTML files. */
|
|
41
|
+
export const HTML_PATH = '/stitch/html';
|
|
42
|
+
|
|
43
|
+
/** A screen id or file stem: no dots, no slashes, so it cannot escape its directory. */
|
|
44
|
+
const SAFE_ID = /^[A-Za-z0-9_-]+$/;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Write a JSON response.
|
|
48
|
+
*
|
|
49
|
+
* `no-store` matters: the panel polls this while a design is being generated,
|
|
50
|
+
* and a cached response would show a stale project.
|
|
51
|
+
*
|
|
52
|
+
* @param res - the response.
|
|
53
|
+
* @param status - HTTP status.
|
|
54
|
+
* @param value - the JSON body.
|
|
55
|
+
*/
|
|
56
|
+
function json(res, status, value) {
|
|
57
|
+
res.writeHead(status, {
|
|
58
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
59
|
+
'Cache-Control': 'no-store',
|
|
60
|
+
});
|
|
61
|
+
res.end(JSON.stringify(value));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Write a file from the local cache.
|
|
66
|
+
*
|
|
67
|
+
* @param res - the response.
|
|
68
|
+
* @param dir - the cache directory the file must live in.
|
|
69
|
+
* @param file - the validated file name.
|
|
70
|
+
* @param contentType - the response content type.
|
|
71
|
+
*/
|
|
72
|
+
async function serveFile(res, dir, file, contentType) {
|
|
73
|
+
try {
|
|
74
|
+
const body = await readFile(join(dir, file));
|
|
75
|
+
res.writeHead(200, { 'Content-Type': contentType, 'Cache-Control': 'no-store' });
|
|
76
|
+
res.end(body);
|
|
77
|
+
} catch {
|
|
78
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
79
|
+
res.end('not found');
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Extract the last path segment after a prefix. */
|
|
84
|
+
function segmentAfter(url, prefix) {
|
|
85
|
+
const path = String(url ?? '').split('?')[0];
|
|
86
|
+
if (!path.startsWith(`${prefix}/`)) return undefined;
|
|
87
|
+
return path.slice(prefix.length + 1);
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/**
|
|
91
|
+
* Build the plugin's routes.
|
|
92
|
+
*
|
|
93
|
+
* @param options - the Stitch client.
|
|
94
|
+
* @returns the route list.
|
|
95
|
+
*/
|
|
96
|
+
export function makeRoutes(options) {
|
|
97
|
+
const { stitch } = options;
|
|
98
|
+
|
|
99
|
+
/** List every project the account can see, flattened for the picker. */
|
|
100
|
+
const listProjects = async () => {
|
|
101
|
+
const result = await stitch.callTool('list_projects', {}, undefined);
|
|
102
|
+
const projects = result?.structuredContent?.projects;
|
|
103
|
+
return Array.isArray(projects) ? projects : [];
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
/** List one project's screens. */
|
|
107
|
+
const listScreens = async (projectId) => {
|
|
108
|
+
const result = await stitch.callTool('list_screens', { projectId }, undefined);
|
|
109
|
+
const screens = result?.structuredContent?.screens;
|
|
110
|
+
return Array.isArray(screens) ? screens : [];
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
/** Fetch one screen directly, which works before the index catches up. */
|
|
114
|
+
const getScreen = async (projectId, screenId) => {
|
|
115
|
+
const result = await stitch.callTool('get_screen', { name: `projects/${projectId}/screens/${screenId}` }, undefined);
|
|
116
|
+
return result?.structuredContent?.screen ?? result?.structuredContent;
|
|
117
|
+
};
|
|
118
|
+
|
|
119
|
+
return [
|
|
120
|
+
// ------------------------------------------------- state (prefix)
|
|
121
|
+
{
|
|
122
|
+
kind: 'prefix',
|
|
123
|
+
path: STATE_API,
|
|
124
|
+
handler: async (req, res) => {
|
|
125
|
+
try {
|
|
126
|
+
const url = new URL(String(req.url ?? ''), 'http://localhost');
|
|
127
|
+
const wanted = url.searchParams.get('projectId') ?? '';
|
|
128
|
+
|
|
129
|
+
const projects = (await listProjects().catch(() => []))
|
|
130
|
+
.map((project) => ({
|
|
131
|
+
id: String(project?.name ?? '').split('/').pop(),
|
|
132
|
+
name: project?.name ?? '',
|
|
133
|
+
title: project?.title ?? '',
|
|
134
|
+
deviceType: project?.deviceType ?? '',
|
|
135
|
+
updateTime: project?.updateTime ?? '',
|
|
136
|
+
}))
|
|
137
|
+
.filter((project) => project.id !== '');
|
|
138
|
+
|
|
139
|
+
const state = await loadState();
|
|
140
|
+
const targetId = wanted || state.projectId || projects[0]?.id || '';
|
|
141
|
+
|
|
142
|
+
const seen = new Set();
|
|
143
|
+
const items = [];
|
|
144
|
+
const adopt = async (screen) => {
|
|
145
|
+
const row = toPanelScreen(screen);
|
|
146
|
+
if (row === undefined || seen.has(row.id)) return;
|
|
147
|
+
seen.add(row.id);
|
|
148
|
+
await rememberScreenId(targetId, row.id);
|
|
149
|
+
await cacheScreenAssets(screen);
|
|
150
|
+
items.push(row);
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
for (const screen of await listScreens(targetId).catch(() => [])) await adopt(screen);
|
|
154
|
+
|
|
155
|
+
// `list_screens` lags generation by up to a couple of minutes, so any
|
|
156
|
+
// id this machine has already seen is re-fetched directly. Without
|
|
157
|
+
// this the panel shows an empty project right after a design lands.
|
|
158
|
+
const fallbackIds = knownScreenIds(state, targetId);
|
|
159
|
+
if (state.lastScreenId && !fallbackIds.includes(state.lastScreenId)) fallbackIds.unshift(state.lastScreenId);
|
|
160
|
+
for (const screenId of fallbackIds) {
|
|
161
|
+
if (seen.has(screenId) || !SAFE_ID.test(screenId)) continue;
|
|
162
|
+
await getScreen(targetId, screenId)
|
|
163
|
+
.then((screen) => adopt(screen))
|
|
164
|
+
.catch(() => {});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
await saveState({ projectId: targetId });
|
|
168
|
+
const target = projects.find((project) => project.id === targetId);
|
|
169
|
+
json(res, 200, {
|
|
170
|
+
ok: true,
|
|
171
|
+
projectId: targetId,
|
|
172
|
+
projectTitle: target?.title ?? '',
|
|
173
|
+
lastScreenId: state.lastScreenId ?? '',
|
|
174
|
+
projects,
|
|
175
|
+
screens: items,
|
|
176
|
+
});
|
|
177
|
+
} catch (error) {
|
|
178
|
+
json(res, 500, { ok: false, error: String(error?.message ?? error) });
|
|
179
|
+
}
|
|
180
|
+
},
|
|
181
|
+
},
|
|
182
|
+
|
|
183
|
+
// ------------------------------------------------- HTML export (prefix)
|
|
184
|
+
{
|
|
185
|
+
kind: 'prefix',
|
|
186
|
+
path: HTML_API,
|
|
187
|
+
handler: async (req, res) => {
|
|
188
|
+
try {
|
|
189
|
+
const screenId = segmentAfter(req.url, HTML_API);
|
|
190
|
+
if (screenId === undefined || !SAFE_ID.test(screenId)) {
|
|
191
|
+
json(res, 404, { ok: false, error: 'screen 不存在' });
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
// The panel can ask for a screen from any project, so the owning
|
|
195
|
+
// project is resolved from the state and then from the project list
|
|
196
|
+
// rather than assumed to be the currently selected one.
|
|
197
|
+
const state = await loadState();
|
|
198
|
+
const candidates = [state.projectId, ...(await listProjects().catch(() => [])).map((p) => String(p?.name ?? '').split('/').pop())];
|
|
199
|
+
let screen;
|
|
200
|
+
for (const projectId of candidates) {
|
|
201
|
+
if (!projectId) continue;
|
|
202
|
+
screen = await getScreen(projectId, screenId).catch(() => undefined);
|
|
203
|
+
if (screen?.htmlCode?.downloadUrl) break;
|
|
204
|
+
screen = undefined;
|
|
205
|
+
}
|
|
206
|
+
if (screen?.htmlCode?.downloadUrl === undefined) {
|
|
207
|
+
json(res, 404, { ok: false, error: 'screen 不存在' });
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
await downloadTo(screen.htmlCode.downloadUrl, join(HTML_DIR, `${screenId}.html`));
|
|
211
|
+
json(res, 200, { ok: true, html: `${HTML_PATH}/${screenId}.html` });
|
|
212
|
+
} catch (error) {
|
|
213
|
+
json(res, 500, { ok: false, error: String(error?.message ?? error) });
|
|
214
|
+
}
|
|
215
|
+
},
|
|
216
|
+
},
|
|
217
|
+
|
|
218
|
+
// ------------------------------------------------- screenshots (prefix)
|
|
219
|
+
{
|
|
220
|
+
kind: 'prefix',
|
|
221
|
+
path: SCREENS_PATH,
|
|
222
|
+
handler: async (req, res) => {
|
|
223
|
+
const file = segmentAfter(req.url, SCREENS_PATH);
|
|
224
|
+
const match = /^([A-Za-z0-9_-]+)\.png$/.exec(file ?? '');
|
|
225
|
+
if (match === null) {
|
|
226
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
227
|
+
res.end('not found');
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
await serveFile(res, SCREENS_DIR, `${match[1]}.png`, 'image/png');
|
|
231
|
+
},
|
|
232
|
+
},
|
|
233
|
+
|
|
234
|
+
// ------------------------------------------------- exported HTML (prefix)
|
|
235
|
+
{
|
|
236
|
+
kind: 'prefix',
|
|
237
|
+
path: HTML_PATH,
|
|
238
|
+
handler: async (req, res) => {
|
|
239
|
+
const file = segmentAfter(req.url, HTML_PATH);
|
|
240
|
+
const match = /^([A-Za-z0-9_-]+)\.html$/.exec(file ?? '');
|
|
241
|
+
if (match === null) {
|
|
242
|
+
res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
|
|
243
|
+
res.end('not found');
|
|
244
|
+
return;
|
|
245
|
+
}
|
|
246
|
+
await serveFile(res, HTML_DIR, `${match[1]}.html`, 'text/html; charset=utf-8');
|
|
247
|
+
},
|
|
248
|
+
},
|
|
249
|
+
];
|
|
250
|
+
}
|
package/lib/stitch.js
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Transport to Google Stitch's MCP endpoint.
|
|
3
|
+
*
|
|
4
|
+
* Stitch speaks stateless Streamable HTTP JSON-RPC: every request carries its
|
|
5
|
+
* own `X-Goog-Api-Key`, no session id is issued or echoed, and the response is
|
|
6
|
+
* always `application/json` — never an SSE stream (measured 2026-10-08 for
|
|
7
|
+
* `initialize`, `tools/list` and `tools/call`). A plain `fetch` is therefore
|
|
8
|
+
* the entire client; there is no handshake to maintain and no session to
|
|
9
|
+
* resume, which is also why `tools/list` works without a preceding
|
|
10
|
+
* `initialize`.
|
|
11
|
+
*
|
|
12
|
+
* @module @logictan/dsh-stitch-designer/stitch
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** Stitch's MCP endpoint. */
|
|
16
|
+
export const MCP_URL = 'https://stitch.googleapis.com/mcp';
|
|
17
|
+
|
|
18
|
+
/** Default per-call budget: `generate_screen_from_text` is long-running. */
|
|
19
|
+
export const DEFAULT_TOOL_CALL_TIMEOUT_MS = 180_000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* One JSON-RPC round trip.
|
|
23
|
+
*
|
|
24
|
+
* @param options - endpoint, API key, method, params, timeout and abort signal.
|
|
25
|
+
* @returns the JSON-RPC envelope.
|
|
26
|
+
* @throws when the HTTP request fails or the response is not a JSON-RPC envelope.
|
|
27
|
+
*/
|
|
28
|
+
async function rpc(options) {
|
|
29
|
+
const { url, apiKey, method, params, timeoutMs, signal } = options;
|
|
30
|
+
const response = await fetch(url, {
|
|
31
|
+
method: 'POST',
|
|
32
|
+
headers: {
|
|
33
|
+
'X-Goog-Api-Key': apiKey,
|
|
34
|
+
'Content-Type': 'application/json',
|
|
35
|
+
Accept: 'application/json, text/event-stream',
|
|
36
|
+
},
|
|
37
|
+
body: JSON.stringify({ jsonrpc: '2.0', id: Date.now(), method, params }),
|
|
38
|
+
signal: AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)].filter(Boolean)),
|
|
39
|
+
});
|
|
40
|
+
if (!response.ok) {
|
|
41
|
+
const detail = await response.text().catch(() => '');
|
|
42
|
+
throw new Error(`Stitch ${method} failed: HTTP ${response.status}${detail ? ` ${detail.slice(0, 300)}` : ''}`);
|
|
43
|
+
}
|
|
44
|
+
const envelope = await response.json();
|
|
45
|
+
if (envelope?.error !== undefined) {
|
|
46
|
+
const message = envelope.error?.message ?? JSON.stringify(envelope.error);
|
|
47
|
+
throw new Error(`Stitch ${method} failed: ${message}`);
|
|
48
|
+
}
|
|
49
|
+
if (envelope?.result === undefined) {
|
|
50
|
+
throw new Error(`Stitch ${method} returned no result`);
|
|
51
|
+
}
|
|
52
|
+
return envelope.result;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Create a Stitch client bound to one key-resolution callback.
|
|
57
|
+
*
|
|
58
|
+
* The key is read through a callback rather than captured, because the
|
|
59
|
+
* credential can be set or replaced while the process runs — a captured string
|
|
60
|
+
* would keep signing with a revoked key until the next restart.
|
|
61
|
+
*
|
|
62
|
+
* @param options - key resolver, endpoint override and per-call timeout.
|
|
63
|
+
* @returns `listTools` and `callTool`.
|
|
64
|
+
*/
|
|
65
|
+
export function createStitchClient(options = {}) {
|
|
66
|
+
const {
|
|
67
|
+
resolveApiKey,
|
|
68
|
+
url = MCP_URL,
|
|
69
|
+
timeoutMs = DEFAULT_TOOL_CALL_TIMEOUT_MS,
|
|
70
|
+
} = options;
|
|
71
|
+
|
|
72
|
+
const requireKey = async () => {
|
|
73
|
+
const apiKey = await resolveApiKey();
|
|
74
|
+
if (typeof apiKey !== 'string' || apiKey === '') {
|
|
75
|
+
throw new Error(
|
|
76
|
+
'Stitch API key is not configured. Open Settings → Plugins → stitch-designer and paste a key from https://stitch.withgoogle.com (avatar → Stitch Settings → API key).',
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
return apiKey;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
/**
|
|
84
|
+
* List the server's tools.
|
|
85
|
+
*
|
|
86
|
+
* @param signal - optional abort signal.
|
|
87
|
+
* @returns the upstream tool descriptors.
|
|
88
|
+
*/
|
|
89
|
+
async listTools(signal) {
|
|
90
|
+
const result = await rpc({ url, apiKey: await requireKey(), method: 'tools/list', params: {}, timeoutMs, signal });
|
|
91
|
+
return Array.isArray(result?.tools) ? result.tools : [];
|
|
92
|
+
},
|
|
93
|
+
|
|
94
|
+
/**
|
|
95
|
+
* Invoke one Stitch tool by its raw name.
|
|
96
|
+
*
|
|
97
|
+
* @param name - Stitch's own tool name.
|
|
98
|
+
* @param args - the tool arguments.
|
|
99
|
+
* @param exec - the tool execution context, whose signal is honoured.
|
|
100
|
+
* @returns the raw MCP result (`content`, `structuredContent`, `isError`).
|
|
101
|
+
*/
|
|
102
|
+
async callTool(name, args, exec) {
|
|
103
|
+
return rpc({
|
|
104
|
+
url,
|
|
105
|
+
apiKey: await requireKey(),
|
|
106
|
+
method: 'tools/call',
|
|
107
|
+
params: { name, arguments: args },
|
|
108
|
+
timeoutMs,
|
|
109
|
+
signal: exec?.signal,
|
|
110
|
+
});
|
|
111
|
+
},
|
|
112
|
+
};
|
|
113
|
+
}
|