@openartifactsai/server-sdk 0.0.0-stage → 0.23.0-rc.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 +202 -0
- package/NOTICE +5 -0
- package/README.md +5 -2
- package/bin/frame-host.d.ts +2 -0
- package/bin/frame-host.js +47 -0
- package/package.json +124 -4
- package/src/child.d.ts +37 -0
- package/src/child.js +64 -0
- package/src/connectors/connectors.d.ts +101 -0
- package/src/connectors/connectors.js +256 -0
- package/src/connectors/daemon-connectors.d.ts +34 -0
- package/src/connectors/daemon-connectors.js +73 -0
- package/src/connectors/index.d.ts +7 -0
- package/src/connectors/index.js +7 -0
- package/src/connectors/mcp-client.d.ts +157 -0
- package/src/connectors/mcp-client.js +483 -0
- package/src/daemon.d.ts +119 -0
- package/src/daemon.js +301 -0
- package/src/frame/access.d.ts +69 -0
- package/src/frame/access.js +168 -0
- package/src/frame/client/comments.css +1 -0
- package/src/frame/client/comments.js +58 -0
- package/src/frame/client/imports.d.ts +6 -0
- package/src/frame/client/imports.js +112 -0
- package/src/frame/client/mcp-shell.js +345 -0
- package/src/frame/client/mcp.js +253 -0
- package/src/frame/client/runtime.js +1363 -0
- package/src/frame/client/sample.js +762 -0
- package/src/frame/client/shell.css +51 -0
- package/src/frame/client/shell.html +29 -0
- package/src/frame/client/shell.js +1417 -0
- package/src/frame/comments.d.ts +102 -0
- package/src/frame/comments.js +379 -0
- package/src/frame/core.d.ts +313 -0
- package/src/frame/core.js +1757 -0
- package/src/frame/db.d.ts +162 -0
- package/src/frame/db.js +604 -0
- package/src/frame/declaration.d.ts +30 -0
- package/src/frame/declaration.js +60 -0
- package/src/frame/env.d.ts +262 -0
- package/src/frame/env.js +13 -0
- package/src/frame/files.d.ts +130 -0
- package/src/frame/files.js +472 -0
- package/src/frame/index.d.ts +35 -0
- package/src/frame/index.js +33 -0
- package/src/frame/local.d.ts +126 -0
- package/src/frame/local.js +612 -0
- package/src/frame/mcp-relay.d.ts +79 -0
- package/src/frame/mcp-relay.js +191 -0
- package/src/frame/page-api.d.ts +48 -0
- package/src/frame/page-api.js +1 -0
- package/src/frame/page-comments.d.ts +109 -0
- package/src/frame/page-comments.js +1 -0
- package/src/frame/page-db.d.ts +88 -0
- package/src/frame/page-db.js +1 -0
- package/src/frame/page-imports.d.ts +2 -0
- package/src/frame/page-imports.js +2 -0
- package/src/frame/page-services.d.ts +124 -0
- package/src/frame/page-services.js +1 -0
- package/src/frame/page-values.d.ts +90 -0
- package/src/frame/page-values.js +1 -0
- package/src/frame/sample-relay.d.ts +42 -0
- package/src/frame/sample-relay.js +186 -0
- package/src/frame/snapshot-action.d.ts +18 -0
- package/src/frame/snapshot-action.js +82 -0
- package/src/frame/wire.d.ts +198 -0
- package/src/frame/wire.js +21 -0
- package/src/index.d.ts +17 -0
- package/src/index.js +17 -0
- package/src/lan.d.ts +75 -0
- package/src/lan.js +200 -0
- package/src/legacy-env.d.ts +7 -0
- package/src/legacy-env.js +14 -0
- package/src/serve.d.ts +375 -0
- package/src/serve.js +811 -0
- package/src/snapshot.d.ts +41 -0
- package/src/snapshot.js +224 -0
- package/src/type-package.d.ts +48 -0
- package/src/type-package.js +114 -0
- package/src/ws.d.ts +50 -0
- package/src/ws.js +203 -0
- package/src/zip.d.ts +197 -0
- package/src/zip.js +662 -0
|
@@ -0,0 +1,483 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A minimal MCP client: JSON-RPC 2.0 over stdio (newline-delimited) or over
|
|
3
|
+
* Streamable HTTP (a POST per message, answered as JSON or as an event
|
|
4
|
+
* stream, the session kept in `Mcp-Session-Id`). It does what the `mcp`
|
|
5
|
+
* capability needs: `initialize`, `tools/list` (every page) and `tools/call`.
|
|
6
|
+
*
|
|
7
|
+
* Failures are {@link McpError}s carrying the capability's codes: a server
|
|
8
|
+
* that cannot be started or reached is `server_not_connected`, HTTP 401/403
|
|
9
|
+
* is `needs_reauth`, a JSON-RPC error or a missed deadline is
|
|
10
|
+
* `upstream_error`. A tool that ran and failed (`isError`) is a result.
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import { createInterface } from 'node:readline';
|
|
14
|
+
import { PendingCalls, readSse } from '@openartifactsai/protocol';
|
|
15
|
+
import { hasExited, stopChild } from "../child.js";
|
|
16
|
+
/** How long one request may take by default, and at most, ms (the editor runtime's `mcp` says the same numbers). */
|
|
17
|
+
export const MCP_CALL_TIMEOUT = { defaultMs: 120_000, maxMs: 600_000 };
|
|
18
|
+
/** The MCP revision this client speaks. */
|
|
19
|
+
export const MCP_PROTOCOL_VERSION = '2025-06-18';
|
|
20
|
+
/** How long starting a server and its `initialize` may take, ms. */
|
|
21
|
+
export const MCP_CONNECT_TIMEOUT_MS = 60_000;
|
|
22
|
+
/** Pages of `tools/list` followed at most. */
|
|
23
|
+
const MAX_TOOL_PAGES = 100;
|
|
24
|
+
/** Characters of a server's stderr kept for error messages. */
|
|
25
|
+
const STDERR_TAIL = 2000;
|
|
26
|
+
/** How long a stdio server has to end after end of input and `SIGTERM` before it is killed, ms. */
|
|
27
|
+
const STOP_GRACE_MS = 2000;
|
|
28
|
+
/** A failed connector call, with the capability's code. */
|
|
29
|
+
export class McpError extends Error {
|
|
30
|
+
code;
|
|
31
|
+
retryable;
|
|
32
|
+
constructor(code, message, retryable) {
|
|
33
|
+
super(message);
|
|
34
|
+
this.name = 'McpError';
|
|
35
|
+
this.code = code;
|
|
36
|
+
if (retryable)
|
|
37
|
+
this.retryable = true;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** An HTTP session the server no longer knows: connect again and repeat once. */
|
|
41
|
+
class SessionExpired extends McpError {
|
|
42
|
+
constructor(name) {
|
|
43
|
+
super('upstream_error', `${name} ended its session.`, true);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
const DEFAULT_CLIENT_INFO = { name: 'open-artifacts', version: '0.1.0' };
|
|
47
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
48
|
+
/** Resolves `promise`, or rejects with the signal's reason once it aborts. */
|
|
49
|
+
function raceSignal(promise, signal) {
|
|
50
|
+
if (!signal)
|
|
51
|
+
return promise;
|
|
52
|
+
if (signal.aborted)
|
|
53
|
+
return Promise.reject(signal.reason);
|
|
54
|
+
return new Promise((resolve, reject) => {
|
|
55
|
+
const onAbort = () => reject(signal.reason);
|
|
56
|
+
signal.addEventListener('abort', onAbort, { once: true });
|
|
57
|
+
promise.then((value) => {
|
|
58
|
+
signal.removeEventListener('abort', onAbort);
|
|
59
|
+
resolve(value);
|
|
60
|
+
}, (error) => {
|
|
61
|
+
signal.removeEventListener('abort', onAbort);
|
|
62
|
+
reject(error);
|
|
63
|
+
});
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
/** Keeps the fields of a `Tool` a page uses, and its hints. */
|
|
67
|
+
function toolOf(value) {
|
|
68
|
+
if (!isRecord(value) || typeof value.name !== 'string' || !value.name)
|
|
69
|
+
return null;
|
|
70
|
+
return {
|
|
71
|
+
name: value.name,
|
|
72
|
+
...(typeof value.title === 'string' ? { title: value.title } : {}),
|
|
73
|
+
...(typeof value.description === 'string' ? { description: value.description } : {}),
|
|
74
|
+
...(isRecord(value.inputSchema) ? { inputSchema: value.inputSchema } : {}),
|
|
75
|
+
...(isRecord(value.outputSchema) ? { outputSchema: value.outputSchema } : {}),
|
|
76
|
+
...(isRecord(value.annotations) ? { annotations: value.annotations } : {}),
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
/** A `CallToolResult`, with `content` always an array. */
|
|
80
|
+
function toolResultOf(name, value) {
|
|
81
|
+
if (!isRecord(value))
|
|
82
|
+
throw new McpError('upstream_error', `${name} answered tools/call with something other than a result.`);
|
|
83
|
+
const result = { ...value, content: Array.isArray(value.content) ? value.content : [] };
|
|
84
|
+
if (!isRecord(value.structuredContent))
|
|
85
|
+
delete result.structuredContent;
|
|
86
|
+
if (value.isError !== true)
|
|
87
|
+
delete result.isError;
|
|
88
|
+
return result;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* The transport-independent part: request ids, answers, deadlines,
|
|
92
|
+
* cancellation, the handshake and the two tool methods.
|
|
93
|
+
*/
|
|
94
|
+
export class McpClient {
|
|
95
|
+
/** The connector's name in the configuration. */
|
|
96
|
+
name;
|
|
97
|
+
clientInfo;
|
|
98
|
+
/** The protocol version the server agreed to. */
|
|
99
|
+
protocolVersion = null;
|
|
100
|
+
nextId = 1;
|
|
101
|
+
pending = new PendingCalls();
|
|
102
|
+
ready = null;
|
|
103
|
+
tools = null;
|
|
104
|
+
constructor(name, clientInfo = DEFAULT_CLIENT_INFO) {
|
|
105
|
+
this.name = name;
|
|
106
|
+
this.clientInfo = clientInfo;
|
|
107
|
+
}
|
|
108
|
+
/** Whether the handshake is done (or under way). */
|
|
109
|
+
get connected() {
|
|
110
|
+
return this.ready !== null;
|
|
111
|
+
}
|
|
112
|
+
/** Fails every pending request and forgets the session: the next call connects again. */
|
|
113
|
+
reset(error) {
|
|
114
|
+
this.ready = null;
|
|
115
|
+
this.tools = null;
|
|
116
|
+
this.protocolVersion = null;
|
|
117
|
+
this.pending.rejectAll(error);
|
|
118
|
+
}
|
|
119
|
+
/** Starts the server and runs the handshake once; concurrent callers share it. */
|
|
120
|
+
connect(signal) {
|
|
121
|
+
if (!this.ready) {
|
|
122
|
+
const ready = this.handshake();
|
|
123
|
+
this.ready = ready;
|
|
124
|
+
ready.catch(() => {
|
|
125
|
+
if (this.ready === ready)
|
|
126
|
+
this.ready = null;
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return raceSignal(this.ready, signal);
|
|
130
|
+
}
|
|
131
|
+
async handshake() {
|
|
132
|
+
await this.open();
|
|
133
|
+
const result = await this.request('initialize', { protocolVersion: MCP_PROTOCOL_VERSION, capabilities: {}, clientInfo: this.clientInfo }, { timeoutMs: MCP_CONNECT_TIMEOUT_MS });
|
|
134
|
+
this.protocolVersion = isRecord(result) && typeof result.protocolVersion === 'string' ? result.protocolVersion : MCP_PROTOCOL_VERSION;
|
|
135
|
+
await this.notify('notifications/initialized');
|
|
136
|
+
}
|
|
137
|
+
/** Every tool of the server, all pages of `tools/list` (kept until the server says the list changed). */
|
|
138
|
+
async listTools(control = {}) {
|
|
139
|
+
return this.session(control, async () => {
|
|
140
|
+
if (this.tools)
|
|
141
|
+
return this.tools;
|
|
142
|
+
const tools = [];
|
|
143
|
+
let cursor;
|
|
144
|
+
for (let page = 0; page < MAX_TOOL_PAGES; page++) {
|
|
145
|
+
const result = await this.request('tools/list', cursor === undefined ? {} : { cursor }, control);
|
|
146
|
+
if (!isRecord(result))
|
|
147
|
+
throw new McpError('upstream_error', `${this.name} answered tools/list with something other than a list.`);
|
|
148
|
+
for (const tool of Array.isArray(result.tools) ? result.tools : []) {
|
|
149
|
+
const info = toolOf(tool);
|
|
150
|
+
if (info)
|
|
151
|
+
tools.push(info);
|
|
152
|
+
}
|
|
153
|
+
cursor = typeof result.nextCursor === 'string' && result.nextCursor ? result.nextCursor : undefined;
|
|
154
|
+
if (cursor === undefined)
|
|
155
|
+
break;
|
|
156
|
+
}
|
|
157
|
+
this.tools = tools;
|
|
158
|
+
return tools;
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
/** Calls one tool. */
|
|
162
|
+
callTool(tool, args, control = {}) {
|
|
163
|
+
return this.session(control, async () => toolResultOf(this.name, await this.request('tools/call', { name: tool, arguments: args }, control)));
|
|
164
|
+
}
|
|
165
|
+
/** Connects, runs `task`, and once more after an HTTP session expired. */
|
|
166
|
+
async session(control, task) {
|
|
167
|
+
await this.connect(control.signal);
|
|
168
|
+
const current = this.ready;
|
|
169
|
+
try {
|
|
170
|
+
return await task();
|
|
171
|
+
}
|
|
172
|
+
catch (error) {
|
|
173
|
+
if (!(error instanceof SessionExpired))
|
|
174
|
+
throw error;
|
|
175
|
+
if (this.ready === current)
|
|
176
|
+
this.reset(error);
|
|
177
|
+
await this.connect(control.signal);
|
|
178
|
+
return task();
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** Sends a request and waits for its answer, its deadline or its signal. */
|
|
182
|
+
request(method, params, control = {}) {
|
|
183
|
+
const id = this.nextId++;
|
|
184
|
+
// NaN would fire the deadline at once; Infinity still means "as long as allowed".
|
|
185
|
+
const wanted = control.timeoutMs === undefined || Number.isNaN(control.timeoutMs) ? MCP_CALL_TIMEOUT.defaultMs : control.timeoutMs;
|
|
186
|
+
const timeoutMs = Math.max(1, Math.min(wanted, MCP_CALL_TIMEOUT.maxMs));
|
|
187
|
+
const { signal } = control;
|
|
188
|
+
// An aborted call is not sent, so the server is not told to cancel it either.
|
|
189
|
+
if (signal?.aborted)
|
|
190
|
+
return Promise.reject(signal.reason);
|
|
191
|
+
const transport = new AbortController();
|
|
192
|
+
const cancel = (reason) => {
|
|
193
|
+
this.notify('notifications/cancelled', { requestId: id, reason }).catch(() => undefined);
|
|
194
|
+
};
|
|
195
|
+
const answer = this.pending.wait(id, {
|
|
196
|
+
timeoutMs,
|
|
197
|
+
onTimeout: () => {
|
|
198
|
+
cancel('Timed out.');
|
|
199
|
+
return new McpError('upstream_error', `${this.name} did not answer ${method} within ${Math.round(timeoutMs / 1000)} s.`, true);
|
|
200
|
+
},
|
|
201
|
+
...(signal ? { signal, onAbort: () => cancel('The page cancelled the call.') } : {}),
|
|
202
|
+
// However the request ends, what still carries it (an HTTP POST) stops.
|
|
203
|
+
onSettled: () => transport.abort(),
|
|
204
|
+
});
|
|
205
|
+
this.transmit({ jsonrpc: '2.0', id, method, params }, transport.signal).then(() => {
|
|
206
|
+
if (this.answersInline)
|
|
207
|
+
this.pending.reject(id, new McpError('upstream_error', `${this.name} sent no answer to ${method}.`));
|
|
208
|
+
}, (error) => void this.pending.reject(id, error));
|
|
209
|
+
return answer;
|
|
210
|
+
}
|
|
211
|
+
/** Sends a notification. */
|
|
212
|
+
notify(method, params) {
|
|
213
|
+
return this.transmit({ jsonrpc: '2.0', method, ...(params === undefined ? {} : { params }) }, AbortSignal.timeout(10_000));
|
|
214
|
+
}
|
|
215
|
+
/** Handles one message from the server: an answer, a request or a notification. */
|
|
216
|
+
deliver(message) {
|
|
217
|
+
if (!isRecord(message))
|
|
218
|
+
return;
|
|
219
|
+
if (typeof message.method === 'string') {
|
|
220
|
+
const id = message.id;
|
|
221
|
+
if (typeof id === 'number' || typeof id === 'string')
|
|
222
|
+
void this.answer(id, message.method);
|
|
223
|
+
else if (message.method === 'notifications/tools/list_changed')
|
|
224
|
+
this.tools = null;
|
|
225
|
+
return;
|
|
226
|
+
}
|
|
227
|
+
const id = message.id;
|
|
228
|
+
if (typeof id !== 'number' && typeof id !== 'string')
|
|
229
|
+
return;
|
|
230
|
+
const key = this.pending.has(id) ? id : typeof id === 'string' && /^\d+$/.test(id) ? Number(id) : undefined;
|
|
231
|
+
if (key === undefined || !this.pending.has(key))
|
|
232
|
+
return;
|
|
233
|
+
if (isRecord(message.error)) {
|
|
234
|
+
const text = typeof message.error.message === 'string' && message.error.message ? message.error.message : 'The connector refused the request.';
|
|
235
|
+
this.pending.reject(key, new McpError('upstream_error', text));
|
|
236
|
+
}
|
|
237
|
+
else
|
|
238
|
+
this.pending.resolve(key, message.result);
|
|
239
|
+
}
|
|
240
|
+
/** Answers a request from the server: `ping` and `roots/list`; anything else is not supported. */
|
|
241
|
+
async answer(id, method) {
|
|
242
|
+
const reply = method === 'ping'
|
|
243
|
+
? { jsonrpc: '2.0', id, result: {} }
|
|
244
|
+
: method === 'roots/list'
|
|
245
|
+
? { jsonrpc: '2.0', id, result: { roots: [] } }
|
|
246
|
+
: { jsonrpc: '2.0', id, error: { code: -32601, message: `Not supported by this client: ${method}` } };
|
|
247
|
+
try {
|
|
248
|
+
await this.transmit(reply, AbortSignal.timeout(10_000));
|
|
249
|
+
}
|
|
250
|
+
catch {
|
|
251
|
+
// The server went away; it gets no answer.
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
/** A server this process starts and talks to over its stdin and stdout. */
|
|
256
|
+
export class StdioMcpClient extends McpClient {
|
|
257
|
+
answersInline = false;
|
|
258
|
+
config;
|
|
259
|
+
log;
|
|
260
|
+
child = null;
|
|
261
|
+
stderr = '';
|
|
262
|
+
constructor(name, config, options = {}) {
|
|
263
|
+
super(name, options.clientInfo);
|
|
264
|
+
this.config = config;
|
|
265
|
+
this.log = options.log ?? (() => undefined);
|
|
266
|
+
}
|
|
267
|
+
/** The running process's id, if any (tests). */
|
|
268
|
+
get pid() {
|
|
269
|
+
return this.child?.pid;
|
|
270
|
+
}
|
|
271
|
+
async open() {
|
|
272
|
+
if (this.child)
|
|
273
|
+
return;
|
|
274
|
+
this.stderr = '';
|
|
275
|
+
const child = spawn(this.config.command, this.config.args ?? [], {
|
|
276
|
+
...(this.config.cwd ? { cwd: this.config.cwd } : {}),
|
|
277
|
+
env: { ...process.env, ...(this.config.env ?? {}) },
|
|
278
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
279
|
+
windowsHide: true,
|
|
280
|
+
});
|
|
281
|
+
this.child = child;
|
|
282
|
+
try {
|
|
283
|
+
await new Promise((resolve, reject) => {
|
|
284
|
+
child.once('spawn', resolve);
|
|
285
|
+
child.once('error', reject);
|
|
286
|
+
});
|
|
287
|
+
}
|
|
288
|
+
catch (error) {
|
|
289
|
+
if (this.child === child)
|
|
290
|
+
this.child = null;
|
|
291
|
+
throw new McpError('server_not_connected', `Could not start ${this.name} (${this.config.command}): ${error instanceof Error ? error.message : String(error)}`);
|
|
292
|
+
}
|
|
293
|
+
if (this.child !== child) {
|
|
294
|
+
void stopChild(child, { graceMs: STOP_GRACE_MS, endStdin: true });
|
|
295
|
+
throw new McpError('server_not_connected', `${this.name} was stopped.`, true);
|
|
296
|
+
}
|
|
297
|
+
child.on('error', (error) => this.log(`connector ${this.name}: ${error.message}`));
|
|
298
|
+
child.stdin.on('error', () => undefined);
|
|
299
|
+
child.stderr.setEncoding('utf8');
|
|
300
|
+
child.stderr.on('data', (chunk) => {
|
|
301
|
+
this.stderr = (this.stderr + chunk).slice(-STDERR_TAIL);
|
|
302
|
+
});
|
|
303
|
+
const lines = createInterface({ input: child.stdout, crlfDelay: Infinity });
|
|
304
|
+
lines.on('line', (line) => {
|
|
305
|
+
const text = line.trim();
|
|
306
|
+
if (!text)
|
|
307
|
+
return;
|
|
308
|
+
let message;
|
|
309
|
+
try {
|
|
310
|
+
message = JSON.parse(text);
|
|
311
|
+
}
|
|
312
|
+
catch {
|
|
313
|
+
this.log(`connector ${this.name}: not JSON on stdout: ${text.slice(0, 200)}`);
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
if (Array.isArray(message))
|
|
317
|
+
for (const item of message)
|
|
318
|
+
this.deliver(item);
|
|
319
|
+
else
|
|
320
|
+
this.deliver(message);
|
|
321
|
+
});
|
|
322
|
+
child.once('exit', (code, signal) => {
|
|
323
|
+
lines.close();
|
|
324
|
+
if (this.child !== child)
|
|
325
|
+
return;
|
|
326
|
+
this.child = null;
|
|
327
|
+
const why = this.stderr.trim().split('\n').slice(-3).join(' ').trim();
|
|
328
|
+
this.reset(new McpError('server_not_connected', `${this.name} stopped (${code ?? signal ?? 'exit'})${why ? `: ${why}` : '.'}`, true));
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
async transmit(message) {
|
|
332
|
+
const stdin = this.child?.stdin;
|
|
333
|
+
if (!stdin?.writable)
|
|
334
|
+
throw new McpError('server_not_connected', `${this.name} is not running.`, true);
|
|
335
|
+
stdin.write(`${JSON.stringify(message)}\n`);
|
|
336
|
+
}
|
|
337
|
+
async close() {
|
|
338
|
+
const child = this.child;
|
|
339
|
+
this.child = null;
|
|
340
|
+
this.reset(new McpError('server_not_connected', `${this.name} was stopped.`, true));
|
|
341
|
+
// Not waited for: closing every connector must not take the server's grace period longer.
|
|
342
|
+
if (child)
|
|
343
|
+
void stopChild(child, { graceMs: STOP_GRACE_MS, endStdin: true });
|
|
344
|
+
}
|
|
345
|
+
/** Kills the process at once (this process is exiting: synchronous, nothing after this runs). */
|
|
346
|
+
killNow() {
|
|
347
|
+
if (this.child && !hasExited(this.child))
|
|
348
|
+
this.child.kill('SIGKILL');
|
|
349
|
+
}
|
|
350
|
+
}
|
|
351
|
+
/** A server reached over Streamable HTTP. */
|
|
352
|
+
export class HttpMcpClient extends McpClient {
|
|
353
|
+
answersInline = true;
|
|
354
|
+
config;
|
|
355
|
+
sessionId = null;
|
|
356
|
+
constructor(name, config, options = {}) {
|
|
357
|
+
super(name, options.clientInfo);
|
|
358
|
+
this.config = config;
|
|
359
|
+
}
|
|
360
|
+
async open() {
|
|
361
|
+
this.sessionId = null;
|
|
362
|
+
}
|
|
363
|
+
headers() {
|
|
364
|
+
return {
|
|
365
|
+
...(this.config.headers ?? {}),
|
|
366
|
+
'content-type': 'application/json',
|
|
367
|
+
accept: 'application/json, text/event-stream',
|
|
368
|
+
...(this.sessionId ? { 'mcp-session-id': this.sessionId } : {}),
|
|
369
|
+
...(this.protocolVersion ? { 'mcp-protocol-version': this.protocolVersion } : {}),
|
|
370
|
+
};
|
|
371
|
+
}
|
|
372
|
+
async transmit(message, signal) {
|
|
373
|
+
const sentSession = this.sessionId;
|
|
374
|
+
let response;
|
|
375
|
+
try {
|
|
376
|
+
response = await fetch(this.config.url, { method: 'POST', headers: this.headers(), body: JSON.stringify(message), signal });
|
|
377
|
+
}
|
|
378
|
+
catch (error) {
|
|
379
|
+
if (signal.aborted)
|
|
380
|
+
throw signal.reason;
|
|
381
|
+
const cause = error instanceof Error ? (error.cause?.message ?? error.message) : String(error);
|
|
382
|
+
throw new McpError('server_not_connected', `Could not reach ${this.name} (${this.config.url}): ${cause}`, true);
|
|
383
|
+
}
|
|
384
|
+
const session = response.headers.get('mcp-session-id');
|
|
385
|
+
if (session)
|
|
386
|
+
this.sessionId = session;
|
|
387
|
+
const { status } = response;
|
|
388
|
+
if (status === 401 || status === 403) {
|
|
389
|
+
await response.body?.cancel();
|
|
390
|
+
throw new McpError('needs_reauth', `${this.name} refused its credentials (HTTP ${status}).`);
|
|
391
|
+
}
|
|
392
|
+
if (status === 404 && sentSession !== null && message.method !== 'initialize') {
|
|
393
|
+
await response.body?.cancel();
|
|
394
|
+
if (this.sessionId === sentSession)
|
|
395
|
+
this.sessionId = null;
|
|
396
|
+
throw new SessionExpired(this.name);
|
|
397
|
+
}
|
|
398
|
+
if (status === 429) {
|
|
399
|
+
await response.body?.cancel();
|
|
400
|
+
throw new McpError('rate_limited', `${this.name} is busy (HTTP 429).`, true);
|
|
401
|
+
}
|
|
402
|
+
if (!response.ok) {
|
|
403
|
+
const text = (await response.text().catch(() => '')).trim().slice(0, 300);
|
|
404
|
+
throw new McpError('upstream_error', `${this.name} answered HTTP ${status}${text ? `: ${text}` : '.'}`, status >= 500);
|
|
405
|
+
}
|
|
406
|
+
if (message.id === undefined || message.method === undefined || status === 202 || !response.body) {
|
|
407
|
+
await response.body?.cancel();
|
|
408
|
+
return;
|
|
409
|
+
}
|
|
410
|
+
const type = (response.headers.get('content-type') ?? '').toLowerCase();
|
|
411
|
+
if (type.includes('text/event-stream'))
|
|
412
|
+
return this.readStream(response.body, message.id, signal);
|
|
413
|
+
let body;
|
|
414
|
+
try {
|
|
415
|
+
body = await response.json();
|
|
416
|
+
}
|
|
417
|
+
catch {
|
|
418
|
+
if (signal.aborted)
|
|
419
|
+
throw signal.reason;
|
|
420
|
+
throw new McpError('upstream_error', `${this.name} answered with something other than JSON.`);
|
|
421
|
+
}
|
|
422
|
+
if (Array.isArray(body))
|
|
423
|
+
for (const item of body)
|
|
424
|
+
this.deliver(item);
|
|
425
|
+
else
|
|
426
|
+
this.deliver(body);
|
|
427
|
+
}
|
|
428
|
+
/**
|
|
429
|
+
* Reads an event stream until the answer to `id` came (then the rest is cancelled) or the stream ends; whatever is
|
|
430
|
+
* left at the end is read too, even an unterminated last line.
|
|
431
|
+
*/
|
|
432
|
+
async readStream(body, id, signal) {
|
|
433
|
+
const answered = (message) => isRecord(message) && message.method === undefined && (message.id === id || String(message.id) === String(id));
|
|
434
|
+
const events = readSse(body, { atEnd: 'all' });
|
|
435
|
+
try {
|
|
436
|
+
for (;;) {
|
|
437
|
+
// Only an error reading the body is mapped here, not one delivering a message.
|
|
438
|
+
let step;
|
|
439
|
+
try {
|
|
440
|
+
step = await events.next();
|
|
441
|
+
}
|
|
442
|
+
catch (error) {
|
|
443
|
+
if (signal.aborted)
|
|
444
|
+
throw signal.reason;
|
|
445
|
+
const cause = error instanceof Error ? (error.cause?.message ?? error.message) : String(error);
|
|
446
|
+
throw new McpError('server_not_connected', `Connection to ${this.name} (${this.config.url}) ended while reading response: ${cause}`, true);
|
|
447
|
+
}
|
|
448
|
+
if (step.done)
|
|
449
|
+
return;
|
|
450
|
+
let message;
|
|
451
|
+
try {
|
|
452
|
+
message = JSON.parse(step.value.data);
|
|
453
|
+
}
|
|
454
|
+
catch {
|
|
455
|
+
continue;
|
|
456
|
+
}
|
|
457
|
+
const batch = Array.isArray(message) ? message : [message];
|
|
458
|
+
for (const item of batch)
|
|
459
|
+
this.deliver(item);
|
|
460
|
+
if (batch.some(answered))
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
}
|
|
464
|
+
finally {
|
|
465
|
+
await events.return(undefined);
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
async close() {
|
|
469
|
+
const session = this.sessionId;
|
|
470
|
+
const headers = this.headers();
|
|
471
|
+
this.sessionId = null;
|
|
472
|
+
this.reset(new McpError('server_not_connected', `${this.name} was disconnected.`, true));
|
|
473
|
+
if (!session)
|
|
474
|
+
return;
|
|
475
|
+
try {
|
|
476
|
+
const response = await fetch(this.config.url, { method: 'DELETE', headers, signal: AbortSignal.timeout(2000) });
|
|
477
|
+
await response.body?.cancel();
|
|
478
|
+
}
|
|
479
|
+
catch {
|
|
480
|
+
// Best effort: the server ends idle sessions by itself.
|
|
481
|
+
}
|
|
482
|
+
}
|
|
483
|
+
}
|
package/src/daemon.d.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The Type API client: what a type server started by the daemon calls back
|
|
3
|
+
* (`/api/open-artifacts.type.*`, Bearer `OPEN_ARTIFACTS_TYPE_TOKEN`).
|
|
4
|
+
*
|
|
5
|
+
* It reads `OPEN_ARTIFACTS_DAEMON_URL` and `OPEN_ARTIFACTS_TYPE_TOKEN`. A server without them
|
|
6
|
+
* (started by hand, or remote) gets a client whose calls fail with
|
|
7
|
+
* `no_daemon`; its pages simply cannot wake the agent.
|
|
8
|
+
*/
|
|
9
|
+
import { OpenArtifactsError, TYPE_API_ROUTES, type SampleLimits, type TypeApiArtifact, type TypeApiEvent, type TypeApiPresence, type TypeApiSampleLimitsQuery, type TypeApiSampleRequest, type TypeApiSampleToolRequest, type TypeApiTask, type TypeApiTouch, type TypeApiWakeRequest, type TypeApiWakeResult, type TypeServerEnv } from '@openartifactsai/protocol';
|
|
10
|
+
import type { FrameMcpState, PageMcpListResult, PageMcpToolDescription, PageMcpToolResult, TypeApiMcpCallRequest, TypeApiMcpPageCallRequest, TypeApiMcpPageDescribeRequest, TypeApiMcpPageToolsRequest, TypeApiMcpToolsResponse } from '@openartifactsai/protocol/page-mcp';
|
|
11
|
+
/**
|
|
12
|
+
* The `OPEN_ARTIFACTS_*` variables the daemon passed, without empty ones. Every field is
|
|
13
|
+
* missing when the server was started by hand.
|
|
14
|
+
*/
|
|
15
|
+
export declare function typeServerEnv(env?: NodeJS.ProcessEnv): Partial<TypeServerEnv>;
|
|
16
|
+
/** A Type API route name. */
|
|
17
|
+
export type TypeApiRoute = (typeof TYPE_API_ROUTES)[keyof typeof TYPE_API_ROUTES];
|
|
18
|
+
/** Options of {@link TypeApi}. `null` means "none"; `undefined` reads the environment. */
|
|
19
|
+
export interface TypeApiOptions {
|
|
20
|
+
/** Base URL of the daemon (default `OPEN_ARTIFACTS_DAEMON_URL`). */
|
|
21
|
+
url?: string | null;
|
|
22
|
+
/** Bearer token of the Type API (default `OPEN_ARTIFACTS_TYPE_TOKEN`). */
|
|
23
|
+
token?: string | null;
|
|
24
|
+
/** Per-request timeout, ms. Default 15 s. */
|
|
25
|
+
timeoutMs?: number;
|
|
26
|
+
}
|
|
27
|
+
/** What {@link TypeApi.wake} hands to the owner's session. */
|
|
28
|
+
export type TypeApiWakeBody = Omit<TypeApiWakeRequest, 'id'>;
|
|
29
|
+
/**
|
|
30
|
+
* The part of the Type API a type server calls back: what an embedder (a cloud host running the type server in its
|
|
31
|
+
* own process) implements in place of a daemon.
|
|
32
|
+
*/
|
|
33
|
+
export type TypeApiLike = Pick<TypeApi, 'wake' | 'presence' | 'touch'> & Partial<Pick<TypeApi, 'quiet'>>;
|
|
34
|
+
/** A failed `type.mcp.call`: the connector's code, and whether trying again may help. */
|
|
35
|
+
export declare class TypeApiMcpError extends OpenArtifactsError {
|
|
36
|
+
readonly retryable: boolean;
|
|
37
|
+
constructor(code: string, message: string, retryable: boolean, status?: number);
|
|
38
|
+
}
|
|
39
|
+
/** The Type API client. */
|
|
40
|
+
export declare class TypeApi {
|
|
41
|
+
/** Base URL of the daemon without a trailing slash, or `null` when standalone. */
|
|
42
|
+
readonly url: string | null;
|
|
43
|
+
/** Bearer token, or `null` when standalone. */
|
|
44
|
+
readonly token: string | null;
|
|
45
|
+
/** Per-request timeout, ms. */
|
|
46
|
+
readonly timeoutMs: number;
|
|
47
|
+
/** Whether the daemon is from before the rename (answers `/api/open-artifact.type.*` only); learned on the first 404. */
|
|
48
|
+
private readonly names;
|
|
49
|
+
/** Reads the daemon address and token from `options`, else from the environment. */
|
|
50
|
+
constructor(options?: TypeApiOptions);
|
|
51
|
+
/** A Type API request: the new path first, the older one when a daemon from before the rename answers 404. */
|
|
52
|
+
private fetchApi;
|
|
53
|
+
/** True when the server was started by a daemon and can call it. */
|
|
54
|
+
get available(): boolean;
|
|
55
|
+
/**
|
|
56
|
+
* Calls `open-artifacts.type.<name>`: `GET` with `query`, or `POST` with `body`.
|
|
57
|
+
* Throws an {@link OpenArtifactsError} (`no_daemon`, `daemon_failed`, or the daemon's
|
|
58
|
+
* own code) on failure.
|
|
59
|
+
*/
|
|
60
|
+
call<T>(name: TypeApiRoute, init?: {
|
|
61
|
+
query?: Record<string, string | number>;
|
|
62
|
+
body?: unknown;
|
|
63
|
+
timeoutMs?: number;
|
|
64
|
+
}): Promise<T>;
|
|
65
|
+
/** The daemon's record of an artifact. */
|
|
66
|
+
artifact(id: string): Promise<TypeApiArtifact>;
|
|
67
|
+
/** Hands comment threads and page requests to the owner's session. */
|
|
68
|
+
wake(id: string, { threads, requests, stage }?: TypeApiWakeBody): Promise<TypeApiWakeResult>;
|
|
69
|
+
/** Reports that the agent's work on the artifact stopped: nothing was written to it for a while. */
|
|
70
|
+
quiet(id: string): Promise<unknown>;
|
|
71
|
+
/** Whether an agent is there to receive, and whether it is busy. */
|
|
72
|
+
presence(id: string): Promise<TypeApiPresence>;
|
|
73
|
+
/** Reports a write: `author` is a viewer name, `guest:<name>` or `agent`. */
|
|
74
|
+
touch(id: string, { author, paths, title }: Omit<TypeApiTouch, 'id'>): Promise<unknown>;
|
|
75
|
+
/** Reports that the owner's view context of an artifact changed (`at`: when, ISO); the daemon tells adapters. */
|
|
76
|
+
context(id: string, at: string): Promise<unknown>;
|
|
77
|
+
/** Reports progress or the end of a long action. */
|
|
78
|
+
task(task: string, report?: Omit<TypeApiTask, 'task'>): Promise<unknown>;
|
|
79
|
+
/**
|
|
80
|
+
* Starts one `sample` call (`open-artifacts.type.sample`): resolves with the answer's NDJSON body (one
|
|
81
|
+
* `SampleStreamEvent` per line, open until `done` or `error`) once the daemon answered 200. No timeout of its own:
|
|
82
|
+
* the daemon ends an over-long call; aborting `signal` cancels it. Throws an {@link OpenArtifactsError} when the call
|
|
83
|
+
* could not be started (`no_daemon`, `daemon_failed`, or the daemon's own code).
|
|
84
|
+
*/
|
|
85
|
+
sampleStream(body: TypeApiSampleRequest, signal: AbortSignal): Promise<AsyncIterable<Uint8Array>>;
|
|
86
|
+
/** Hands back one round's tool results of a running `sample` call. */
|
|
87
|
+
sampleTool(body: TypeApiSampleToolRequest): Promise<unknown>;
|
|
88
|
+
/** A view's `sample` limits. */
|
|
89
|
+
sampleLimits(query: TypeApiSampleLimitsQuery): Promise<SampleLimits>;
|
|
90
|
+
/** The daemon's connectors and their tools (all, or `server`), for this type's own editor. */
|
|
91
|
+
mcpTools(server?: string): Promise<TypeApiMcpToolsResponse>;
|
|
92
|
+
/**
|
|
93
|
+
* One tool call of this type's own editor on the daemon's connectors. Rejects with an {@link OpenArtifactsError}
|
|
94
|
+
* ({@link TypeApiMcpError}) whose `code` is the connector's (`server_not_connected`, `needs_reauth`,
|
|
95
|
+
* `upstream_error`, ...). Aborting `signal` cancels it on the connector.
|
|
96
|
+
*/
|
|
97
|
+
mcpCall(body: TypeApiMcpCallRequest, signal?: AbortSignal): Promise<PageMcpToolResult>;
|
|
98
|
+
/**
|
|
99
|
+
* A page's `mcp` call, as the daemon answers it: NDJSON `McpStreamEvent`s (page-mcp.ts) until `done` or `error`.
|
|
100
|
+
* Aborting `signal` cancels the call.
|
|
101
|
+
*/
|
|
102
|
+
mcpPageStream(body: TypeApiMcpPageCallRequest, signal: AbortSignal): Promise<AsyncIterable<Uint8Array>>;
|
|
103
|
+
/** A page's `mcp.listTools`: its declared connectors and tools, as much as the person allowed it to see. */
|
|
104
|
+
mcpPageTools(body: TypeApiMcpPageToolsRequest): Promise<PageMcpListResult>;
|
|
105
|
+
/** A page's `mcp.describeTool`. */
|
|
106
|
+
mcpPageDescribe(body: TypeApiMcpPageDescribeRequest): Promise<PageMcpToolDescription>;
|
|
107
|
+
/** Whether each declared connector of a page is allowed (`permissions.state("mcp:<server>")`), never asking. */
|
|
108
|
+
mcpPageState(id: string, view: string): Promise<FrameMcpState>;
|
|
109
|
+
/** Whether the person's grants already cover artifact `id`'s `sample` calls (no consent dialog would open). */
|
|
110
|
+
sampleState(id: string): Promise<{
|
|
111
|
+
state: 'granted' | 'denied' | 'none';
|
|
112
|
+
}>;
|
|
113
|
+
/**
|
|
114
|
+
* Follows presence and artifact events of some artifacts (server-sent
|
|
115
|
+
* events). Calls `onEvent` for each one and reconnects after a drop until
|
|
116
|
+
* the returned function is called. Does nothing when standalone.
|
|
117
|
+
*/
|
|
118
|
+
events(ids: string[], onEvent: (event: TypeApiEvent) => void): () => void;
|
|
119
|
+
}
|