@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,256 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connectors: the MCP servers the owner set up on this computer, whose tools
|
|
3
|
+
* the owner's pages call through the `mcp` capability.
|
|
4
|
+
*
|
|
5
|
+
* They are configured in `connectors.json` beside `settings.json`
|
|
6
|
+
* (`$OPEN_ARTIFACTS_CONNECTORS`, else `$OPEN_ARTIFACTS_HOME/connectors.json`,
|
|
7
|
+
* else `~/.agents/open-artifacts/connectors.json`), in the usual
|
|
8
|
+
* `mcpServers` shape:
|
|
9
|
+
*
|
|
10
|
+
* { "mcpServers": {
|
|
11
|
+
* "files": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "~/Data"] },
|
|
12
|
+
* "tracker": { "url": "https://mcp.example.com/mcp", "headers": { "Authorization": "Bearer ${TRACKER_TOKEN}" } }
|
|
13
|
+
* } }
|
|
14
|
+
*
|
|
15
|
+
* `${NAME}` (or `${NAME:-default}`) in a string is read from the
|
|
16
|
+
* environment; `"disabled": true` keeps a server listed but off. The file is
|
|
17
|
+
* read again when it changes. Stdio servers start on first use, are reused,
|
|
18
|
+
* start again after they stop, and are stopped with {@link ConnectorsHost.close}.
|
|
19
|
+
*/
|
|
20
|
+
import { lstatSync, readFileSync, statSync } from 'node:fs';
|
|
21
|
+
import { homedir } from 'node:os';
|
|
22
|
+
import { join, resolve } from 'node:path';
|
|
23
|
+
import { envOrLegacy } from "../legacy-env.js";
|
|
24
|
+
import { HttpMcpClient, McpError, StdioMcpClient } from "./mcp-client.js";
|
|
25
|
+
/** How long listing one server's tools may take, ms. */
|
|
26
|
+
const LIST_TIMEOUT_MS = 30_000;
|
|
27
|
+
/** Expands a leading `~`. */
|
|
28
|
+
function expandHome(path) {
|
|
29
|
+
if (path === '~')
|
|
30
|
+
return homedir();
|
|
31
|
+
if (path.startsWith('~/'))
|
|
32
|
+
return join(homedir(), path.slice(2));
|
|
33
|
+
return path;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The home before 0.23. A daemon that has not moved it yet uses it (it moves it once to `~/.agents/open-artifacts`
|
|
37
|
+
* and leaves a link, or keeps it when both are there).
|
|
38
|
+
*/
|
|
39
|
+
const LEGACY_HOME = '~/.agents/open-artifact';
|
|
40
|
+
/** The default home, as the daemon finds it without moving anything: the old one while it is a folder, not a link. */
|
|
41
|
+
function defaultHome() {
|
|
42
|
+
try {
|
|
43
|
+
const old = lstatSync(expandHome(LEGACY_HOME));
|
|
44
|
+
if (old.isDirectory() && !old.isSymbolicLink())
|
|
45
|
+
return LEGACY_HOME;
|
|
46
|
+
}
|
|
47
|
+
catch {
|
|
48
|
+
/* no old home */
|
|
49
|
+
}
|
|
50
|
+
return '~/.agents/open-artifacts';
|
|
51
|
+
}
|
|
52
|
+
/** Where the connectors are configured. */
|
|
53
|
+
export function connectorsFile(env = process.env) {
|
|
54
|
+
const named = envOrLegacy(env, 'OPEN_ARTIFACTS_CONNECTORS');
|
|
55
|
+
if (named)
|
|
56
|
+
return resolve(expandHome(named));
|
|
57
|
+
return join(resolve(expandHome(envOrLegacy(env, 'OPEN_ARTIFACTS_HOME') || defaultHome())), 'connectors.json');
|
|
58
|
+
}
|
|
59
|
+
/** Replaces `${NAME}` and `${NAME:-default}` with the environment's values. */
|
|
60
|
+
export function expandVariables(text, env = process.env) {
|
|
61
|
+
return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_match, name, fallback) => env[name] ?? fallback ?? '');
|
|
62
|
+
}
|
|
63
|
+
const isRecord = (value) => typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
64
|
+
function stringMap(value, what, env) {
|
|
65
|
+
if (value === undefined)
|
|
66
|
+
return undefined;
|
|
67
|
+
if (!isRecord(value))
|
|
68
|
+
throw new Error(`${what} must be an object of strings.`);
|
|
69
|
+
const out = {};
|
|
70
|
+
for (const [key, item] of Object.entries(value)) {
|
|
71
|
+
if (typeof item !== 'string')
|
|
72
|
+
throw new Error(`${what}.${key} must be a string.`);
|
|
73
|
+
out[key] = expandVariables(item, env);
|
|
74
|
+
}
|
|
75
|
+
return out;
|
|
76
|
+
}
|
|
77
|
+
/** Checks and expands one server's entry; throws a readable message when it is unusable. */
|
|
78
|
+
export function connectorConfigOf(value, env = process.env) {
|
|
79
|
+
if (!isRecord(value))
|
|
80
|
+
throw new Error('A server entry must be an object.');
|
|
81
|
+
const disabled = value.disabled === true ? { disabled: true } : {};
|
|
82
|
+
if (typeof value.command === 'string' && value.command) {
|
|
83
|
+
if (value.args !== undefined && (!Array.isArray(value.args) || value.args.some((arg) => typeof arg !== 'string')))
|
|
84
|
+
throw new Error('args must be a list of strings.');
|
|
85
|
+
if (value.cwd !== undefined && typeof value.cwd !== 'string')
|
|
86
|
+
throw new Error('cwd must be a string.');
|
|
87
|
+
const envVars = stringMap(value.env, 'env', env);
|
|
88
|
+
return {
|
|
89
|
+
command: expandVariables(value.command, env),
|
|
90
|
+
...(Array.isArray(value.args) ? { args: value.args.map((arg) => expandVariables(arg, env)) } : {}),
|
|
91
|
+
...(envVars ? { env: envVars } : {}),
|
|
92
|
+
...(typeof value.cwd === 'string' ? { cwd: resolve(expandHome(expandVariables(value.cwd, env))) } : {}),
|
|
93
|
+
...disabled,
|
|
94
|
+
};
|
|
95
|
+
}
|
|
96
|
+
if (typeof value.url === 'string' && value.url) {
|
|
97
|
+
if (value.type === 'sse')
|
|
98
|
+
throw new Error('The older SSE transport is not supported; use the server\'s Streamable HTTP endpoint.');
|
|
99
|
+
const url = expandVariables(value.url, env);
|
|
100
|
+
let parsed;
|
|
101
|
+
try {
|
|
102
|
+
parsed = new URL(url);
|
|
103
|
+
}
|
|
104
|
+
catch {
|
|
105
|
+
throw new Error(`Not a URL: ${url}`);
|
|
106
|
+
}
|
|
107
|
+
if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')
|
|
108
|
+
throw new Error(`Not an http(s) URL: ${url}`);
|
|
109
|
+
const headers = stringMap(value.headers, 'headers', env);
|
|
110
|
+
return { url, ...(headers ? { headers } : {}), ...(typeof value.type === 'string' ? { type: value.type } : {}), ...disabled };
|
|
111
|
+
}
|
|
112
|
+
throw new Error('A server needs a command (stdio) or a url (Streamable HTTP).');
|
|
113
|
+
}
|
|
114
|
+
/** Reads the file's servers. A missing file has none; a broken one throws. */
|
|
115
|
+
export function parseConnectors(text, env = process.env) {
|
|
116
|
+
const data = JSON.parse(text);
|
|
117
|
+
if (!isRecord(data))
|
|
118
|
+
throw new Error('connectors.json must hold an object.');
|
|
119
|
+
const servers = data.mcpServers ?? {};
|
|
120
|
+
if (!isRecord(servers))
|
|
121
|
+
throw new Error('mcpServers must be an object.');
|
|
122
|
+
const out = new Map();
|
|
123
|
+
for (const [name, value] of Object.entries(servers)) {
|
|
124
|
+
try {
|
|
125
|
+
const config = connectorConfigOf(value, env);
|
|
126
|
+
out.set(name, { config, key: JSON.stringify(config) });
|
|
127
|
+
}
|
|
128
|
+
catch (error) {
|
|
129
|
+
out.set(name, { key: `error:${JSON.stringify(value)}`, error: error instanceof Error ? error.message : String(error) });
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return out;
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
135
|
+
* The connectors of this computer: configuration, running clients, and the two calls pages make. The daemon keeps one
|
|
136
|
+
* for every page and type; a type server running without a daemon keeps its own.
|
|
137
|
+
*/
|
|
138
|
+
export class ConnectorsHost {
|
|
139
|
+
file;
|
|
140
|
+
log;
|
|
141
|
+
clientInfo;
|
|
142
|
+
entries = new Map();
|
|
143
|
+
clients = new Map();
|
|
144
|
+
/** `mtime:size` of the file last read (`missing` when absent). */
|
|
145
|
+
stamp = null;
|
|
146
|
+
fileError = null;
|
|
147
|
+
onExit = () => {
|
|
148
|
+
for (const { client } of this.clients.values())
|
|
149
|
+
if (client instanceof StdioMcpClient)
|
|
150
|
+
client.killNow();
|
|
151
|
+
};
|
|
152
|
+
constructor(options = {}) {
|
|
153
|
+
this.file = options.file ?? connectorsFile();
|
|
154
|
+
this.log = options.log ?? (() => undefined);
|
|
155
|
+
this.clientInfo = options.clientInfo;
|
|
156
|
+
process.on('exit', this.onExit);
|
|
157
|
+
}
|
|
158
|
+
/** Reads the file again when it changed, and stops clients whose server changed or went. */
|
|
159
|
+
refresh() {
|
|
160
|
+
let stamp = 'missing';
|
|
161
|
+
try {
|
|
162
|
+
const stats = statSync(this.file);
|
|
163
|
+
stamp = `${stats.mtimeMs}:${stats.size}`;
|
|
164
|
+
}
|
|
165
|
+
catch {
|
|
166
|
+
// No file: no connectors.
|
|
167
|
+
}
|
|
168
|
+
if (stamp === this.stamp)
|
|
169
|
+
return;
|
|
170
|
+
this.stamp = stamp;
|
|
171
|
+
let next = new Map();
|
|
172
|
+
this.fileError = null;
|
|
173
|
+
if (stamp !== 'missing') {
|
|
174
|
+
try {
|
|
175
|
+
next = parseConnectors(readFileSync(this.file, 'utf8'));
|
|
176
|
+
}
|
|
177
|
+
catch (error) {
|
|
178
|
+
this.fileError = `${this.file} could not be read: ${error instanceof Error ? error.message : String(error)}`;
|
|
179
|
+
this.log(`connectors: ${this.fileError}`);
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
this.entries = next;
|
|
183
|
+
for (const [name, running] of [...this.clients]) {
|
|
184
|
+
if (next.get(name)?.key === running.key)
|
|
185
|
+
continue;
|
|
186
|
+
this.clients.delete(name);
|
|
187
|
+
void running.client.close();
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
/** The client of a usable, enabled server; throws `server_not_connected` otherwise. */
|
|
191
|
+
clientOf(server) {
|
|
192
|
+
this.refresh();
|
|
193
|
+
const entry = this.entries.get(server);
|
|
194
|
+
if (!entry) {
|
|
195
|
+
const why = this.fileError ?? `No connector named "${server}" is set up in ${this.file}.`;
|
|
196
|
+
throw new McpError('server_not_connected', why);
|
|
197
|
+
}
|
|
198
|
+
if (entry.error !== undefined)
|
|
199
|
+
throw new McpError('server_not_connected', `${server}: ${entry.error}`);
|
|
200
|
+
if (entry.config.disabled)
|
|
201
|
+
throw new McpError('server_not_connected', `${server} is turned off in ${this.file}.`);
|
|
202
|
+
const running = this.clients.get(server);
|
|
203
|
+
if (running?.key === entry.key)
|
|
204
|
+
return running.client;
|
|
205
|
+
const config = entry.config;
|
|
206
|
+
const client = 'command' in config
|
|
207
|
+
? new StdioMcpClient(server, config, { log: this.log, ...(this.clientInfo ? { clientInfo: this.clientInfo } : {}) })
|
|
208
|
+
: new HttpMcpClient(server, config, this.clientInfo ? { clientInfo: this.clientInfo } : {});
|
|
209
|
+
this.clients.set(server, { key: entry.key, client });
|
|
210
|
+
return client;
|
|
211
|
+
}
|
|
212
|
+
/** The configured server names. */
|
|
213
|
+
names() {
|
|
214
|
+
this.refresh();
|
|
215
|
+
return [...this.entries.keys()];
|
|
216
|
+
}
|
|
217
|
+
/** Calls a tool of `server`. */
|
|
218
|
+
callTool(server, tool, args, control = {}) {
|
|
219
|
+
try {
|
|
220
|
+
return this.clientOf(server).callTool(tool, args, control);
|
|
221
|
+
}
|
|
222
|
+
catch (error) {
|
|
223
|
+
return Promise.reject(error);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
/** Every server (or only `server`, when it is set up), connected ones with their tools. */
|
|
227
|
+
async listTools(server) {
|
|
228
|
+
this.refresh();
|
|
229
|
+
const names = server === undefined ? [...this.entries.keys()] : this.entries.has(server) ? [server] : [];
|
|
230
|
+
return Promise.all(names.map((name) => this.describe(name)));
|
|
231
|
+
}
|
|
232
|
+
async describe(name) {
|
|
233
|
+
const entry = this.entries.get(name);
|
|
234
|
+
if (!entry || entry.error !== undefined)
|
|
235
|
+
return { server: name, kind: 'connector', authStatus: 'error', error: entry?.error ?? 'Not set up.' };
|
|
236
|
+
if (entry.config.disabled)
|
|
237
|
+
return { server: name, kind: 'connector', authStatus: 'disconnected' };
|
|
238
|
+
try {
|
|
239
|
+
const tools = await this.clientOf(name).listTools({ timeoutMs: LIST_TIMEOUT_MS, signal: AbortSignal.timeout(LIST_TIMEOUT_MS + 5000) });
|
|
240
|
+
return { server: name, kind: 'connector', authStatus: 'connected', tools };
|
|
241
|
+
}
|
|
242
|
+
catch (error) {
|
|
243
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
244
|
+
if (error instanceof McpError && error.code === 'needs_reauth')
|
|
245
|
+
return { server: name, kind: 'connector', authStatus: 'needs_auth', error: message };
|
|
246
|
+
return { server: name, kind: 'connector', authStatus: 'error', error: message };
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
/** Stops every server this host started. */
|
|
250
|
+
async close() {
|
|
251
|
+
process.off('exit', this.onExit);
|
|
252
|
+
const running = [...this.clients.values()];
|
|
253
|
+
this.clients.clear();
|
|
254
|
+
await Promise.all(running.map(({ client }) => client.close()));
|
|
255
|
+
}
|
|
256
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connectors of a type server that has a daemon: every call goes to the daemon's one {@link ConnectorsHost}
|
|
3
|
+
* (Type API `mcp.tools` and `mcp.call`), so a connector runs once for the whole computer, whichever type and page uses
|
|
4
|
+
* it. A daemon too old to answer those routes hands the calls to a host of the type server's own.
|
|
5
|
+
*/
|
|
6
|
+
import type { McpToolResult } from '@openartifactsai/runtime/capabilities';
|
|
7
|
+
import type { TypeApiMcpCallRequest, TypeApiMcpToolsResponse } from '@openartifactsai/protocol/page-mcp';
|
|
8
|
+
import { type ConnectorServerEntry, type ConnectorsHost } from './connectors.js';
|
|
9
|
+
import { type McpRequestControl } from './mcp-client.js';
|
|
10
|
+
/** What a type server needs of its connectors: a {@link ConnectorsHost}, or one that asks the daemon. */
|
|
11
|
+
export interface ConnectorsLike {
|
|
12
|
+
/** `connectors.json` (what sits beside it, such as the shares file, is found from it). */
|
|
13
|
+
readonly file: string;
|
|
14
|
+
listTools(server?: string): Promise<ConnectorServerEntry[]>;
|
|
15
|
+
callTool(server: string, tool: string, args: Record<string, unknown>, control?: McpRequestControl): Promise<McpToolResult>;
|
|
16
|
+
close(): Promise<void>;
|
|
17
|
+
}
|
|
18
|
+
/** The two Type API calls {@link DaemonConnectors} makes (`TypeApi.mcpTools`, `TypeApi.mcpCall`). */
|
|
19
|
+
export interface DaemonMcpApi {
|
|
20
|
+
mcpTools(server?: string): Promise<TypeApiMcpToolsResponse>;
|
|
21
|
+
mcpCall(body: TypeApiMcpCallRequest, signal?: AbortSignal): Promise<unknown>;
|
|
22
|
+
}
|
|
23
|
+
/** The daemon's connector calls, when it offers them (a Type API client that is connected); else null. */
|
|
24
|
+
export declare function daemonMcpApiOf(daemon: unknown): DaemonMcpApi | null;
|
|
25
|
+
/** Connectors through the daemon; {@link fallback} when the daemon does not know the routes (`not_found`). */
|
|
26
|
+
export declare class DaemonConnectors implements ConnectorsLike {
|
|
27
|
+
#private;
|
|
28
|
+
readonly file: string;
|
|
29
|
+
constructor(api: DaemonMcpApi, fallback: () => ConnectorsHost, file?: string);
|
|
30
|
+
listTools(server?: string): Promise<ConnectorServerEntry[]>;
|
|
31
|
+
callTool(server: string, tool: string, args: Record<string, unknown>, control?: McpRequestControl): Promise<McpToolResult>;
|
|
32
|
+
/** The connectors are the daemon's: nothing of this server's runs (a fallback host is closed by its owner). */
|
|
33
|
+
close(): Promise<void>;
|
|
34
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The connectors of a type server that has a daemon: every call goes to the daemon's one {@link ConnectorsHost}
|
|
3
|
+
* (Type API `mcp.tools` and `mcp.call`), so a connector runs once for the whole computer, whichever type and page uses
|
|
4
|
+
* it. A daemon too old to answer those routes hands the calls to a host of the type server's own.
|
|
5
|
+
*/
|
|
6
|
+
import { connectorsFile } from "./connectors.js";
|
|
7
|
+
import { McpError } from "./mcp-client.js";
|
|
8
|
+
/** The daemon's connector calls, when it offers them (a Type API client that is connected); else null. */
|
|
9
|
+
export function daemonMcpApiOf(daemon) {
|
|
10
|
+
const api = daemon;
|
|
11
|
+
if (!api || api.available === false)
|
|
12
|
+
return null;
|
|
13
|
+
return typeof api.mcpTools === 'function' && typeof api.mcpCall === 'function' ? api : null;
|
|
14
|
+
}
|
|
15
|
+
const codeOf = (error) => String(error?.code ?? '');
|
|
16
|
+
/** A Type API failure as the connector failure it stands for. */
|
|
17
|
+
function connectorError(error) {
|
|
18
|
+
if (error instanceof McpError)
|
|
19
|
+
return error;
|
|
20
|
+
const code = codeOf(error);
|
|
21
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
22
|
+
const retryable = error?.retryable === true;
|
|
23
|
+
if (code === 'server_not_connected' || code === 'needs_reauth' || code === 'not_granted' || code === 'rate_limited' || code === 'upstream_error')
|
|
24
|
+
return new McpError(code, message, retryable);
|
|
25
|
+
return new McpError('upstream_error', `The Open Artifacts daemon could not run the connector call: ${message}`, true);
|
|
26
|
+
}
|
|
27
|
+
/** Connectors through the daemon; {@link fallback} when the daemon does not know the routes (`not_found`). */
|
|
28
|
+
export class DaemonConnectors {
|
|
29
|
+
file;
|
|
30
|
+
#api;
|
|
31
|
+
#fallback;
|
|
32
|
+
#old = false;
|
|
33
|
+
constructor(api, fallback, file = connectorsFile()) {
|
|
34
|
+
this.#api = api;
|
|
35
|
+
this.#fallback = fallback;
|
|
36
|
+
this.file = file;
|
|
37
|
+
}
|
|
38
|
+
async listTools(server) {
|
|
39
|
+
if (this.#old)
|
|
40
|
+
return this.#fallback().listTools(server);
|
|
41
|
+
try {
|
|
42
|
+
const answer = await this.#api.mcpTools(server);
|
|
43
|
+
return Array.isArray(answer?.servers) ? answer.servers : [];
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
if (codeOf(error) !== 'not_found')
|
|
47
|
+
throw connectorError(error);
|
|
48
|
+
this.#old = true;
|
|
49
|
+
return this.#fallback().listTools(server);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
async callTool(server, tool, args, control = {}) {
|
|
53
|
+
if (this.#old)
|
|
54
|
+
return this.#fallback().callTool(server, tool, args, control);
|
|
55
|
+
const { signal } = control;
|
|
56
|
+
if (signal?.aborted)
|
|
57
|
+
throw signal.reason;
|
|
58
|
+
try {
|
|
59
|
+
const body = { server, tool, args, ...(control.timeoutMs === undefined ? {} : { timeoutMs: control.timeoutMs }) };
|
|
60
|
+
return (await this.#api.mcpCall(body, signal));
|
|
61
|
+
}
|
|
62
|
+
catch (error) {
|
|
63
|
+
if (signal?.aborted)
|
|
64
|
+
throw signal.reason;
|
|
65
|
+
if (codeOf(error) !== 'not_found')
|
|
66
|
+
throw connectorError(error);
|
|
67
|
+
this.#old = true;
|
|
68
|
+
return this.#fallback().callTool(server, tool, args, control);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
/** The connectors are the daemon's: nothing of this server's runs (a fallback host is closed by its owner). */
|
|
72
|
+
async close() { }
|
|
73
|
+
}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connectors (MCP servers set up in `connectors.json`) and the small MCP client that talks to them. The daemon runs
|
|
3
|
+
* one {@link ConnectorsHost} for the whole computer; a type server that runs without a daemon starts its own.
|
|
4
|
+
*/
|
|
5
|
+
export * from './connectors.js';
|
|
6
|
+
export * from './mcp-client.js';
|
|
7
|
+
export * from './daemon-connectors.js';
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connectors (MCP servers set up in `connectors.json`) and the small MCP client that talks to them. The daemon runs
|
|
3
|
+
* one {@link ConnectorsHost} for the whole computer; a type server that runs without a daemon starts its own.
|
|
4
|
+
*/
|
|
5
|
+
export * from "./connectors.js";
|
|
6
|
+
export * from "./mcp-client.js";
|
|
7
|
+
export * from "./daemon-connectors.js";
|
|
@@ -0,0 +1,157 @@
|
|
|
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 type { JsonRecord, McpErrorCode, McpToolInfo, McpToolResult } from '@openartifactsai/runtime/capabilities';
|
|
13
|
+
/** How long one request may take by default, and at most, ms (the editor runtime's `mcp` says the same numbers). */
|
|
14
|
+
export declare const MCP_CALL_TIMEOUT: {
|
|
15
|
+
readonly defaultMs: 120000;
|
|
16
|
+
readonly maxMs: 600000;
|
|
17
|
+
};
|
|
18
|
+
/** One tool as a connector lists it: what pages use, plus its hints and output schema when it gives them. */
|
|
19
|
+
export interface ConnectorToolInfo extends McpToolInfo {
|
|
20
|
+
outputSchema?: JsonRecord;
|
|
21
|
+
/** MCP `ToolAnnotations` (`readOnlyHint`, `destructiveHint`, ...). */
|
|
22
|
+
annotations?: JsonRecord;
|
|
23
|
+
}
|
|
24
|
+
/** The MCP revision this client speaks. */
|
|
25
|
+
export declare const MCP_PROTOCOL_VERSION = "2025-06-18";
|
|
26
|
+
/** How long starting a server and its `initialize` may take, ms. */
|
|
27
|
+
export declare const MCP_CONNECT_TIMEOUT_MS = 60000;
|
|
28
|
+
/** A failed connector call, with the capability's code. */
|
|
29
|
+
export declare class McpError extends Error {
|
|
30
|
+
readonly code: McpErrorCode;
|
|
31
|
+
readonly retryable?: boolean;
|
|
32
|
+
constructor(code: McpErrorCode, message: string, retryable?: boolean);
|
|
33
|
+
}
|
|
34
|
+
/** How one request may end early. */
|
|
35
|
+
export interface McpRequestControl {
|
|
36
|
+
signal?: AbortSignal;
|
|
37
|
+
/** Default {@link MCP_CALL_TIMEOUT}.defaultMs. */
|
|
38
|
+
timeoutMs?: number;
|
|
39
|
+
}
|
|
40
|
+
/** Who this client says it is in `initialize`. */
|
|
41
|
+
export interface McpClientInfo {
|
|
42
|
+
name: string;
|
|
43
|
+
version: string;
|
|
44
|
+
}
|
|
45
|
+
type JsonRpcId = number | string;
|
|
46
|
+
interface JsonRpcMessage {
|
|
47
|
+
jsonrpc: '2.0';
|
|
48
|
+
id?: JsonRpcId | null;
|
|
49
|
+
method?: string;
|
|
50
|
+
params?: unknown;
|
|
51
|
+
result?: unknown;
|
|
52
|
+
error?: {
|
|
53
|
+
code: number;
|
|
54
|
+
message: string;
|
|
55
|
+
data?: unknown;
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* The transport-independent part: request ids, answers, deadlines,
|
|
60
|
+
* cancellation, the handshake and the two tool methods.
|
|
61
|
+
*/
|
|
62
|
+
export declare abstract class McpClient {
|
|
63
|
+
/** The connector's name in the configuration. */
|
|
64
|
+
readonly name: string;
|
|
65
|
+
protected readonly clientInfo: McpClientInfo;
|
|
66
|
+
/** The protocol version the server agreed to. */
|
|
67
|
+
protected protocolVersion: string | null;
|
|
68
|
+
private nextId;
|
|
69
|
+
private readonly pending;
|
|
70
|
+
private ready;
|
|
71
|
+
private tools;
|
|
72
|
+
constructor(name: string, clientInfo?: McpClientInfo);
|
|
73
|
+
/** Starts the transport (spawns the process); a no-op where nothing has to start. */
|
|
74
|
+
protected abstract open(): Promise<void>;
|
|
75
|
+
/**
|
|
76
|
+
* Sends one message. Answers that come back with it (HTTP) go to
|
|
77
|
+
* {@link deliver} before it resolves; `signal` ends a request it carries.
|
|
78
|
+
*/
|
|
79
|
+
protected abstract transmit(message: JsonRpcMessage, signal: AbortSignal): Promise<void>;
|
|
80
|
+
/** Whether {@link transmit} resolving means every answer to it was delivered (HTTP). */
|
|
81
|
+
protected abstract readonly answersInline: boolean;
|
|
82
|
+
/** Stops the transport and fails what is pending. */
|
|
83
|
+
abstract close(): Promise<void>;
|
|
84
|
+
/** Whether the handshake is done (or under way). */
|
|
85
|
+
get connected(): boolean;
|
|
86
|
+
/** Fails every pending request and forgets the session: the next call connects again. */
|
|
87
|
+
protected reset(error: McpError): void;
|
|
88
|
+
/** Starts the server and runs the handshake once; concurrent callers share it. */
|
|
89
|
+
connect(signal?: AbortSignal): Promise<void>;
|
|
90
|
+
private handshake;
|
|
91
|
+
/** Every tool of the server, all pages of `tools/list` (kept until the server says the list changed). */
|
|
92
|
+
listTools(control?: McpRequestControl): Promise<ConnectorToolInfo[]>;
|
|
93
|
+
/** Calls one tool. */
|
|
94
|
+
callTool(tool: string, args: Record<string, unknown>, control?: McpRequestControl): Promise<McpToolResult>;
|
|
95
|
+
/** Connects, runs `task`, and once more after an HTTP session expired. */
|
|
96
|
+
private session;
|
|
97
|
+
/** Sends a request and waits for its answer, its deadline or its signal. */
|
|
98
|
+
protected request(method: string, params: unknown, control?: McpRequestControl): Promise<unknown>;
|
|
99
|
+
/** Sends a notification. */
|
|
100
|
+
protected notify(method: string, params?: unknown): Promise<void>;
|
|
101
|
+
/** Handles one message from the server: an answer, a request or a notification. */
|
|
102
|
+
protected deliver(message: unknown): void;
|
|
103
|
+
/** Answers a request from the server: `ping` and `roots/list`; anything else is not supported. */
|
|
104
|
+
private answer;
|
|
105
|
+
}
|
|
106
|
+
/** How to start a stdio server. */
|
|
107
|
+
export interface StdioServerConfig {
|
|
108
|
+
command: string;
|
|
109
|
+
args?: string[];
|
|
110
|
+
/** Added to this process's environment. */
|
|
111
|
+
env?: Record<string, string>;
|
|
112
|
+
cwd?: string;
|
|
113
|
+
}
|
|
114
|
+
/** A server this process starts and talks to over its stdin and stdout. */
|
|
115
|
+
export declare class StdioMcpClient extends McpClient {
|
|
116
|
+
protected readonly answersInline = false;
|
|
117
|
+
private readonly config;
|
|
118
|
+
private readonly log;
|
|
119
|
+
private child;
|
|
120
|
+
private stderr;
|
|
121
|
+
constructor(name: string, config: StdioServerConfig, options?: {
|
|
122
|
+
log?: (line: string) => void;
|
|
123
|
+
clientInfo?: McpClientInfo;
|
|
124
|
+
});
|
|
125
|
+
/** The running process's id, if any (tests). */
|
|
126
|
+
get pid(): number | undefined;
|
|
127
|
+
protected open(): Promise<void>;
|
|
128
|
+
protected transmit(message: JsonRpcMessage): Promise<void>;
|
|
129
|
+
close(): Promise<void>;
|
|
130
|
+
/** Kills the process at once (this process is exiting: synchronous, nothing after this runs). */
|
|
131
|
+
killNow(): void;
|
|
132
|
+
}
|
|
133
|
+
/** Where a Streamable HTTP server is. */
|
|
134
|
+
export interface HttpServerConfig {
|
|
135
|
+
url: string;
|
|
136
|
+
/** Sent with every request (e.g. `Authorization`). */
|
|
137
|
+
headers?: Record<string, string>;
|
|
138
|
+
}
|
|
139
|
+
/** A server reached over Streamable HTTP. */
|
|
140
|
+
export declare class HttpMcpClient extends McpClient {
|
|
141
|
+
protected readonly answersInline = true;
|
|
142
|
+
private readonly config;
|
|
143
|
+
private sessionId;
|
|
144
|
+
constructor(name: string, config: HttpServerConfig, options?: {
|
|
145
|
+
clientInfo?: McpClientInfo;
|
|
146
|
+
});
|
|
147
|
+
protected open(): Promise<void>;
|
|
148
|
+
private headers;
|
|
149
|
+
protected transmit(message: JsonRpcMessage, signal: AbortSignal): Promise<void>;
|
|
150
|
+
/**
|
|
151
|
+
* Reads an event stream until the answer to `id` came (then the rest is cancelled) or the stream ends; whatever is
|
|
152
|
+
* left at the end is read too, even an unterminated last line.
|
|
153
|
+
*/
|
|
154
|
+
private readStream;
|
|
155
|
+
close(): Promise<void>;
|
|
156
|
+
}
|
|
157
|
+
export {};
|