@koneeric/onetool 0.0.0-stage → 0.3.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.
@@ -0,0 +1,142 @@
1
+ // The command: arguments, settings, the server on standard input and output, the end.
2
+ import { readFileSync } from "node:fs";
3
+ import { resolve } from "node:path";
4
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
5
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
6
+ import {
7
+ CallToolRequestSchema,
8
+ ErrorCode,
9
+ GetPromptRequestSchema,
10
+ ListPromptsRequestSchema,
11
+ ListToolsRequestSchema,
12
+ McpError,
13
+ } from "@modelcontextprotocol/sdk/types.js";
14
+ import { INSTRUCTIONS, readSettings, SettingsError } from "../../core/src/index.js";
15
+ import { missingFolders } from "../../shell/src/index.js";
16
+ import { Connection } from "./connect.js";
17
+ import { makeHost } from "./host.js";
18
+ import { runInit } from "./init.js";
19
+ import { TIDY_DESCRIPTION, TIDY_NAME, TIDY_TEXT } from "./prompt.js";
20
+ import { LOGIN_USAGE, LOGOUT_USAGE, parseSignArgs, runLogin, runLogout } from "./sign.js";
21
+ import { makeTools } from "./tools.js";
22
+
23
+ const USAGE = "usage: onetool --config <settings file>";
24
+ const END_MS = 4500;
25
+
26
+ const version = JSON.parse(readFileSync(new URL("../../package.json", import.meta.url), "utf8")).version;
27
+
28
+ const say = (line) => process.stderr.write(`${line}\n`);
29
+
30
+ /** The settings of the file at `path`, or `null` once its problems are written (the exit code is then 2). */
31
+ function settingsOf(path) {
32
+ try {
33
+ return readSettings(path);
34
+ } catch (err) {
35
+ if (!(err instanceof SettingsError)) throw err;
36
+ for (const problem of err.problems) say(`onetool: ${problem}`);
37
+ process.exitCode = 2;
38
+ return null;
39
+ }
40
+ }
41
+
42
+ /** `login` or `logout`: one thing is done, and the process ends. */
43
+ async function signCommand(word, rest) {
44
+ const parsed = parseSignArgs(word, rest);
45
+ if (parsed === null) {
46
+ say(word === "login" ? LOGIN_USAGE : LOGOUT_USAGE);
47
+ process.exitCode = 2;
48
+ return;
49
+ }
50
+ const settings = settingsOf(parsed.config);
51
+ if (settings === null) return;
52
+ if (word === "login") await runLogin(parsed.server, settings, parsed);
53
+ else runLogout(parsed.server);
54
+ }
55
+
56
+ export async function main(argv) {
57
+ if (argv[0] === "init") {
58
+ process.exitCode = await runInit(argv.slice(1));
59
+ return;
60
+ }
61
+ if (argv[0] === "login" || argv[0] === "logout") return signCommand(argv[0], argv.slice(1));
62
+ if (argv.length !== 2 || argv[0] !== "--config") {
63
+ say(USAGE);
64
+ process.exitCode = 2;
65
+ return;
66
+ }
67
+ const settings = settingsOf(argv[1]);
68
+ if (settings === null) return;
69
+
70
+ if (settings.shell !== null && settings.shell.folders !== null) {
71
+ const missing = await missingFolders(settings.shell.folders);
72
+ for (const position of missing) say(`onetool: onetool.shell.folders: item ${position + 1} is not a folder`);
73
+ if (missing.length > 0) {
74
+ process.exitCode = 2;
75
+ return;
76
+ }
77
+ }
78
+
79
+ const connections = settings.servers.map(
80
+ (entry) => new Connection(entry.name, entry, settings.connectSeconds, version),
81
+ );
82
+ // a list of tools that can change: the description of `run` follows the folders of the host program
83
+ const listChanged = settings.shell !== null && settings.shell.folders === null;
84
+ // ... and so does what a sign-in server offers, once the person has signed in or out
85
+ const signIns = connections.some((connection) => connection.signIn);
86
+ const server = new Server(
87
+ { name: "onetool", version },
88
+ {
89
+ capabilities: { tools: listChanged || signIns ? { listChanged: true } : {}, prompts: {} },
90
+ ...(settings.instructions ? { instructions: INSTRUCTIONS } : {}),
91
+ },
92
+ );
93
+ const host = makeHost(settings, server);
94
+ const tools = makeTools(settings, connections, server, host, resolve(argv[1]));
95
+
96
+ server.setRequestHandler(ListToolsRequestSchema, async () => {
97
+ host.start();
98
+ if (listChanged) await host.idle();
99
+ return { tools: await tools.list() };
100
+ });
101
+ server.setRequestHandler(CallToolRequestSchema, async (request) =>
102
+ tools.call(request.params.name, request.params.arguments),
103
+ );
104
+
105
+ server.setRequestHandler(ListPromptsRequestSchema, async () => ({
106
+ prompts: [{ name: TIDY_NAME, description: TIDY_DESCRIPTION }],
107
+ }));
108
+ server.setRequestHandler(GetPromptRequestSchema, async (request) => {
109
+ if (request.params.name !== TIDY_NAME) throw new McpError(ErrorCode.InvalidParams, `unknown prompt: ${request.params.name}`);
110
+ return { description: TIDY_DESCRIPTION, messages: [{ role: "user", content: { type: "text", text: TIDY_TEXT } }] };
111
+ });
112
+
113
+ let ending = false;
114
+ const end = async () => {
115
+ if (ending) return;
116
+ ending = true;
117
+ const hard = setTimeout(() => {
118
+ for (const connection of connections) connection.kill();
119
+ process.exit(0);
120
+ }, END_MS);
121
+ await Promise.allSettled([server.close(), ...connections.map((connection) => connection.close())]);
122
+ clearTimeout(hard);
123
+ process.exit(0);
124
+ };
125
+ process.on("SIGINT", end);
126
+ process.on("SIGTERM", end);
127
+ process.stdout.on("error", () => {});
128
+
129
+ await server.connect(new StdioServerTransport());
130
+ process.stdin.on("end", end);
131
+ process.stdin.on("close", end);
132
+
133
+ // the entries that cannot be used are told first, before any connection is tried
134
+ for (const { name, reason } of settings.bad) say(`onetool: server ${name}: not connected (bad entry: ${reason})`);
135
+ tools.ready = Promise.all(
136
+ connections.map(async (connection) => {
137
+ await connection.connect();
138
+ if (connection.error !== null) say(`onetool: server ${connection.name}: not connected (${connection.error})`);
139
+ else if (connection.needed) say(`onetool: server ${connection.name}: sign in needed`);
140
+ }),
141
+ );
142
+ }
@@ -0,0 +1,15 @@
1
+ // The prompt `tidy-library`: fixed texts, the same whatever the settings and the library hold.
2
+
3
+ export const TIDY_NAME = "tidy-library";
4
+
5
+ export const TIDY_DESCRIPTION = "Tidy the library of saved programs: merge the ones that repeat, retire the ones not used, and rename the unclear.";
6
+
7
+ export const TIDY_TEXT = [
8
+ "Tidy the library of saved programs, with the person.",
9
+ "1. Run a program that returns `await library.report()`. It tells, for each saved program, its uses, its failures and its last use, the programs that share most of their tools, the programs not used for a long time, and the sequences of calls that ran again and again without being saved.",
10
+ "2. Open, with `library.read(name)`, only the programs worth comparing: those of a pair, those not used, those that fail. Do not read the others.",
11
+ "3. Propose to the person what to merge, retire, rename or save, with the reason of each. Do not apply any of it yet.",
12
+ "Change nothing before the person says yes.",
13
+ "4. When the person says yes, apply what they accepted, and only that: `library.save` to save a program, with `replace: true` to put it in the place of another, and `library.remove` to retire one.",
14
+ "5. Say that what was replaced or removed is in the archive, and that `library.restore(name)` brings it back.",
15
+ ].join("\n");
@@ -0,0 +1,131 @@
1
+ // The record of every call: one record per call a program makes, the trail at the end of an answer, the log file.
2
+ import { randomUUID } from "node:crypto";
3
+ import { appendFile, mkdir } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import { callSize, formatTrail, logFileName, logLine, shellLogArgs } from "../../core/src/index.js";
7
+ import { logArgs } from "../../library/src/index.js";
8
+
9
+ const DEFAULT_FOLDER = fileURLToPath(new URL("../../logs", import.meta.url));
10
+ const FAULT_LIMIT = 500;
11
+
12
+ /** An `Error` for a call that was refused: `why` is `"rules"` (deny, allow, ask) or `"outside"` (a path outside). */
13
+ export function refused(message, why) {
14
+ return Object.assign(new Error(message), { refusal: why });
15
+ }
16
+
17
+ const FAULTS = { rules: "refused by the rules", outside: "outside the listed folders" };
18
+
19
+ /** The log file: lines queued in the order the records were completed, each appended whole. */
20
+ function makeLog(settings, session, fail) {
21
+ if (!settings.log) return { write() {}, flush: async () => {} };
22
+ const folder = typeof settings.logFolder === "string" ? settings.logFolder : DEFAULT_FOLDER;
23
+ let tail = Promise.resolve();
24
+ return {
25
+ write(record) {
26
+ let text;
27
+ try {
28
+ text = `${logLine({ ...record, session })}\n`;
29
+ } catch {
30
+ fail();
31
+ return;
32
+ }
33
+ tail = tail.then(async () => {
34
+ try {
35
+ await mkdir(folder, { recursive: true });
36
+ await appendFile(join(folder, logFileName(record.time)), text);
37
+ } catch {
38
+ fail();
39
+ }
40
+ });
41
+ },
42
+ flush: () => tail,
43
+ };
44
+ }
45
+
46
+ /**
47
+ * The records of the process: `program()` gives the records of one program. `session` is the text of the lines of the log;
48
+ * `failed()` says once, for the life of the process, that the log cannot be written (the file of the sequences shares it).
49
+ */
50
+ export function makeRecords(settings) {
51
+ const session = randomUUID();
52
+ let told = false;
53
+ const failed = () => {
54
+ if (told) return;
55
+ told = true;
56
+ process.stderr.write("onetool: the log cannot be written\n");
57
+ };
58
+ const log = makeLog(settings, session, failed);
59
+
60
+ function program() {
61
+ const calls = [];
62
+ // the lines the program's trail ends with, after its calls
63
+ const notes = [];
64
+ let over = false;
65
+
66
+ function complete(record, fields) {
67
+ if (record.done) return;
68
+ record.done = true;
69
+ record.ms = Math.max(0, Math.floor(performance.now() - record.began));
70
+ Object.assign(record, fields);
71
+ log.write(record);
72
+ }
73
+
74
+ // what the log keeps of the arguments of a call of a built-in server: never the text of a file or of a program
75
+ const loggedArgs = (serverName, tool, args) => {
76
+ if (serverName === "shell" && settings.shell !== null) return shellLogArgs(tool, args);
77
+ if (serverName === "library") return logArgs(tool, args);
78
+ return args;
79
+ };
80
+
81
+ return {
82
+ calls,
83
+ notes,
84
+ /** A call begins: the record is kept, its decision is for the caller to set. */
85
+ begin(serverName, tool, args) {
86
+ const record = {
87
+ time: Date.now(),
88
+ began: performance.now(),
89
+ id: `${serverName}.${tool}`,
90
+ args: loggedArgs(serverName, tool, args),
91
+ decision: "allowed",
92
+ outcome: null,
93
+ ms: 0,
94
+ size: null,
95
+ fault: null,
96
+ done: over,
97
+ };
98
+ if (!over) calls.push(record);
99
+ return record;
100
+ },
101
+ resolved(record, value) {
102
+ if (record.id === "shell.run" && settings.shell !== null && value?.exitCode !== 0) {
103
+ complete(record, { outcome: "failed", fault: `exit code ${value?.exitCode}` });
104
+ return;
105
+ }
106
+ complete(record, { outcome: "ok", size: callSize(value) });
107
+ },
108
+ rejected(record, err) {
109
+ if (err?.refusal !== undefined) {
110
+ complete(record, { outcome: "refused", fault: FAULTS[err.refusal] });
111
+ return;
112
+ }
113
+ complete(record, { outcome: "failed", fault: String(err?.message ?? err).slice(0, FAULT_LIMIT) });
114
+ },
115
+ /** The program's result is there: what has not ended is complete now, and the file holds every line. */
116
+ async close() {
117
+ over = true;
118
+ for (const record of calls) complete(record, { outcome: "unfinished", fault: "unfinished" });
119
+ await log.flush();
120
+ },
121
+ trail() {
122
+ return formatTrail(
123
+ calls.map(({ id, ms, size, outcome }) => ({ id, ms, size, outcome })),
124
+ { notes },
125
+ );
126
+ },
127
+ };
128
+ }
129
+
130
+ return { program, session, failed };
131
+ }
@@ -0,0 +1,98 @@
1
+ // The commands `onetool login` and `onetool logout`: the arguments, and what each prints. The sign-in itself is part `auth`'s.
2
+ import { spawn } from "node:child_process";
3
+ import { browserCommand, login, logout } from "../../auth/src/index.js";
4
+ import { signsIn } from "../../core/src/index.js";
5
+
6
+ export const LOGIN_USAGE = "usage: onetool login <server> --config <settings file> [--no-browser] [--wait <seconds>]";
7
+ export const LOGOUT_USAGE = "usage: onetool logout <server> --config <settings file>";
8
+
9
+ const WAIT_DEFAULT = 300;
10
+
11
+ /**
12
+ * The arguments of `login` or `logout` (`word` is the first, `rest` the others): `{ server, config, noBrowser, waitSeconds }`,
13
+ * or `null` when they are not as the table says.
14
+ */
15
+ export function parseSignArgs(word, rest) {
16
+ const isLogin = word === "login";
17
+ if (rest.length === 0 || rest[0] === "") return null;
18
+ const parsed = { server: rest[0], config: null, noBrowser: false, waitSeconds: WAIT_DEFAULT };
19
+ let waitSeen = false;
20
+ for (let i = 1; i < rest.length; i += 1) {
21
+ const option = rest[i];
22
+ if (option === "--config" && parsed.config === null) {
23
+ if (i + 1 >= rest.length) return null;
24
+ parsed.config = rest[(i += 1)];
25
+ } else if (isLogin && option === "--no-browser" && !parsed.noBrowser) {
26
+ parsed.noBrowser = true;
27
+ } else if (isLogin && option === "--wait" && !waitSeen) {
28
+ if (i + 1 >= rest.length || !/^[0-9]+$/.test(rest[i + 1])) return null;
29
+ const seconds = Number(rest[(i += 1)]);
30
+ if (seconds < 1 || seconds > 3600) return null;
31
+ parsed.waitSeconds = seconds;
32
+ waitSeen = true;
33
+ } else {
34
+ return null;
35
+ }
36
+ }
37
+ return parsed.config === null ? null : parsed;
38
+ }
39
+
40
+ const out = (line) => process.stdout.write(`${line}\n`);
41
+
42
+ // the last line is flushed, then the process ends at once, whatever is still in flight
43
+ function finish(stream, line, code) {
44
+ stream.on("error", () => {});
45
+ stream.write(`${line}\n`, () => process.exit(code));
46
+ return new Promise(() => {});
47
+ }
48
+
49
+ /** Starts the browser on `address` and does not wait for it; a program that cannot be started is ignored. */
50
+ function openBrowser(address) {
51
+ const command = browserCommand(address);
52
+ if (command === null) return;
53
+ try {
54
+ const child = spawn(command[0], command.slice(1), { stdio: "ignore", detached: true, shell: false });
55
+ child.on("error", () => {});
56
+ child.unref();
57
+ } catch {
58
+ // the printed address is the way
59
+ }
60
+ }
61
+
62
+ /** One sign-in, then the end of the process. `settings` is what `readSettings` gave. */
63
+ export async function runLogin(server, settings, { noBrowser, waitSeconds }) {
64
+ const entry = settings.servers.find((candidate) => candidate.name === server);
65
+ if (entry === undefined) return fail(`onetool: login: ${server} is not a server of the settings file`);
66
+ if (!Object.hasOwn(entry, "url")) return fail(`onetool: login: ${server} is started by a command, there is nothing to sign in to`);
67
+ if (!signsIn(entry)) return fail(`onetool: login: ${server} has an Authorization header in the settings file`);
68
+ let result;
69
+ try {
70
+ result = await login(
71
+ { name: entry.name, url: entry.url, oauth: entry.oauth },
72
+ {
73
+ waitSeconds,
74
+ say: (address) => out(`onetool: to sign in to ${server}, open ${address}`),
75
+ ...(noBrowser ? {} : { open: openBrowser }),
76
+ },
77
+ );
78
+ } catch {
79
+ result = { ok: false, reason: "the sign-in could not be started" };
80
+ }
81
+ if (result.ok) {
82
+ return finish(process.stdout, `onetool: signed in to ${server}`, 0);
83
+ }
84
+ return fail(`onetool: login: ${server}: ${result.reason}`);
85
+ }
86
+
87
+ /** The sign-in of `server` is forgotten, then the end of the process. */
88
+ export function runLogout(server) {
89
+ let had;
90
+ try {
91
+ had = logout(server);
92
+ } catch {
93
+ return fail(`onetool: logout: ${server}: the sign-in could not be removed`);
94
+ }
95
+ return finish(process.stdout, had ? `onetool: signed out of ${server}` : `onetool: ${server} had no sign-in`, 0);
96
+ }
97
+
98
+ const fail = (line) => finish(process.stderr, line, 1);