@c9up/polaris 0.1.0 → 0.1.1
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 +614 -10
- package/dist/Polaris.d.ts +6 -2
- package/dist/Polaris.d.ts.map +1 -1
- package/dist/Polaris.js +14 -0
- package/dist/Polaris.js.map +1 -1
- package/dist/PolarisClient.d.ts +51 -3
- package/dist/PolarisClient.d.ts.map +1 -1
- package/dist/PolarisClient.js +213 -45
- package/dist/PolarisClient.js.map +1 -1
- package/dist/PolarisProvider.d.ts +7 -2
- package/dist/PolarisProvider.d.ts.map +1 -1
- package/dist/PolarisProvider.js +34 -2
- package/dist/PolarisProvider.js.map +1 -1
- package/dist/augmentations.d.ts +4 -1
- package/dist/augmentations.d.ts.map +1 -1
- package/dist/augmentations.js +1 -1
- package/dist/budget.d.ts +39 -6
- package/dist/budget.d.ts.map +1 -1
- package/dist/budget.js +79 -12
- package/dist/budget.js.map +1 -1
- package/dist/catalog/catalog.d.ts +37 -0
- package/dist/catalog/catalog.d.ts.map +1 -0
- package/dist/catalog/catalog.js +145 -0
- package/dist/catalog/catalog.js.map +1 -0
- package/dist/catalog/discover.d.ts +64 -0
- package/dist/catalog/discover.d.ts.map +1 -0
- package/dist/catalog/discover.js +148 -0
- package/dist/catalog/discover.js.map +1 -0
- package/dist/catalog/index.d.ts +8 -0
- package/dist/catalog/index.d.ts.map +1 -0
- package/dist/catalog/index.js +8 -0
- package/dist/catalog/index.js.map +1 -0
- package/dist/commands/index.d.ts +82 -0
- package/dist/commands/index.d.ts.map +1 -0
- package/dist/commands/index.js +278 -0
- package/dist/commands/index.js.map +1 -0
- package/dist/cost.d.ts +3 -1
- package/dist/cost.d.ts.map +1 -1
- package/dist/cost.js +8 -3
- package/dist/cost.js.map +1 -1
- package/dist/drivers/anthropic.d.ts +6 -1
- package/dist/drivers/anthropic.d.ts.map +1 -1
- package/dist/drivers/anthropic.js +166 -21
- package/dist/drivers/anthropic.js.map +1 -1
- package/dist/drivers/openai-compatible.d.ts +1 -1
- package/dist/drivers/openai-compatible.d.ts.map +1 -1
- package/dist/drivers/openai-compatible.js +106 -70
- package/dist/drivers/openai-compatible.js.map +1 -1
- package/dist/errors.d.ts +24 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +24 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +6 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/json-schema.d.ts +33 -0
- package/dist/json-schema.d.ts.map +1 -0
- package/dist/json-schema.js +508 -0
- package/dist/json-schema.js.map +1 -0
- package/dist/log.d.ts.map +1 -1
- package/dist/log.js +3 -1
- package/dist/log.js.map +1 -1
- package/dist/mcp/client.d.ts +81 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/client.js +401 -0
- package/dist/mcp/client.js.map +1 -0
- package/dist/mcp/endpoint.d.ts +54 -0
- package/dist/mcp/endpoint.d.ts.map +1 -0
- package/dist/mcp/endpoint.js +158 -0
- package/dist/mcp/endpoint.js.map +1 -0
- package/dist/mcp/host.d.ts +42 -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/http.d.ts +32 -0
- package/dist/mcp/http.d.ts.map +1 -0
- package/dist/mcp/http.js +190 -0
- package/dist/mcp/http.js.map +1 -0
- package/dist/mcp/index.d.ts +23 -0
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +21 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/mcp/manifest.d.ts +36 -0
- package/dist/mcp/manifest.d.ts.map +1 -0
- package/dist/mcp/manifest.js +40 -0
- package/dist/mcp/manifest.js.map +1 -0
- package/dist/mcp/rpc.d.ts +39 -0
- package/dist/mcp/rpc.d.ts.map +1 -0
- package/dist/mcp/rpc.js +149 -0
- package/dist/mcp/rpc.js.map +1 -0
- package/dist/mcp/stdio.d.ts +24 -0
- package/dist/mcp/stdio.d.ts.map +1 -0
- package/dist/mcp/stdio.js +157 -0
- package/dist/mcp/stdio.js.map +1 -0
- package/dist/mcp/worker-main.d.ts +6 -0
- package/dist/mcp/worker-main.d.ts.map +1 -0
- package/dist/mcp/worker-main.js +17 -0
- package/dist/mcp/worker-main.js.map +1 -0
- package/dist/mcp/worker.d.ts +54 -0
- package/dist/mcp/worker.d.ts.map +1 -0
- package/dist/mcp/worker.js +166 -0
- package/dist/mcp/worker.js.map +1 -0
- package/dist/meter.d.ts +6 -0
- package/dist/meter.d.ts.map +1 -1
- package/dist/meter.js +6 -3
- package/dist/meter.js.map +1 -1
- package/dist/redact.d.ts +4 -3
- package/dist/redact.d.ts.map +1 -1
- package/dist/redact.js +5 -4
- package/dist/redact.js.map +1 -1
- package/dist/redis-budget.d.ts +45 -0
- package/dist/redis-budget.d.ts.map +1 -0
- package/dist/redis-budget.js +56 -0
- package/dist/redis-budget.js.map +1 -0
- package/dist/response.d.ts +21 -3
- package/dist/response.d.ts.map +1 -1
- package/dist/response.js +71 -7
- package/dist/response.js.map +1 -1
- package/dist/server-sent.d.ts +9 -0
- package/dist/server-sent.d.ts.map +1 -0
- package/dist/server-sent.js +74 -0
- package/dist/server-sent.js.map +1 -0
- package/dist/server-tools.d.ts +12 -0
- package/dist/server-tools.d.ts.map +1 -0
- package/dist/server-tools.js +71 -0
- package/dist/server-tools.js.map +1 -0
- package/dist/services/catalog.d.ts +19 -0
- package/dist/services/catalog.d.ts.map +1 -0
- package/dist/services/catalog.js +37 -0
- package/dist/services/catalog.js.map +1 -0
- package/dist/skills/folder.d.ts +32 -0
- package/dist/skills/folder.d.ts.map +1 -0
- package/dist/skills/folder.js +170 -0
- package/dist/skills/folder.js.map +1 -0
- package/dist/skills/frontmatter.d.ts +15 -0
- package/dist/skills/frontmatter.d.ts.map +1 -0
- package/dist/skills/frontmatter.js +92 -0
- package/dist/skills/frontmatter.js.map +1 -0
- package/dist/skills/index.d.ts +18 -0
- package/dist/skills/index.d.ts.map +1 -0
- package/dist/skills/index.js +18 -0
- package/dist/skills/index.js.map +1 -0
- package/dist/skills/kit.d.ts +39 -0
- package/dist/skills/kit.d.ts.map +1 -0
- package/dist/skills/kit.js +124 -0
- package/dist/skills/kit.js.map +1 -0
- package/dist/skills/skill.d.ts +67 -0
- package/dist/skills/skill.d.ts.map +1 -0
- package/dist/skills/skill.js +114 -0
- package/dist/skills/skill.js.map +1 -0
- package/dist/sse.d.ts +43 -6
- package/dist/sse.d.ts.map +1 -1
- package/dist/sse.js +44 -18
- package/dist/sse.js.map +1 -1
- package/dist/testing/FakeProvider.d.ts.map +1 -1
- package/dist/testing/FakeProvider.js +1 -0
- package/dist/testing/FakeProvider.js.map +1 -1
- package/dist/tool-modules.d.ts +17 -0
- package/dist/tool-modules.d.ts.map +1 -0
- package/dist/tool-modules.js +43 -0
- package/dist/tool-modules.js.map +1 -0
- package/dist/tools.d.ts +69 -5
- package/dist/tools.d.ts.map +1 -1
- package/dist/tools.js +174 -31
- package/dist/tools.js.map +1 -1
- package/dist/transport.d.ts +8 -3
- package/dist/transport.d.ts.map +1 -1
- package/dist/transport.js +19 -4
- package/dist/transport.js.map +1 -1
- package/dist/types.d.ts +106 -2
- package/dist/types.d.ts.map +1 -1
- package/package.json +22 -1
- package/src/Polaris.ts +25 -1
- package/src/PolarisClient.ts +288 -51
- package/src/PolarisProvider.ts +40 -2
- package/src/augmentations.ts +4 -1
- package/src/budget.ts +115 -15
- package/src/catalog/catalog.ts +180 -0
- package/src/catalog/discover.ts +234 -0
- package/src/catalog/index.ts +19 -0
- package/src/commands/index.ts +412 -0
- package/src/cost.ts +9 -3
- package/src/drivers/anthropic.ts +203 -20
- package/src/drivers/openai-compatible.ts +143 -76
- package/src/errors.ts +41 -0
- package/src/index.ts +16 -0
- package/src/json-schema.ts +597 -0
- package/src/log.ts +3 -1
- package/src/mcp/client.ts +532 -0
- package/src/mcp/endpoint.ts +229 -0
- package/src/mcp/host.ts +140 -0
- package/src/mcp/http.ts +276 -0
- package/src/mcp/index.ts +51 -0
- package/src/mcp/manifest.ts +73 -0
- package/src/mcp/rpc.ts +197 -0
- package/src/mcp/stdio.ts +190 -0
- package/src/mcp/worker-main.ts +18 -0
- package/src/mcp/worker.ts +212 -0
- package/src/meter.ts +13 -2
- package/src/redact.ts +6 -3
- package/src/redis-budget.ts +85 -0
- package/src/response.ts +86 -8
- package/src/server-sent.ts +70 -0
- package/src/server-tools.ts +77 -0
- package/src/services/catalog.ts +43 -0
- package/src/skills/folder.ts +231 -0
- package/src/skills/frontmatter.ts +92 -0
- package/src/skills/index.ts +38 -0
- package/src/skills/kit.ts +163 -0
- package/src/skills/skill.ts +171 -0
- package/src/sse.ts +88 -22
- package/src/testing/FakeProvider.ts +1 -0
- package/src/tool-modules.ts +49 -0
- package/src/tools.ts +260 -27
- package/src/transport.ts +25 -3
- package/src/types.ts +108 -2
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `tools.json`: the application's tools as an outside agent lists them, read
|
|
3
|
+
* without importing a tool module (as `commands.json` is for commands).
|
|
4
|
+
* `ream mcp:serve` answers `initialize` and `tools/list` from it, and starts
|
|
5
|
+
* the worker it names for the first call.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
9
|
+
import { dirname, relative, sep } from "node:path";
|
|
10
|
+
import { fileURLToPath } from "node:url";
|
|
11
|
+
import type { ToolDefinition } from "../types.js";
|
|
12
|
+
import { loadTools, moduleUrl, ToolHost } from "./host.js";
|
|
13
|
+
import { WORKER_PROTOCOL } from "./worker.js";
|
|
14
|
+
|
|
15
|
+
/** What `tools.json` holds. */
|
|
16
|
+
export interface ToolsManifest {
|
|
17
|
+
/** The manifest's format. */
|
|
18
|
+
readonly version: 1;
|
|
19
|
+
/** The worker protocol the `worker` speaks. */
|
|
20
|
+
readonly protocol: typeof WORKER_PROTOCOL;
|
|
21
|
+
/** The module that exports the tools, relative to the manifest. */
|
|
22
|
+
readonly module: string;
|
|
23
|
+
/** The worker to start, relative to the manifest: `node <worker> <tools.json>`. */
|
|
24
|
+
readonly worker: string;
|
|
25
|
+
readonly tools: readonly ToolDefinition[];
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export interface ToolsManifestOptions {
|
|
29
|
+
/**
|
|
30
|
+
* The module that exports the tools to expose: a list, or a function
|
|
31
|
+
* (sync or async) returning one, as `default` or `tools`. Its path, or a
|
|
32
|
+
* `file:` URL.
|
|
33
|
+
*/
|
|
34
|
+
readonly module: string | URL;
|
|
35
|
+
/** Where to write the manifest. Default `tools.json` beside the module. */
|
|
36
|
+
readonly output?: string | URL;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** The worker of this polaris, as built beside this module. */
|
|
40
|
+
const WORKER = new URL(
|
|
41
|
+
import.meta.url.endsWith(".ts") ? "./worker-main.ts" : "./worker-main.js",
|
|
42
|
+
import.meta.url,
|
|
43
|
+
);
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Import the tools module, and write the manifest that lists its tools.
|
|
47
|
+
* Returns the manifest, so a caller can report what it wrote.
|
|
48
|
+
*/
|
|
49
|
+
export async function writeToolsManifest(
|
|
50
|
+
options: ToolsManifestOptions,
|
|
51
|
+
): Promise<ToolsManifest> {
|
|
52
|
+
const module = fileURLToPath(moduleUrl(options.module));
|
|
53
|
+
const output =
|
|
54
|
+
options.output === undefined
|
|
55
|
+
? `${dirname(module)}${sep}tools.json`
|
|
56
|
+
: fileURLToPath(moduleUrl(options.output));
|
|
57
|
+
const tools = await loadTools(module);
|
|
58
|
+
const from = dirname(output);
|
|
59
|
+
const path = (to: string): string => {
|
|
60
|
+
const relativePath = relative(from, to).split(sep).join("/");
|
|
61
|
+
return relativePath.startsWith(".") ? relativePath : `./${relativePath}`;
|
|
62
|
+
};
|
|
63
|
+
const manifest: ToolsManifest = {
|
|
64
|
+
version: 1,
|
|
65
|
+
protocol: WORKER_PROTOCOL,
|
|
66
|
+
module: path(module),
|
|
67
|
+
worker: path(fileURLToPath(WORKER)),
|
|
68
|
+
tools: new ToolHost(tools).definitions,
|
|
69
|
+
};
|
|
70
|
+
await mkdir(from, { recursive: true });
|
|
71
|
+
await writeFile(output, `${JSON.stringify(manifest, null, 2)}\n`);
|
|
72
|
+
return manifest;
|
|
73
|
+
}
|
package/src/mcp/rpc.ts
ADDED
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* JSON-RPC 2.0 over one channel to an MCP server: requests with a timeout
|
|
3
|
+
* and a signal, notifications both ways, and the few requests a server may
|
|
4
|
+
* send a client that declares no capability (`ping` is answered, anything
|
|
5
|
+
* else is "Method not found").
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { E_POLARIS_MCP } from "../errors.js";
|
|
9
|
+
|
|
10
|
+
export type JsonObject = Record<string, unknown>;
|
|
11
|
+
|
|
12
|
+
/** A way to exchange JSON-RPC messages with one server. */
|
|
13
|
+
export interface Channel {
|
|
14
|
+
/**
|
|
15
|
+
* Send one message. What the server sends back goes to
|
|
16
|
+
* {@link ChannelEvents.receive}. Rejects when it could not be sent.
|
|
17
|
+
*/
|
|
18
|
+
send(message: JsonObject, signal?: AbortSignal): Promise<void>;
|
|
19
|
+
/** End the connection. Never rejects. */
|
|
20
|
+
close(): Promise<void>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface ChannelEvents {
|
|
24
|
+
receive(message: unknown): void;
|
|
25
|
+
/** The connection ended on its own; `error` says why. */
|
|
26
|
+
closed(error: Error): void;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface RequestOptions {
|
|
30
|
+
readonly timeout: number;
|
|
31
|
+
readonly signal?: AbortSignal | undefined;
|
|
32
|
+
/** Tell the server when the request is given up. Not for `initialize`. */
|
|
33
|
+
readonly cancellable?: boolean;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface Pending {
|
|
37
|
+
readonly method: string;
|
|
38
|
+
resolve(result: unknown): void;
|
|
39
|
+
reject(error: unknown): void;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** The longest server error message kept, in characters. */
|
|
43
|
+
const MAX_ERROR_MESSAGE = 500;
|
|
44
|
+
|
|
45
|
+
export function isObject(value: unknown): value is JsonObject {
|
|
46
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class Session {
|
|
50
|
+
readonly #name: string;
|
|
51
|
+
readonly #channel: Channel;
|
|
52
|
+
readonly #onNotification: (method: string, params: unknown) => void;
|
|
53
|
+
readonly #pending = new Map<number, Pending>();
|
|
54
|
+
#nextId = 1;
|
|
55
|
+
#closed: Error | undefined;
|
|
56
|
+
|
|
57
|
+
constructor(
|
|
58
|
+
name: string,
|
|
59
|
+
open: (events: ChannelEvents) => Channel,
|
|
60
|
+
onNotification: (method: string, params: unknown) => void,
|
|
61
|
+
) {
|
|
62
|
+
this.#name = name;
|
|
63
|
+
this.#onNotification = onNotification;
|
|
64
|
+
this.#channel = open({
|
|
65
|
+
receive: (message) => this.#receive(message),
|
|
66
|
+
closed: (error) => this.#fail(error),
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** Send a request and wait for its result. */
|
|
71
|
+
request(
|
|
72
|
+
method: string,
|
|
73
|
+
params: JsonObject | undefined,
|
|
74
|
+
options: RequestOptions,
|
|
75
|
+
): Promise<unknown> {
|
|
76
|
+
if (this.#closed !== undefined) return Promise.reject(this.#closed);
|
|
77
|
+
const { signal, timeout, cancellable = true } = options;
|
|
78
|
+
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
79
|
+
const id = this.#nextId++;
|
|
80
|
+
|
|
81
|
+
return new Promise((resolve, reject) => {
|
|
82
|
+
const cleanup = (): void => {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
signal?.removeEventListener("abort", onAbort);
|
|
85
|
+
this.#pending.delete(id);
|
|
86
|
+
};
|
|
87
|
+
const giveUp = (reason: string): void => {
|
|
88
|
+
if (!cancellable || this.#closed !== undefined) return;
|
|
89
|
+
this.notify("notifications/cancelled", { requestId: id, reason });
|
|
90
|
+
};
|
|
91
|
+
const onAbort = (): void => {
|
|
92
|
+
cleanup();
|
|
93
|
+
giveUp("The request was cancelled.");
|
|
94
|
+
reject(signal?.reason);
|
|
95
|
+
};
|
|
96
|
+
const timer = setTimeout(() => {
|
|
97
|
+
cleanup();
|
|
98
|
+
giveUp("The request timed out.");
|
|
99
|
+
reject(
|
|
100
|
+
new E_POLARIS_MCP([
|
|
101
|
+
this.#name,
|
|
102
|
+
`'${method}' did not finish within ${timeout} ms`,
|
|
103
|
+
]),
|
|
104
|
+
);
|
|
105
|
+
}, timeout);
|
|
106
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
107
|
+
this.#pending.set(id, {
|
|
108
|
+
method,
|
|
109
|
+
resolve: (result) => {
|
|
110
|
+
cleanup();
|
|
111
|
+
resolve(result);
|
|
112
|
+
},
|
|
113
|
+
reject: (error) => {
|
|
114
|
+
cleanup();
|
|
115
|
+
reject(error);
|
|
116
|
+
},
|
|
117
|
+
});
|
|
118
|
+
this.#channel
|
|
119
|
+
.send(
|
|
120
|
+
{
|
|
121
|
+
jsonrpc: "2.0",
|
|
122
|
+
id,
|
|
123
|
+
method,
|
|
124
|
+
...(params !== undefined ? { params } : {}),
|
|
125
|
+
},
|
|
126
|
+
signal,
|
|
127
|
+
)
|
|
128
|
+
.catch((error: unknown) => this.#pending.get(id)?.reject(error));
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** Send a notification; a failure to send it is ignored. */
|
|
133
|
+
notify(method: string, params?: JsonObject): void {
|
|
134
|
+
if (this.#closed !== undefined) return;
|
|
135
|
+
this.#channel
|
|
136
|
+
.send({
|
|
137
|
+
jsonrpc: "2.0",
|
|
138
|
+
method,
|
|
139
|
+
...(params !== undefined ? { params } : {}),
|
|
140
|
+
})
|
|
141
|
+
.catch(() => undefined);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
async close(): Promise<void> {
|
|
145
|
+
if (this.#closed === undefined) {
|
|
146
|
+
this.#fail(new E_POLARIS_MCP([this.#name, "the connection was closed"]));
|
|
147
|
+
}
|
|
148
|
+
await this.#channel.close();
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
#fail(error: Error): void {
|
|
152
|
+
if (this.#closed !== undefined) return;
|
|
153
|
+
this.#closed = error;
|
|
154
|
+
for (const pending of [...this.#pending.values()]) pending.reject(error);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
#receive(message: unknown): void {
|
|
158
|
+
if (!isObject(message)) return;
|
|
159
|
+
const { id, method } = message;
|
|
160
|
+
if (typeof method === "string") {
|
|
161
|
+
if (typeof id === "string" || typeof id === "number") {
|
|
162
|
+
this.#answer(id, method);
|
|
163
|
+
} else {
|
|
164
|
+
this.#onNotification(method, message.params);
|
|
165
|
+
}
|
|
166
|
+
return;
|
|
167
|
+
}
|
|
168
|
+
if (typeof id !== "number") return;
|
|
169
|
+
const pending = this.#pending.get(id);
|
|
170
|
+
if (pending === undefined) return;
|
|
171
|
+
if ("error" in message) {
|
|
172
|
+
const error = message.error;
|
|
173
|
+
const text =
|
|
174
|
+
isObject(error) && typeof error.message === "string"
|
|
175
|
+
? error.message.slice(0, MAX_ERROR_MESSAGE)
|
|
176
|
+
: "no message";
|
|
177
|
+
pending.reject(
|
|
178
|
+
new E_POLARIS_MCP([
|
|
179
|
+
this.#name,
|
|
180
|
+
`'${pending.method}' was refused: ${text}`,
|
|
181
|
+
]),
|
|
182
|
+
);
|
|
183
|
+
} else {
|
|
184
|
+
pending.resolve(message.result);
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** A request from the server. */
|
|
189
|
+
#answer(id: string | number, method: string): void {
|
|
190
|
+
if (this.#closed !== undefined) return;
|
|
191
|
+
const reply =
|
|
192
|
+
method === "ping"
|
|
193
|
+
? { result: {} }
|
|
194
|
+
: { error: { code: -32601, message: "Method not found" } };
|
|
195
|
+
this.#channel.send({ jsonrpc: "2.0", id, ...reply }).catch(() => undefined);
|
|
196
|
+
}
|
|
197
|
+
}
|
package/src/mcp/stdio.ts
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* An MCP server run as a child process, spoken to over its stdin and stdout:
|
|
3
|
+
* one JSON-RPC message per line.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { type ChildProcess, spawn } from "node:child_process";
|
|
7
|
+
import { StringDecoder } from "node:string_decoder";
|
|
8
|
+
import { E_POLARIS_MCP } from "../errors.js";
|
|
9
|
+
import type { Channel, ChannelEvents, JsonObject } from "./rpc.js";
|
|
10
|
+
|
|
11
|
+
export interface StdioServer {
|
|
12
|
+
readonly type: "stdio";
|
|
13
|
+
/** The program to run: `npx`, `node`, `/usr/local/bin/server`. */
|
|
14
|
+
readonly command: string;
|
|
15
|
+
readonly args?: readonly string[];
|
|
16
|
+
/**
|
|
17
|
+
* Added to the few variables the server inherits (`PATH`, `HOME`...):
|
|
18
|
+
* the application's own environment, and the keys in it, is not passed on.
|
|
19
|
+
* The values are kept out of errors.
|
|
20
|
+
*/
|
|
21
|
+
readonly env?: Readonly<Record<string, string>>;
|
|
22
|
+
readonly cwd?: string;
|
|
23
|
+
/** Where the server's stderr goes. Default `inherit`: the application's. */
|
|
24
|
+
readonly stderr?: "inherit" | "ignore";
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** What a stdio server inherits from the application's environment. */
|
|
28
|
+
const INHERITED =
|
|
29
|
+
process.platform === "win32"
|
|
30
|
+
? [
|
|
31
|
+
"APPDATA",
|
|
32
|
+
"HOMEDRIVE",
|
|
33
|
+
"HOMEPATH",
|
|
34
|
+
"LOCALAPPDATA",
|
|
35
|
+
"PATH",
|
|
36
|
+
"PROCESSOR_ARCHITECTURE",
|
|
37
|
+
"SYSTEMDRIVE",
|
|
38
|
+
"SYSTEMROOT",
|
|
39
|
+
"TEMP",
|
|
40
|
+
"USERNAME",
|
|
41
|
+
"USERPROFILE",
|
|
42
|
+
"PROGRAMFILES",
|
|
43
|
+
]
|
|
44
|
+
: ["HOME", "LOGNAME", "PATH", "SHELL", "TERM", "USER"];
|
|
45
|
+
|
|
46
|
+
/** How long `close()` waits for the server to leave, at each step. */
|
|
47
|
+
const EXIT_GRACE_MS = 2_000;
|
|
48
|
+
|
|
49
|
+
/** The environment a stdio server is started with. */
|
|
50
|
+
export function stdioEnvironment(
|
|
51
|
+
given: Readonly<Record<string, string>> = {},
|
|
52
|
+
): Record<string, string> {
|
|
53
|
+
const env: Record<string, string> = {};
|
|
54
|
+
for (const key of INHERITED) {
|
|
55
|
+
const value = process.env[key];
|
|
56
|
+
// A shell function exported by bash starts with "()": not a value.
|
|
57
|
+
if (value !== undefined && !value.startsWith("()")) env[key] = value;
|
|
58
|
+
}
|
|
59
|
+
return { ...env, ...given };
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function openStdio(
|
|
63
|
+
name: string,
|
|
64
|
+
server: StdioServer,
|
|
65
|
+
maxMessageBytes: number,
|
|
66
|
+
events: ChannelEvents,
|
|
67
|
+
): Channel {
|
|
68
|
+
const child: ChildProcess = spawn(server.command, [...(server.args ?? [])], {
|
|
69
|
+
env: stdioEnvironment(server.env),
|
|
70
|
+
...(server.cwd !== undefined ? { cwd: server.cwd } : {}),
|
|
71
|
+
stdio: ["pipe", "pipe", server.stderr ?? "inherit"],
|
|
72
|
+
shell: false,
|
|
73
|
+
windowsHide: true,
|
|
74
|
+
});
|
|
75
|
+
let exited = false;
|
|
76
|
+
let closing = false;
|
|
77
|
+
const exit = new Promise<void>((resolve) => {
|
|
78
|
+
child.once("exit", (code, signal) => {
|
|
79
|
+
exited = true;
|
|
80
|
+
resolve();
|
|
81
|
+
if (!closing) {
|
|
82
|
+
events.closed(
|
|
83
|
+
new E_POLARIS_MCP([
|
|
84
|
+
name,
|
|
85
|
+
`the server exited (${signal ?? `code ${code}`})`,
|
|
86
|
+
]),
|
|
87
|
+
);
|
|
88
|
+
}
|
|
89
|
+
});
|
|
90
|
+
});
|
|
91
|
+
child.once("error", (error: NodeJS.ErrnoException) => {
|
|
92
|
+
exited = true;
|
|
93
|
+
events.closed(
|
|
94
|
+
new E_POLARIS_MCP([
|
|
95
|
+
name,
|
|
96
|
+
`could not start '${server.command}' (${error.code ?? "unknown error"})`,
|
|
97
|
+
]),
|
|
98
|
+
);
|
|
99
|
+
});
|
|
100
|
+
// A write to a server that left fails here as well as in `send`.
|
|
101
|
+
child.stdin?.on("error", () => undefined);
|
|
102
|
+
|
|
103
|
+
const decoder = new StringDecoder("utf8");
|
|
104
|
+
let pending: string[] = [];
|
|
105
|
+
let pendingBytes = 0;
|
|
106
|
+
const line = (text: string): void => {
|
|
107
|
+
const trimmed = text.endsWith("\r") ? text.slice(0, -1) : text;
|
|
108
|
+
if (trimmed.trim() === "") return;
|
|
109
|
+
let message: unknown;
|
|
110
|
+
try {
|
|
111
|
+
message = JSON.parse(trimmed);
|
|
112
|
+
} catch {
|
|
113
|
+
// Not a message: a server that logs to stdout. Skipped.
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
events.receive(message);
|
|
117
|
+
};
|
|
118
|
+
child.stdout?.on("data", (chunk: Buffer) => {
|
|
119
|
+
const text = decoder.write(chunk);
|
|
120
|
+
let start = 0;
|
|
121
|
+
let newline = text.indexOf("\n");
|
|
122
|
+
while (newline !== -1) {
|
|
123
|
+
pending.push(text.slice(start, newline));
|
|
124
|
+
const whole = pending.join("");
|
|
125
|
+
pending = [];
|
|
126
|
+
pendingBytes = 0;
|
|
127
|
+
line(whole);
|
|
128
|
+
start = newline + 1;
|
|
129
|
+
newline = text.indexOf("\n", start);
|
|
130
|
+
}
|
|
131
|
+
const rest = text.slice(start);
|
|
132
|
+
pendingBytes += Buffer.byteLength(rest, "utf8");
|
|
133
|
+
if (pendingBytes > maxMessageBytes) {
|
|
134
|
+
pending = [];
|
|
135
|
+
pendingBytes = 0;
|
|
136
|
+
events.closed(
|
|
137
|
+
new E_POLARIS_MCP([
|
|
138
|
+
name,
|
|
139
|
+
`the server sent a message longer than ${maxMessageBytes} bytes`,
|
|
140
|
+
]),
|
|
141
|
+
);
|
|
142
|
+
closing = true;
|
|
143
|
+
child.kill("SIGKILL");
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
if (rest !== "") pending.push(rest);
|
|
147
|
+
});
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
send(message: JsonObject): Promise<void> {
|
|
151
|
+
const stdin = child.stdin;
|
|
152
|
+
if (exited || stdin === null || !stdin.writable) {
|
|
153
|
+
return Promise.reject(
|
|
154
|
+
new E_POLARIS_MCP([name, "the server is not running"]),
|
|
155
|
+
);
|
|
156
|
+
}
|
|
157
|
+
return new Promise((resolve, reject) => {
|
|
158
|
+
stdin.write(`${JSON.stringify(message)}\n`, (error) => {
|
|
159
|
+
if (error)
|
|
160
|
+
reject(new E_POLARIS_MCP([name, "the server is not running"]));
|
|
161
|
+
else resolve();
|
|
162
|
+
});
|
|
163
|
+
});
|
|
164
|
+
},
|
|
165
|
+
|
|
166
|
+
async close(): Promise<void> {
|
|
167
|
+
closing = true;
|
|
168
|
+
if (exited) return;
|
|
169
|
+
child.stdin?.end();
|
|
170
|
+
for (const signal of ["SIGTERM", "SIGKILL"] as const) {
|
|
171
|
+
if (await settles(exit, EXIT_GRACE_MS)) return;
|
|
172
|
+
child.kill(signal);
|
|
173
|
+
}
|
|
174
|
+
await settles(exit, EXIT_GRACE_MS);
|
|
175
|
+
},
|
|
176
|
+
};
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Whether `promise` settles within `ms`. */
|
|
180
|
+
async function settles(promise: Promise<void>, ms: number): Promise<boolean> {
|
|
181
|
+
let timer: NodeJS.Timeout | undefined;
|
|
182
|
+
const late = new Promise<false>((resolve) => {
|
|
183
|
+
timer = setTimeout(() => resolve(false), ms);
|
|
184
|
+
});
|
|
185
|
+
try {
|
|
186
|
+
return await Promise.race([promise.then(() => true as const), late]);
|
|
187
|
+
} finally {
|
|
188
|
+
clearTimeout(timer);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The worker `ream mcp:serve` starts: `node worker-main.js <tools.json>`.
|
|
3
|
+
* See `worker.ts` for the protocol.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import { pathToFileURL } from "node:url";
|
|
8
|
+
import { startWorker } from "./worker.js";
|
|
9
|
+
|
|
10
|
+
const main = process.argv[1];
|
|
11
|
+
if (main !== undefined && import.meta.url === pathToFileURL(main).href) {
|
|
12
|
+
await startWorker(process.argv[2], {
|
|
13
|
+
readFile: (path) => readFile(path, "utf8"),
|
|
14
|
+
process,
|
|
15
|
+
});
|
|
16
|
+
// The application may hold handles open (a database pool): the session is over.
|
|
17
|
+
process.exit();
|
|
18
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The worker protocol: how `ream mcp:serve` has the application's tools run
|
|
3
|
+
* by a long-lived Node process. One JSON object per line, both ways.
|
|
4
|
+
*
|
|
5
|
+
* Started as `node <worker> <tools.json>`, the worker imports the module the
|
|
6
|
+
* manifest names, then writes `{"type":"ready","protocol":1}`; when it cannot,
|
|
7
|
+
* `{"type":"failed","message":"..."}`, and it exits with code 1.
|
|
8
|
+
*
|
|
9
|
+
* Then, from the parent:
|
|
10
|
+
* {"type":"call","id":1,"name":"canton_rate","input":{...}}
|
|
11
|
+
* {"type":"cancel","id":1}
|
|
12
|
+
* and from the worker:
|
|
13
|
+
* {"type":"result","id":1,"ok":true,"content":"..."}
|
|
14
|
+
* {"type":"error","id":null,"message":"..."} a line it could not read
|
|
15
|
+
*
|
|
16
|
+
* Calls run side by side; each is answered once. `ok: false` is a failure
|
|
17
|
+
* meant for the agent (unknown tool, refused input, the tool's error), never
|
|
18
|
+
* a stack trace. The worker leaves when its stdin ends. stdout carries only
|
|
19
|
+
* the protocol: what the application writes there goes to stderr.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
import { resolve } from "node:path";
|
|
23
|
+
import type { Readable } from "node:stream";
|
|
24
|
+
import { pathToFileURL } from "node:url";
|
|
25
|
+
import { loadTools, type OnHostedToolError, ToolHost } from "./host.js";
|
|
26
|
+
import { isObject } from "./rpc.js";
|
|
27
|
+
|
|
28
|
+
/** The version of the protocol above. */
|
|
29
|
+
export const WORKER_PROTOCOL = 1;
|
|
30
|
+
|
|
31
|
+
/** The longest line the worker reads, in bytes. */
|
|
32
|
+
export const MAX_WORKER_LINE = 4 * 1024 * 1024;
|
|
33
|
+
|
|
34
|
+
export interface WorkerOptions {
|
|
35
|
+
readonly tools: readonly unknown[];
|
|
36
|
+
/** Where the parent's lines come from. */
|
|
37
|
+
readonly input: Readable;
|
|
38
|
+
/** Write one line (without its end) to the parent. */
|
|
39
|
+
readonly write: (line: string) => void;
|
|
40
|
+
readonly onToolError?: OnHostedToolError;
|
|
41
|
+
readonly maxLineBytes?: number;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
type Id = string | number;
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* Serve the protocol until `input` ends. Writes `ready` first. Resolves once
|
|
48
|
+
* the input ended and every call was answered.
|
|
49
|
+
*/
|
|
50
|
+
export async function runWorker(options: WorkerOptions): Promise<void> {
|
|
51
|
+
const host = new ToolHost(options.tools, options.onToolError);
|
|
52
|
+
const max = options.maxLineBytes ?? MAX_WORKER_LINE;
|
|
53
|
+
const send = (message: Record<string, unknown>): void =>
|
|
54
|
+
options.write(JSON.stringify(message));
|
|
55
|
+
const running = new Map<Id, AbortController>();
|
|
56
|
+
const settled: Promise<void>[] = [];
|
|
57
|
+
|
|
58
|
+
const handle = (line: string): void => {
|
|
59
|
+
let message: unknown;
|
|
60
|
+
try {
|
|
61
|
+
message = JSON.parse(line);
|
|
62
|
+
} catch {
|
|
63
|
+
send({ type: "error", id: null, message: "The line is not JSON." });
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const id = isObject(message) ? message.id : undefined;
|
|
67
|
+
if (
|
|
68
|
+
!isObject(message) ||
|
|
69
|
+
(typeof id !== "string" && typeof id !== "number")
|
|
70
|
+
) {
|
|
71
|
+
send({ type: "error", id: null, message: "The message has no id." });
|
|
72
|
+
return;
|
|
73
|
+
}
|
|
74
|
+
if (message.type === "cancel") {
|
|
75
|
+
running.get(id)?.abort();
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if (message.type !== "call" || typeof message.name !== "string") {
|
|
79
|
+
send({
|
|
80
|
+
type: "error",
|
|
81
|
+
id,
|
|
82
|
+
message: "The message is neither a call nor a cancel.",
|
|
83
|
+
});
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (running.has(id)) {
|
|
87
|
+
send({ type: "error", id, message: "A call with this id is running." });
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
const controller = new AbortController();
|
|
91
|
+
running.set(id, controller);
|
|
92
|
+
settled.push(
|
|
93
|
+
host
|
|
94
|
+
.call(message.name, message.input, { signal: controller.signal })
|
|
95
|
+
.then((result) => {
|
|
96
|
+
running.delete(id);
|
|
97
|
+
send({ type: "result", id, ...result });
|
|
98
|
+
}),
|
|
99
|
+
);
|
|
100
|
+
};
|
|
101
|
+
|
|
102
|
+
send({ type: "ready", protocol: WORKER_PROTOCOL });
|
|
103
|
+
|
|
104
|
+
const tooLong = (): void =>
|
|
105
|
+
send({
|
|
106
|
+
type: "error",
|
|
107
|
+
id: null,
|
|
108
|
+
message: `The line is longer than ${max} bytes.`,
|
|
109
|
+
});
|
|
110
|
+
let pending = "";
|
|
111
|
+
let skipping = false;
|
|
112
|
+
options.input.setEncoding("utf8");
|
|
113
|
+
for await (const chunk of options.input) {
|
|
114
|
+
let text = pending + String(chunk);
|
|
115
|
+
pending = "";
|
|
116
|
+
let start = 0;
|
|
117
|
+
let newline = text.indexOf("\n");
|
|
118
|
+
while (newline !== -1) {
|
|
119
|
+
const line = text.slice(start, newline).trim();
|
|
120
|
+
if (skipping) skipping = false;
|
|
121
|
+
else if (Buffer.byteLength(line, "utf8") > max) tooLong();
|
|
122
|
+
else if (line !== "") handle(line);
|
|
123
|
+
start = newline + 1;
|
|
124
|
+
newline = text.indexOf("\n", start);
|
|
125
|
+
}
|
|
126
|
+
text = text.slice(start);
|
|
127
|
+
if (skipping) continue;
|
|
128
|
+
if (Buffer.byteLength(text, "utf8") > max) {
|
|
129
|
+
tooLong();
|
|
130
|
+
skipping = true;
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
pending = text;
|
|
134
|
+
}
|
|
135
|
+
if (!skipping && pending.trim() !== "") handle(pending.trim());
|
|
136
|
+
await Promise.all(settled);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** What {@link startWorker} needs of the process, so a test can stand in. */
|
|
140
|
+
export interface WorkerProcess {
|
|
141
|
+
readonly readFile: (path: string) => Promise<string>;
|
|
142
|
+
readonly process: Pick<
|
|
143
|
+
NodeJS.Process,
|
|
144
|
+
"stdin" | "stdout" | "stderr" | "exitCode"
|
|
145
|
+
> & {
|
|
146
|
+
on(
|
|
147
|
+
event: "unhandledRejection",
|
|
148
|
+
listener: (reason: unknown) => void,
|
|
149
|
+
): unknown;
|
|
150
|
+
};
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Read the manifest, import its tools, and serve the protocol on the
|
|
155
|
+
* process's stdin and stdout. What the application writes to stdout goes to
|
|
156
|
+
* stderr. A failure to start is written as `failed`, with exit code 1.
|
|
157
|
+
*/
|
|
158
|
+
export async function startWorker(
|
|
159
|
+
manifestPath: string | undefined,
|
|
160
|
+
{ readFile, process: proc }: WorkerProcess,
|
|
161
|
+
): Promise<void> {
|
|
162
|
+
const out = proc.stdout.write.bind(proc.stdout);
|
|
163
|
+
const write = (line: string): void => {
|
|
164
|
+
out(`${line}\n`);
|
|
165
|
+
};
|
|
166
|
+
// Only the protocol on stdout: console.log and the like go to stderr.
|
|
167
|
+
proc.stdout.write = proc.stderr.write.bind(proc.stderr);
|
|
168
|
+
const log = (text: string): void => {
|
|
169
|
+
proc.stderr.write(`[polaris worker] ${text}\n`);
|
|
170
|
+
};
|
|
171
|
+
proc.on("unhandledRejection", (reason) => {
|
|
172
|
+
log(
|
|
173
|
+
`unhandled rejection: ${reason instanceof Error ? reason.message : String(reason)}`,
|
|
174
|
+
);
|
|
175
|
+
});
|
|
176
|
+
|
|
177
|
+
let tools: unknown[];
|
|
178
|
+
try {
|
|
179
|
+
if (manifestPath === undefined) {
|
|
180
|
+
throw new Error("usage: node worker-main.js <tools.json>");
|
|
181
|
+
}
|
|
182
|
+
const manifest: unknown = JSON.parse(await readFile(manifestPath));
|
|
183
|
+
if (!isObject(manifest) || typeof manifest.module !== "string") {
|
|
184
|
+
throw new Error(`'${manifestPath}' is not a tools manifest`);
|
|
185
|
+
}
|
|
186
|
+
if (manifest.protocol !== WORKER_PROTOCOL) {
|
|
187
|
+
throw new Error(
|
|
188
|
+
`'${manifestPath}' asks for worker protocol ${String(manifest.protocol)}; this polaris speaks ${WORKER_PROTOCOL}`,
|
|
189
|
+
);
|
|
190
|
+
}
|
|
191
|
+
const base = pathToFileURL(resolve(manifestPath));
|
|
192
|
+
tools = await loadTools(new URL(manifest.module, base));
|
|
193
|
+
} catch (error) {
|
|
194
|
+
write(
|
|
195
|
+
JSON.stringify({
|
|
196
|
+
type: "failed",
|
|
197
|
+
message: error instanceof Error ? error.message : String(error),
|
|
198
|
+
}),
|
|
199
|
+
);
|
|
200
|
+
proc.exitCode = 1;
|
|
201
|
+
return;
|
|
202
|
+
}
|
|
203
|
+
await runWorker({
|
|
204
|
+
tools,
|
|
205
|
+
input: proc.stdin,
|
|
206
|
+
write,
|
|
207
|
+
onToolError: (error, call) =>
|
|
208
|
+
log(
|
|
209
|
+
`'${call.name}' failed: ${error instanceof Error ? (error.stack ?? error.message) : String(error)}`,
|
|
210
|
+
),
|
|
211
|
+
});
|
|
212
|
+
}
|