chat-recall 0.7.38 → 0.7.40
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/README.md +22 -14
- package/dist/cli.js +833 -425
- package/dist/cli.js.map +1 -1
- package/dist/install-hooks.d.ts +11 -3
- package/dist/install-hooks.d.ts.map +1 -1
- package/dist/install-hooks.js +10 -5
- package/dist/install-hooks.js.map +1 -1
- package/dist/kit-store.d.ts +5 -4
- package/dist/kit-store.d.ts.map +1 -1
- package/dist/kit-store.js +6 -6
- package/dist/kit-store.js.map +1 -1
- package/dist/mcp-host.d.ts +50 -0
- package/dist/mcp-host.d.ts.map +1 -0
- package/dist/mcp-host.js +111 -0
- package/dist/mcp-host.js.map +1 -0
- package/dist/mcp.js +1057 -993
- package/dist/mcp.js.map +1 -1
- package/dist/memory-guard.d.ts +41 -0
- package/dist/memory-guard.d.ts.map +1 -0
- package/dist/memory-guard.js +56 -0
- package/dist/memory-guard.js.map +1 -0
- package/dist/message-hook.js +1 -1
- package/dist/scan-worker.js +8 -5
- package/dist/service-installer.d.ts +13 -0
- package/dist/service-installer.d.ts.map +1 -1
- package/dist/service-installer.js +19 -7
- package/dist/service-installer.js.map +1 -1
- package/dist/session-exit.d.ts +50 -0
- package/dist/session-exit.d.ts.map +1 -0
- package/dist/session-exit.js +70 -0
- package/dist/session-exit.js.map +1 -0
- package/dist/star-nudge.js +1 -1
- package/dist/sync-client.d.ts +16 -2
- package/dist/sync-client.d.ts.map +1 -1
- package/dist/sync-client.js +47 -10
- package/dist/sync-client.js.map +1 -1
- package/dist/vendor/mcp-kit/VERSION +1 -0
- package/dist/vendor/mcp-kit/host-main.d.ts +2 -0
- package/dist/vendor/mcp-kit/host-main.js +3 -0
- package/dist/vendor/mcp-kit/host-plain.d.ts +56 -0
- package/dist/vendor/mcp-kit/host-plain.js +502 -0
- package/dist/vendor/mcp-kit/host.d.ts +32 -0
- package/dist/vendor/mcp-kit/host.js +43 -0
- package/dist/vendor/mcp-kit/registry.d.ts +79 -0
- package/dist/vendor/mcp-kit/registry.js +194 -0
- package/dist/watch.js +78 -26
- package/package.json +2 -2
- package/dist/mcp-relay.d.ts +0 -3
- package/dist/mcp-relay.d.ts.map +0 -1
- package/dist/mcp-relay.js +0 -472
- package/dist/mcp-relay.js.map +0 -1
- package/dist/mcp-socket.d.ts +0 -98
- package/dist/mcp-socket.d.ts.map +0 -1
- package/dist/mcp-socket.js +0 -249
- package/dist/mcp-socket.js.map +0 -1
- package/dist/relay-lifecycle.d.ts +0 -92
- package/dist/relay-lifecycle.d.ts.map +0 -1
- package/dist/relay-lifecycle.js +0 -290
- package/dist/relay-lifecycle.js.map +0 -1
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { type Host } from './host.js';
|
|
2
|
+
import { type HostConfig, type ServerSpec } from './registry.js';
|
|
3
|
+
export declare const USAGE = "mcp-kit-host runs the servers that need the files of this machine once, and serves them over HTTP on 127.0.0.1.\n\n mcp-kit-host [--config <file.json>]\n mcp-kit-host --server <name>=<command>[,<arg>...] [--server ...] [--port <n>] [--host <address>]\n mcp-kit-host install | status | uninstall\n\nA config file is JSON: {\"port\": 7717, \"servers\": [{\"name\": \"codeindex\", \"command\": \"codeindex\"}]}\nA client holds the URL of each server: http://127.0.0.1:<port>/<name>\n\nA product adds its server to the config and then calls `install` once, or calls it again when a run of this\nmachine has not kept the host yet. `install` writes the unit of the service, loads it, and leaves the config\nalone; `uninstall` stops the service and keeps the config.";
|
|
4
|
+
/** The options of a run of the command. */
|
|
5
|
+
export interface HostCommand {
|
|
6
|
+
servers: ServerSpec[];
|
|
7
|
+
port: number;
|
|
8
|
+
host: string;
|
|
9
|
+
config?: string;
|
|
10
|
+
}
|
|
11
|
+
/** Reads `--server name=command[,arg...]`, `--port`, `--host` and `--config`. Throws on a bad value. */
|
|
12
|
+
export declare function parseHostArgs(argv: string[], read?: (path: string) => string): HostCommand;
|
|
13
|
+
/** The default end of a run: a signal of the operating system. */
|
|
14
|
+
export declare function untilSignal(): Promise<void>;
|
|
15
|
+
export interface PlainHostOptions {
|
|
16
|
+
config: Pick<HostConfig, 'servers' | 'port' | 'host'>;
|
|
17
|
+
/** A line for each server started, and for each child that stops. */
|
|
18
|
+
log?: (line: string) => void;
|
|
19
|
+
}
|
|
20
|
+
export interface PlainHost {
|
|
21
|
+
/** The base URL of the host, for example `http://127.0.0.1:7717`. */
|
|
22
|
+
readonly url: string;
|
|
23
|
+
/** The URL of one server, for example `http://127.0.0.1:7717/codeindex`. */
|
|
24
|
+
urlOf(name: string): string;
|
|
25
|
+
readonly sessions: number;
|
|
26
|
+
readonly children: number;
|
|
27
|
+
close(): Promise<void>;
|
|
28
|
+
}
|
|
29
|
+
/**
|
|
30
|
+
* Start the host. The caller registers the returned URLs in the clients, and calls `close` when the process stops.
|
|
31
|
+
*/
|
|
32
|
+
export declare function startPlainHost(options: PlainHostOptions): Promise<PlainHost>;
|
|
33
|
+
/** The parts of a run that a test replaces. */
|
|
34
|
+
export interface RunDeps {
|
|
35
|
+
start?: typeof startPlainHost;
|
|
36
|
+
/** The promise that ends the run. The default resolves on SIGINT or SIGTERM. */
|
|
37
|
+
wait?: () => Promise<void>;
|
|
38
|
+
say?: (line: string) => void;
|
|
39
|
+
fail?: (line: string) => void;
|
|
40
|
+
/** The machine: its home, its commands and its files. */
|
|
41
|
+
host?: Host;
|
|
42
|
+
platform?: NodeJS.Platform;
|
|
43
|
+
/** The program of the host that the unit runs. The default is this file. */
|
|
44
|
+
main?: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* `install`, `status` and `uninstall` of the one service per machine.
|
|
48
|
+
*
|
|
49
|
+
* `install` reads the config of the machine, writes the unit if its text changed, and loads it. What it prints a
|
|
50
|
+
* person can paste: none of it is a token, and the config holds no token either.
|
|
51
|
+
*/
|
|
52
|
+
export declare function runService(command: 'install' | 'status' | 'uninstall', deps: RunDeps, say: (line: string) => void, fail: (line: string) => void): number;
|
|
53
|
+
/** Runs the command and returns its exit code. It serves until `wait` resolves, then closes the host. */
|
|
54
|
+
export declare function runHostCommand(argv: string[], deps?: RunDeps): Promise<number>;
|
|
55
|
+
/** The home of the person, for a run that names no file. */
|
|
56
|
+
export declare function homeOf(env?: NodeJS.ProcessEnv): string;
|
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The host that runs the servers of this machine, with no dependency other than Node.
|
|
3
|
+
*
|
|
4
|
+
* It reads the one file that the products write (`~/.config/mcp-kit/host.json`), starts every server as a child
|
|
5
|
+
* process over stdio, and serves each of them over Streamable HTTP on the loopback address. A client then holds a
|
|
6
|
+
* URL for a local server, and a session of that client starts no copy of the server: the host starts each server
|
|
7
|
+
* once per machine and answers the sessions from that one child.
|
|
8
|
+
*
|
|
9
|
+
* The file imports only Node's own modules and the two files of this folder (`registry.js`, `host.js`), because a
|
|
10
|
+
* product vendors the compiled folder instead of installing this package, which needs the MCP SDK.
|
|
11
|
+
*/
|
|
12
|
+
import { spawn } from 'node:child_process';
|
|
13
|
+
import { randomUUID } from 'node:crypto';
|
|
14
|
+
import { readFileSync } from 'node:fs';
|
|
15
|
+
import { createServer } from 'node:http';
|
|
16
|
+
import { homedir } from 'node:os';
|
|
17
|
+
import { fileURLToPath } from 'node:url';
|
|
18
|
+
import { systemHost } from './host.js';
|
|
19
|
+
import { DEFAULT_PORT, LOOPBACK, configPath, hostArgv, hostStatus, installHost, readConfig, uninstallHost, } from './registry.js';
|
|
20
|
+
const MAX_BODY = 8 * 1024 * 1024;
|
|
21
|
+
const PROTOCOL = '2025-06-18';
|
|
22
|
+
export const USAGE = `mcp-kit-host runs the servers that need the files of this machine once, and serves them over HTTP on ${LOOPBACK}.
|
|
23
|
+
|
|
24
|
+
mcp-kit-host [--config <file.json>]
|
|
25
|
+
mcp-kit-host --server <name>=<command>[,<arg>...] [--server ...] [--port <n>] [--host <address>]
|
|
26
|
+
mcp-kit-host install | status | uninstall
|
|
27
|
+
|
|
28
|
+
A config file is JSON: {"port": ${DEFAULT_PORT}, "servers": [{"name": "codeindex", "command": "codeindex"}]}
|
|
29
|
+
A client holds the URL of each server: http://${LOOPBACK}:<port>/<name>
|
|
30
|
+
|
|
31
|
+
A product adds its server to the config and then calls \`install\` once, or calls it again when a run of this
|
|
32
|
+
machine has not kept the host yet. \`install\` writes the unit of the service, loads it, and leaves the config
|
|
33
|
+
alone; \`uninstall\` stops the service and keeps the config.`;
|
|
34
|
+
function parseServer(text) {
|
|
35
|
+
const at = text.indexOf('=');
|
|
36
|
+
if (at < 1)
|
|
37
|
+
throw new Error(`a server is name=command[,arg...], not ${text}`);
|
|
38
|
+
const [bin, ...rest] = text.slice(at + 1).split(',');
|
|
39
|
+
if (!bin)
|
|
40
|
+
throw new Error(`a server needs a command: ${text}`);
|
|
41
|
+
return { name: text.slice(0, at), command: bin, args: rest.length > 0 ? rest : undefined };
|
|
42
|
+
}
|
|
43
|
+
/** Reads `--server name=command[,arg...]`, `--port`, `--host` and `--config`. Throws on a bad value. */
|
|
44
|
+
export function parseHostArgs(argv, read = (p) => readFileSync(p, 'utf8')) {
|
|
45
|
+
const command = { servers: [], port: DEFAULT_PORT, host: LOOPBACK };
|
|
46
|
+
for (let i = 0; i < argv.length; i += 1) {
|
|
47
|
+
const flag = argv[i];
|
|
48
|
+
if (flag === '--server') {
|
|
49
|
+
const text = argv[i + 1];
|
|
50
|
+
i += 1;
|
|
51
|
+
if (!text)
|
|
52
|
+
throw new Error('--server needs a value, such as codeindex=codeindex');
|
|
53
|
+
command.servers.push(parseServer(text));
|
|
54
|
+
}
|
|
55
|
+
else if (flag === '--port') {
|
|
56
|
+
const text = argv[i + 1];
|
|
57
|
+
i += 1;
|
|
58
|
+
const port = Number(text);
|
|
59
|
+
if (!Number.isInteger(port) || port < 0)
|
|
60
|
+
throw new Error(`--port needs a number, not ${text}`);
|
|
61
|
+
command.port = port;
|
|
62
|
+
}
|
|
63
|
+
else if (flag === '--host') {
|
|
64
|
+
const text = argv[i + 1];
|
|
65
|
+
i += 1;
|
|
66
|
+
if (!text)
|
|
67
|
+
throw new Error('--host needs an address');
|
|
68
|
+
command.host = text;
|
|
69
|
+
}
|
|
70
|
+
else if (flag === '--config') {
|
|
71
|
+
const path = argv[i + 1];
|
|
72
|
+
i += 1;
|
|
73
|
+
if (!path)
|
|
74
|
+
throw new Error('--config needs a file');
|
|
75
|
+
const file = JSON.parse(read(path));
|
|
76
|
+
command.config = path;
|
|
77
|
+
if (file.port !== undefined)
|
|
78
|
+
command.port = file.port;
|
|
79
|
+
if (file.host !== undefined)
|
|
80
|
+
command.host = file.host;
|
|
81
|
+
if (file.servers)
|
|
82
|
+
command.servers.push(...file.servers.map((s) => ({ ...s })));
|
|
83
|
+
}
|
|
84
|
+
else {
|
|
85
|
+
throw new Error(`unknown argument ${flag}`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
if (command.servers.length === 0)
|
|
89
|
+
throw new Error('give at least one --server, or a --config with servers');
|
|
90
|
+
for (const spec of command.servers) {
|
|
91
|
+
if (!spec.name || !spec.command)
|
|
92
|
+
throw new Error(`a server needs a name and a command: ${JSON.stringify(spec)}`);
|
|
93
|
+
}
|
|
94
|
+
return command;
|
|
95
|
+
}
|
|
96
|
+
/** The default end of a run: a signal of the operating system. */
|
|
97
|
+
export function untilSignal() {
|
|
98
|
+
return new Promise((resolve) => {
|
|
99
|
+
const stop = () => {
|
|
100
|
+
process.off('SIGINT', stop);
|
|
101
|
+
process.off('SIGTERM', stop);
|
|
102
|
+
resolve();
|
|
103
|
+
};
|
|
104
|
+
process.on('SIGINT', stop);
|
|
105
|
+
process.on('SIGTERM', stop);
|
|
106
|
+
});
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* One server of this machine, as a child process that speaks JSON-RPC over stdio, one message to a line.
|
|
110
|
+
*
|
|
111
|
+
* The child starts once. Every request of every session goes to it with an id of our own, so two sessions that
|
|
112
|
+
* happen to use the same id never collide, and each answer goes back to the session that asked.
|
|
113
|
+
*/
|
|
114
|
+
class ChildServer {
|
|
115
|
+
log;
|
|
116
|
+
spec;
|
|
117
|
+
/** The answer of `initialize`, which every session receives when it starts. */
|
|
118
|
+
init;
|
|
119
|
+
proc;
|
|
120
|
+
buffer = '';
|
|
121
|
+
nextId = 0;
|
|
122
|
+
pending = new Map();
|
|
123
|
+
gone;
|
|
124
|
+
constructor(spec, log) {
|
|
125
|
+
this.log = log;
|
|
126
|
+
this.spec = spec;
|
|
127
|
+
this.proc = spawn(spec.command, spec.args ?? [], {
|
|
128
|
+
cwd: spec.cwd,
|
|
129
|
+
env: { ...process.env, ...spec.env },
|
|
130
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
131
|
+
});
|
|
132
|
+
this.proc.stdout?.setEncoding('utf8');
|
|
133
|
+
this.proc.stderr?.setEncoding('utf8');
|
|
134
|
+
this.proc.stdout?.on('data', (text) => this.read(text));
|
|
135
|
+
this.proc.stderr?.on('data', (text) => this.log(`${spec.name}: ${text.trimEnd()}`));
|
|
136
|
+
this.proc.on('exit', (code, signal) => {
|
|
137
|
+
this.gone = `the server ${spec.name} stopped (${signal ?? `exit ${code}`})`;
|
|
138
|
+
for (const [, resolve] of this.pending)
|
|
139
|
+
resolve({ jsonrpc: '2.0', error: { code: -32000, message: this.gone } });
|
|
140
|
+
this.pending.clear();
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
/** Start the child and initialize it for the whole machine. */
|
|
144
|
+
async start() {
|
|
145
|
+
this.write({
|
|
146
|
+
jsonrpc: '2.0',
|
|
147
|
+
id: this.take(),
|
|
148
|
+
method: 'initialize',
|
|
149
|
+
params: { protocolVersion: PROTOCOL, capabilities: {}, clientInfo: { name: 'mcp-kit-host', version: VERSION } },
|
|
150
|
+
});
|
|
151
|
+
const answer = await this.request('initialize', undefined, true);
|
|
152
|
+
if (answer.error)
|
|
153
|
+
throw new Error(`${this.spec.name}: ${JSON.stringify(answer.error)}`);
|
|
154
|
+
this.init = answer;
|
|
155
|
+
this.write({ jsonrpc: '2.0', method: 'notifications/initialized' });
|
|
156
|
+
}
|
|
157
|
+
/** Is the child alive? The message says why not, when it is not. */
|
|
158
|
+
stopped() {
|
|
159
|
+
return this.gone;
|
|
160
|
+
}
|
|
161
|
+
/** Send a request and wait for its answer. The id of the caller is never used. */
|
|
162
|
+
request(method, params, preallocated = false) {
|
|
163
|
+
const id = preallocated ? this.nextId : this.take();
|
|
164
|
+
if (!preallocated) {
|
|
165
|
+
this.write({ jsonrpc: '2.0', id, method, params });
|
|
166
|
+
}
|
|
167
|
+
return new Promise((resolve) => {
|
|
168
|
+
this.pending.set(id, resolve);
|
|
169
|
+
});
|
|
170
|
+
}
|
|
171
|
+
/** Send a notification. It has no answer. */
|
|
172
|
+
notify(method, params) {
|
|
173
|
+
this.write({ jsonrpc: '2.0', method, params });
|
|
174
|
+
}
|
|
175
|
+
async close() {
|
|
176
|
+
if (this.proc.exitCode !== null || this.proc.signalCode !== null)
|
|
177
|
+
return;
|
|
178
|
+
const ended = new Promise((resolve) => this.proc.once('exit', () => resolve()));
|
|
179
|
+
this.proc.kill('SIGTERM');
|
|
180
|
+
const timer = setTimeout(() => this.proc.kill('SIGKILL'), 3000);
|
|
181
|
+
await ended;
|
|
182
|
+
clearTimeout(timer);
|
|
183
|
+
}
|
|
184
|
+
take() {
|
|
185
|
+
this.nextId += 1;
|
|
186
|
+
return this.nextId;
|
|
187
|
+
}
|
|
188
|
+
write(message) {
|
|
189
|
+
if (this.gone)
|
|
190
|
+
return;
|
|
191
|
+
this.proc.stdin?.write(`${JSON.stringify(message)}\n`);
|
|
192
|
+
}
|
|
193
|
+
read(text) {
|
|
194
|
+
this.buffer += text;
|
|
195
|
+
let at = this.buffer.indexOf('\n');
|
|
196
|
+
while (at >= 0) {
|
|
197
|
+
const line = this.buffer.slice(0, at).trim();
|
|
198
|
+
this.buffer = this.buffer.slice(at + 1);
|
|
199
|
+
at = this.buffer.indexOf('\n');
|
|
200
|
+
if (line === '')
|
|
201
|
+
continue;
|
|
202
|
+
let message;
|
|
203
|
+
try {
|
|
204
|
+
message = JSON.parse(line);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
this.log(`${this.spec.name}: not JSON: ${line.slice(0, 200)}`);
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
const id = typeof message.id === 'number' ? message.id : undefined;
|
|
211
|
+
const resolve = id === undefined ? undefined : this.pending.get(id);
|
|
212
|
+
if (id !== undefined && resolve) {
|
|
213
|
+
this.pending.delete(id);
|
|
214
|
+
resolve(message);
|
|
215
|
+
continue;
|
|
216
|
+
}
|
|
217
|
+
if (typeof message.method === 'string' && message.id !== undefined) {
|
|
218
|
+
// A request from the server to its client: this host holds no tools of its own, so it refuses it.
|
|
219
|
+
this.write({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'the local host answers no request of a server' } });
|
|
220
|
+
continue;
|
|
221
|
+
}
|
|
222
|
+
if (typeof message.method === 'string')
|
|
223
|
+
this.log(`${this.spec.name}: ${message.method}`);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
const VERSION = '1.0.0';
|
|
228
|
+
function header(req, name) {
|
|
229
|
+
const value = req.headers[name];
|
|
230
|
+
return Array.isArray(value) ? value[0] : value;
|
|
231
|
+
}
|
|
232
|
+
function json(res, code, body, extra = {}) {
|
|
233
|
+
const text = JSON.stringify(body);
|
|
234
|
+
res.writeHead(code, {
|
|
235
|
+
'content-type': 'application/json',
|
|
236
|
+
'content-length': Buffer.byteLength(text),
|
|
237
|
+
...extra,
|
|
238
|
+
});
|
|
239
|
+
res.end(text);
|
|
240
|
+
}
|
|
241
|
+
function empty(res, code, extra = {}) {
|
|
242
|
+
res.writeHead(code, extra);
|
|
243
|
+
res.end();
|
|
244
|
+
}
|
|
245
|
+
function body(req) {
|
|
246
|
+
return new Promise((resolve, reject) => {
|
|
247
|
+
let size = 0;
|
|
248
|
+
const chunks = [];
|
|
249
|
+
req.on('data', (chunk) => {
|
|
250
|
+
size += chunk.length;
|
|
251
|
+
if (size > MAX_BODY) {
|
|
252
|
+
reject(new Error('the request is too large'));
|
|
253
|
+
req.destroy();
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
chunks.push(chunk);
|
|
257
|
+
});
|
|
258
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
259
|
+
req.on('error', reject);
|
|
260
|
+
});
|
|
261
|
+
}
|
|
262
|
+
/** Is the request from this machine? The host serves the loopback address only. */
|
|
263
|
+
function local(req) {
|
|
264
|
+
const name = (header(req, 'host') ?? '').split(':')[0];
|
|
265
|
+
return name === '127.0.0.1' || name === 'localhost' || name === '[::1]';
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Start the host. The caller registers the returned URLs in the clients, and calls `close` when the process stops.
|
|
269
|
+
*/
|
|
270
|
+
export async function startPlainHost(options) {
|
|
271
|
+
const log = options.log ?? (() => undefined);
|
|
272
|
+
const host = options.config.host ?? LOOPBACK;
|
|
273
|
+
const children = new Map();
|
|
274
|
+
const sessions = new Map();
|
|
275
|
+
try {
|
|
276
|
+
for (const spec of options.config.servers) {
|
|
277
|
+
if (children.has(spec.name))
|
|
278
|
+
throw new Error(`the local host has two servers named ${spec.name}`);
|
|
279
|
+
const child = new ChildServer(spec, log);
|
|
280
|
+
await child.start();
|
|
281
|
+
children.set(spec.name, child);
|
|
282
|
+
}
|
|
283
|
+
}
|
|
284
|
+
catch (error) {
|
|
285
|
+
for (const child of children.values())
|
|
286
|
+
await child.close();
|
|
287
|
+
throw error;
|
|
288
|
+
}
|
|
289
|
+
/** Forward one message of a client to the child, and answer with the message that goes back. */
|
|
290
|
+
const forward = async (child, message) => {
|
|
291
|
+
const method = typeof message.method === 'string' ? message.method : undefined;
|
|
292
|
+
if (method === undefined)
|
|
293
|
+
return undefined;
|
|
294
|
+
if (message.id === undefined) {
|
|
295
|
+
child.notify(method, message.params);
|
|
296
|
+
return undefined;
|
|
297
|
+
}
|
|
298
|
+
if (method === 'initialize' && child.init) {
|
|
299
|
+
return { jsonrpc: '2.0', id: message.id, result: child.init.result };
|
|
300
|
+
}
|
|
301
|
+
const answer = await child.request(method, message.params);
|
|
302
|
+
return { ...answer, id: message.id };
|
|
303
|
+
};
|
|
304
|
+
const http = createServer((req, res) => {
|
|
305
|
+
void (async () => {
|
|
306
|
+
if (!local(req)) {
|
|
307
|
+
json(res, 400, { error: 'the local host serves 127.0.0.1 only' });
|
|
308
|
+
return;
|
|
309
|
+
}
|
|
310
|
+
const path = new URL(req.url ?? '/', `http://${LOOPBACK}`).pathname.replace(/^\/+|\/+$/g, '');
|
|
311
|
+
if (path === '' || path === 'health') {
|
|
312
|
+
json(res, 200, {
|
|
313
|
+
servers: [...children.keys()],
|
|
314
|
+
sessions: sessions.size,
|
|
315
|
+
stopped: [...children.entries()].filter(([, c]) => c.stopped()).map(([name, c]) => ({ name, why: c.stopped() })),
|
|
316
|
+
});
|
|
317
|
+
return;
|
|
318
|
+
}
|
|
319
|
+
const child = children.get(path);
|
|
320
|
+
if (!child) {
|
|
321
|
+
json(res, 404, { error: `the local host runs no server named ${path}` });
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (child.stopped()) {
|
|
325
|
+
json(res, 503, { error: child.stopped() });
|
|
326
|
+
return;
|
|
327
|
+
}
|
|
328
|
+
const id = header(req, 'mcp-session-id');
|
|
329
|
+
if (req.method === 'DELETE') {
|
|
330
|
+
if (id === undefined || !sessions.has(id)) {
|
|
331
|
+
json(res, 404, { error: `the local host has no session ${id ?? ''}` });
|
|
332
|
+
return;
|
|
333
|
+
}
|
|
334
|
+
sessions.delete(id);
|
|
335
|
+
empty(res, 204);
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (req.method !== 'POST') {
|
|
339
|
+
json(res, 405, { error: 'the local host answers POST and DELETE; it sends no stream of its own' }, { allow: 'POST, DELETE' });
|
|
340
|
+
return;
|
|
341
|
+
}
|
|
342
|
+
const text = await body(req);
|
|
343
|
+
let parsed;
|
|
344
|
+
try {
|
|
345
|
+
parsed = JSON.parse(text);
|
|
346
|
+
}
|
|
347
|
+
catch {
|
|
348
|
+
json(res, 400, { error: 'the request is not JSON' });
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
const messages = Array.isArray(parsed) ? parsed : [parsed];
|
|
352
|
+
const starts = messages.some((m) => m.method === 'initialize');
|
|
353
|
+
let session = id === undefined ? undefined : sessions.get(id);
|
|
354
|
+
if (session === undefined) {
|
|
355
|
+
if (id !== undefined) {
|
|
356
|
+
json(res, 404, { error: `the local host has no session ${id}` });
|
|
357
|
+
return;
|
|
358
|
+
}
|
|
359
|
+
if (!starts) {
|
|
360
|
+
json(res, 400, { error: 'a session starts with a POST of initialize' });
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
session = { server: path, protocol: header(req, 'mcp-protocol-version') ?? PROTOCOL };
|
|
364
|
+
sessions.set(randomUUID(), session);
|
|
365
|
+
}
|
|
366
|
+
const sessionId = [...sessions.entries()].find(([, s]) => s === session)?.[0];
|
|
367
|
+
const extra = sessionId ? { 'mcp-session-id': sessionId, 'mcp-protocol-version': session.protocol } : {};
|
|
368
|
+
const answers = [];
|
|
369
|
+
for (const message of messages) {
|
|
370
|
+
const answer = await forward(child, message);
|
|
371
|
+
if (answer)
|
|
372
|
+
answers.push(answer);
|
|
373
|
+
}
|
|
374
|
+
if (answers.length === 0)
|
|
375
|
+
empty(res, 202, extra);
|
|
376
|
+
else
|
|
377
|
+
json(res, 200, Array.isArray(parsed) ? answers : answers[0], extra);
|
|
378
|
+
})().catch((error) => {
|
|
379
|
+
if (res.headersSent) {
|
|
380
|
+
res.end();
|
|
381
|
+
return;
|
|
382
|
+
}
|
|
383
|
+
json(res, 500, { error: error instanceof Error ? error.message : String(error) });
|
|
384
|
+
});
|
|
385
|
+
});
|
|
386
|
+
await new Promise((resolve, reject) => {
|
|
387
|
+
http.once('error', reject);
|
|
388
|
+
http.listen(options.config.port ?? DEFAULT_PORT, host, () => {
|
|
389
|
+
http.off('error', reject);
|
|
390
|
+
resolve();
|
|
391
|
+
});
|
|
392
|
+
});
|
|
393
|
+
const port = http.address().port;
|
|
394
|
+
const url = `http://${host}:${port}`;
|
|
395
|
+
return {
|
|
396
|
+
url,
|
|
397
|
+
urlOf: (name) => `${url}/${name}`,
|
|
398
|
+
get sessions() {
|
|
399
|
+
return sessions.size;
|
|
400
|
+
},
|
|
401
|
+
get children() {
|
|
402
|
+
return children.size;
|
|
403
|
+
},
|
|
404
|
+
async close() {
|
|
405
|
+
sessions.clear();
|
|
406
|
+
for (const child of children.values())
|
|
407
|
+
await child.close();
|
|
408
|
+
children.clear();
|
|
409
|
+
await new Promise((resolve) => http.close(() => resolve()));
|
|
410
|
+
},
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
/** The text of an empty config: the service needs a file to read on a machine that has none. */
|
|
414
|
+
function emptyConfig() {
|
|
415
|
+
return `${JSON.stringify({ port: DEFAULT_PORT, host: LOOPBACK, servers: [] }, null, 2)}\n`;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* `install`, `status` and `uninstall` of the one service per machine.
|
|
419
|
+
*
|
|
420
|
+
* `install` reads the config of the machine, writes the unit if its text changed, and loads it. What it prints a
|
|
421
|
+
* person can paste: none of it is a token, and the config holds no token either.
|
|
422
|
+
*/
|
|
423
|
+
export function runService(command, deps, say, fail) {
|
|
424
|
+
const h = deps.host ?? systemHost(process.env);
|
|
425
|
+
const platform = deps.platform ?? process.platform;
|
|
426
|
+
const main = deps.main ?? fileURLToPath(import.meta.url);
|
|
427
|
+
try {
|
|
428
|
+
if (command === 'install') {
|
|
429
|
+
if (h.read(configPath(h.home)) === undefined)
|
|
430
|
+
h.write(configPath(h.home), emptyConfig(), { mode: 0o600, dirMode: 0o700 });
|
|
431
|
+
const config = readConfig(h.home, h.read);
|
|
432
|
+
const r = installHost(h, { argv: hostArgv({ node: process.execPath, main, config: configPath(h.home) }), platform });
|
|
433
|
+
for (const file of r.written)
|
|
434
|
+
say(`mcp-kit-host: wrote ${file}`);
|
|
435
|
+
if (r.load) {
|
|
436
|
+
fail(`mcp-kit-host: the service manager did not load the service. Run: ${r.load.join(' ')}`);
|
|
437
|
+
return 1;
|
|
438
|
+
}
|
|
439
|
+
const names = config.servers.map((s) => s.name).join(', ') || 'no server yet';
|
|
440
|
+
say(`mcp-kit-host: the service runs, with ${names} on http://${LOOPBACK}:${config.port}`);
|
|
441
|
+
return 0;
|
|
442
|
+
}
|
|
443
|
+
if (command === 'status') {
|
|
444
|
+
const config = readConfig(h.home, h.read);
|
|
445
|
+
say(`mcp-kit-host: ${hostStatus(h, platform)} on http://${LOOPBACK}:${config.port}`);
|
|
446
|
+
for (const spec of config.servers)
|
|
447
|
+
say(`mcp-kit-host: ${spec.name} http://${LOOPBACK}:${config.port}/${spec.name} runs ${spec.command}`);
|
|
448
|
+
return 0;
|
|
449
|
+
}
|
|
450
|
+
const removed = uninstallHost(h, platform);
|
|
451
|
+
say(removed.length > 0 ? `mcp-kit-host: stopped, and cleared ${removed.join(', ')}. The config stays.` : 'mcp-kit-host: no service on this machine');
|
|
452
|
+
return 0;
|
|
453
|
+
}
|
|
454
|
+
catch (error) {
|
|
455
|
+
fail(`mcp-kit-host: ${error.message}`);
|
|
456
|
+
return 1;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
/** Runs the command and returns its exit code. It serves until `wait` resolves, then closes the host. */
|
|
460
|
+
export async function runHostCommand(argv, deps = {}) {
|
|
461
|
+
const say = deps.say ?? ((line) => console.log(line));
|
|
462
|
+
const fail = deps.fail ?? ((line) => console.error(line));
|
|
463
|
+
if (argv.includes('--help') || argv.includes('-h')) {
|
|
464
|
+
say(USAGE);
|
|
465
|
+
return 0;
|
|
466
|
+
}
|
|
467
|
+
if (argv[0] === 'install' || argv[0] === 'status' || argv[0] === 'uninstall') {
|
|
468
|
+
return runService(argv[0], deps, say, fail);
|
|
469
|
+
}
|
|
470
|
+
let command;
|
|
471
|
+
try {
|
|
472
|
+
command = parseHostArgs(argv);
|
|
473
|
+
}
|
|
474
|
+
catch (error) {
|
|
475
|
+
fail(`mcp-kit-host: ${error.message}\n\n${USAGE}`);
|
|
476
|
+
return 2;
|
|
477
|
+
}
|
|
478
|
+
const start = deps.start ?? startPlainHost;
|
|
479
|
+
let host;
|
|
480
|
+
try {
|
|
481
|
+
host = await start({ config: command, log: (line) => fail(line) });
|
|
482
|
+
}
|
|
483
|
+
catch (error) {
|
|
484
|
+
fail(`mcp-kit-host: ${error.message}`);
|
|
485
|
+
return 1;
|
|
486
|
+
}
|
|
487
|
+
for (const spec of command.servers)
|
|
488
|
+
say(`mcp-kit-host: ${spec.name} ${host.urlOf(spec.name)}`);
|
|
489
|
+
say(`mcp-kit-host: listening on ${host.url}`);
|
|
490
|
+
try {
|
|
491
|
+
await (deps.wait ?? untilSignal)();
|
|
492
|
+
}
|
|
493
|
+
finally {
|
|
494
|
+
await host.close();
|
|
495
|
+
}
|
|
496
|
+
say('mcp-kit-host: closed');
|
|
497
|
+
return 0;
|
|
498
|
+
}
|
|
499
|
+
/** The home of the person, for a run that names no file. */
|
|
500
|
+
export function homeOf(env = process.env) {
|
|
501
|
+
return env.HOME ?? homedir();
|
|
502
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Runs a program and answers its exit code and text. */
|
|
2
|
+
export type Run = (bin: string, args: string[], opts?: {
|
|
3
|
+
input?: string;
|
|
4
|
+
cwd?: string;
|
|
5
|
+
env?: NodeJS.ProcessEnv;
|
|
6
|
+
timeoutMs?: number;
|
|
7
|
+
}) => {
|
|
8
|
+
code: number;
|
|
9
|
+
stdout: string;
|
|
10
|
+
stderr: string;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* The machine that a client writer works on: the home folder, the programs it can run, and the
|
|
14
|
+
* files it reads and writes. A test gives a writer a host of its own, so no test touches a real
|
|
15
|
+
* home folder.
|
|
16
|
+
*/
|
|
17
|
+
export interface Host {
|
|
18
|
+
home: string;
|
|
19
|
+
env: NodeJS.ProcessEnv;
|
|
20
|
+
run: Run;
|
|
21
|
+
read(path: string): string | undefined;
|
|
22
|
+
/**
|
|
23
|
+
* Writes the file and makes its folders. With no `mode`, a file that it replaces keeps a copy named
|
|
24
|
+
* `<file>.munhq-bak`. With a `mode` (a secret, a program) no copy is kept, and the file and its
|
|
25
|
+
* folders get the modes given.
|
|
26
|
+
*/
|
|
27
|
+
write(path: string, text: string, opts?: {
|
|
28
|
+
mode?: number;
|
|
29
|
+
dirMode?: number;
|
|
30
|
+
}): void;
|
|
31
|
+
}
|
|
32
|
+
export declare function systemHost(env?: NodeJS.ProcessEnv): Host;
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { chmodSync, copyFileSync, existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { homedir } from 'node:os';
|
|
4
|
+
import { dirname } from 'node:path';
|
|
5
|
+
export function systemHost(env = process.env) {
|
|
6
|
+
return {
|
|
7
|
+
home: env.HOME ?? homedir(),
|
|
8
|
+
env,
|
|
9
|
+
run(bin, args, opts = {}) {
|
|
10
|
+
const r = spawnSync(bin, args, {
|
|
11
|
+
input: opts.input,
|
|
12
|
+
cwd: opts.cwd,
|
|
13
|
+
env: opts.env ?? env,
|
|
14
|
+
timeout: opts.timeoutMs,
|
|
15
|
+
encoding: 'utf8',
|
|
16
|
+
});
|
|
17
|
+
return { code: r.status ?? 1, stdout: r.stdout ?? '', stderr: r.stderr ?? (r.error ? String(r.error) : '') };
|
|
18
|
+
},
|
|
19
|
+
read(path) {
|
|
20
|
+
try {
|
|
21
|
+
return readFileSync(path, 'utf8');
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
return undefined;
|
|
25
|
+
}
|
|
26
|
+
},
|
|
27
|
+
write(path, text, opts = {}) {
|
|
28
|
+
mkdirSync(dirname(path), { recursive: true, ...(opts.dirMode === undefined ? {} : { mode: opts.dirMode }) });
|
|
29
|
+
if (opts.mode === undefined) {
|
|
30
|
+
if (existsSync(path))
|
|
31
|
+
copyFileSync(path, `${path}.munhq-bak`);
|
|
32
|
+
writeFileSync(path, text);
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
// Many agents read token.json while one of them renews it. The text goes to a file of this process and
|
|
36
|
+
// a rename puts it in place, so a reader sees the old file or the new one, and never an empty one.
|
|
37
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
38
|
+
writeFileSync(tmp, text, { mode: opts.mode });
|
|
39
|
+
chmodSync(tmp, opts.mode);
|
|
40
|
+
renameSync(tmp, path);
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
}
|