turno-cli 0.1.1 → 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.
- package/CHANGELOG.md +432 -0
- package/README.md +228 -73
- package/dist/accounts/audit.js +154 -12
- package/dist/accounts/builtin.js +100 -25
- package/dist/accounts/delegate.js +199 -35
- package/dist/accounts/policy.js +79 -0
- package/dist/accounts/registry.js +39 -21
- package/dist/agents/adapter.js +29 -0
- package/dist/agents/claude.js +246 -0
- package/dist/agents/codex.js +186 -0
- package/dist/agents/copilot.js +56 -0
- package/dist/agents/cursor.js +58 -0
- package/dist/agents/index.js +26 -86
- package/dist/agents/snippets.js +43 -13
- package/dist/cli/args.js +38 -6
- package/dist/cli/commands/accounts.js +119 -52
- package/dist/cli/commands/auto.js +121 -33
- package/dist/cli/commands/browser-identity.js +514 -0
- package/dist/cli/commands/browser-session.js +102 -0
- package/dist/cli/commands/browser-vault.js +193 -0
- package/dist/cli/commands/browser.js +319 -138
- package/dist/cli/commands/complete.js +14 -3
- package/dist/cli/commands/completion.js +8 -2
- package/dist/cli/commands/config.js +186 -24
- package/dist/cli/commands/demo.js +321 -0
- package/dist/cli/commands/doctor.js +525 -123
- package/dist/cli/commands/handoff.js +33 -22
- package/dist/cli/commands/identity.js +192 -54
- package/dist/cli/commands/init.js +648 -0
- package/dist/cli/commands/limit.js +84 -16
- package/dist/cli/commands/mcp-call.js +240 -0
- package/dist/cli/commands/mcp-oauth.js +221 -0
- package/dist/cli/commands/mcp-observe.js +539 -0
- package/dist/cli/commands/mcp-share.js +201 -0
- package/dist/cli/commands/mcp.js +816 -187
- package/dist/cli/commands/mcpd.js +388 -76
- package/dist/cli/commands/migrate.js +6 -4
- package/dist/cli/commands/open.js +115 -27
- package/dist/cli/commands/profile.js +396 -78
- package/dist/cli/commands/resolve.js +14 -3
- package/dist/cli/commands/run.js +36 -6
- package/dist/cli/commands/secret.js +80 -76
- package/dist/cli/commands/session.js +17 -6
- package/dist/cli/commands/sessions.js +48 -12
- package/dist/cli/commands/setup.js +214 -164
- package/dist/cli/commands/status.js +227 -44
- package/dist/cli/commands/statusline.js +311 -114
- package/dist/cli/commands/ui.js +78 -68
- package/dist/cli/commands/undo.js +193 -18
- package/dist/cli/commands/uninstall.js +481 -0
- package/dist/cli/commands/upgrade.js +172 -79
- package/dist/cli/commands/usage.js +125 -51
- package/dist/cli/commands/version.js +21 -7
- package/dist/cli/commands/which.js +9 -24
- package/dist/cli/compile-cache.js +32 -0
- package/dist/cli/diagnostics.js +184 -0
- package/dist/cli/exit.js +65 -0
- package/dist/cli/group.js +24 -12
- package/dist/cli/help.js +62 -0
- package/dist/cli/highlight.js +236 -0
- package/dist/cli/hints.js +30 -0
- package/dist/cli/io.js +186 -1
- package/dist/cli/launch.js +52 -39
- package/dist/cli/launchers.js +161 -95
- package/dist/cli/main.js +201 -31
- package/dist/cli/optional.js +144 -0
- package/dist/cli/output.js +123 -0
- package/dist/cli/picker.js +459 -0
- package/dist/cli/registry.js +61 -6
- package/dist/cli/safe.js +87 -0
- package/dist/cli/secret-input.js +63 -0
- package/dist/cli/security.js +561 -0
- package/dist/cli/style.js +311 -0
- package/dist/cli/topics.js +142 -0
- package/dist/core/config.js +181 -23
- package/dist/core/exhausted.js +6 -8
- package/dist/core/fsutil.js +39 -0
- package/dist/core/journal.js +294 -16
- package/dist/core/manifest.js +153 -6
- package/dist/core/paths.js +14 -13
- package/dist/core/profiles.js +160 -10
- package/dist/core/resolve.js +139 -23
- package/dist/core/secrets.js +68 -23
- package/dist/core/sessions.js +13 -20
- package/dist/core/state-file.js +107 -0
- package/dist/core/update.js +31 -18
- package/dist/core/version.js +57 -10
- package/dist/demo/server.js +42 -0
- package/dist/mcpd/cache.js +23 -10
- package/dist/mcpd/calllog.js +254 -0
- package/dist/mcpd/client-names.js +46 -0
- package/dist/mcpd/connectors.js +188 -18
- package/dist/mcpd/daemon.js +472 -115
- package/dist/mcpd/folder-sets.js +42 -0
- package/dist/mcpd/gateway.js +473 -51
- package/dist/mcpd/health.js +313 -0
- package/dist/mcpd/importer.js +453 -36
- package/dist/mcpd/instances.js +453 -65
- package/dist/mcpd/jsonrpc.js +11 -1
- package/dist/mcpd/launchd.js +65 -48
- package/dist/mcpd/middleware.js +144 -0
- package/dist/mcpd/modern.js +686 -0
- package/dist/mcpd/oauth.js +845 -0
- package/dist/mcpd/peerpid.js +134 -6
- package/dist/mcpd/pressure.js +88 -0
- package/dist/mcpd/rss.js +166 -0
- package/dist/mcpd/service.js +191 -0
- package/dist/mcpd/share.js +217 -0
- package/dist/mcpd/state.js +183 -0
- package/dist/mcpd/sync.js +72 -87
- package/dist/mcpd/systemd.js +83 -0
- package/dist/mcpd/tokens.js +85 -0
- package/dist/mcpd/upstream.js +163 -46
- package/dist/statusline/cost.js +167 -44
- package/dist/statusline/input.js +78 -0
- package/dist/statusline/render.js +9 -3
- package/dist/ui/fonts.js +8 -3
- package/dist/ui/settings.js +33 -16
- package/npm-shrinkwrap.json +1102 -0
- package/package.json +10 -9
- package/dist/cli/commands/available.js +0 -18
|
@@ -1,10 +1,12 @@
|
|
|
1
|
+
import { adapter } from "../../agents/index.js";
|
|
1
2
|
import { loadConfig } from "../../core/config.js";
|
|
2
3
|
import { clearExhausted, exhaustedUntil, markExhausted } from "../../core/exhausted.js";
|
|
3
4
|
import { agentOf, listProfiles } from "../../core/profiles.js";
|
|
4
5
|
import { formatUntil } from "../../core/resolve.js";
|
|
5
|
-
import { DRY_RUN, JSON_FLAG, WATCH, bool,
|
|
6
|
+
import { DRY_RUN, JSON_FLAG, WATCH, bool, flagsOf, parseFlags, str } from "../args.js";
|
|
6
7
|
import { group } from "../group.js";
|
|
7
8
|
import { fail } from "../io.js";
|
|
9
|
+
import { emit, emitLines, jsonOutput } from "../output.js";
|
|
8
10
|
import { launcherPath } from "../launch.js";
|
|
9
11
|
import { parseLocalDateTime } from "./exhausted.js";
|
|
10
12
|
import { command as usage, account, usageSnapshot } from "./usage.js";
|
|
@@ -20,11 +22,15 @@ export async function limitsData(env, withAccounts = true) {
|
|
|
20
22
|
const config = loadConfig(env);
|
|
21
23
|
const profiles = listProfiles(config, env);
|
|
22
24
|
// Usage windows and accounts come from Claude Code; other agents show only exhausted marks.
|
|
23
|
-
const accounts = withAccounts
|
|
25
|
+
const accounts = withAccounts
|
|
26
|
+
? await Promise.all(profiles.map((p) => (adapter(agentOf(p, config)).accountDetails ? account(p, env) : undefined)))
|
|
27
|
+
: [];
|
|
24
28
|
return profiles.map((p, i) => {
|
|
25
29
|
const snap = usageSnapshot(p, env);
|
|
26
30
|
const limits = snap.rate_limits ?? {};
|
|
27
|
-
const win = (w) => w
|
|
31
|
+
const win = (w) => w
|
|
32
|
+
? { used: Number(w.used_percentage) || 0, resetsAt: typeof w.resets_at === "number" ? w.resets_at : null }
|
|
33
|
+
: null;
|
|
28
34
|
return {
|
|
29
35
|
profile: p,
|
|
30
36
|
agent: agentOf(p, config),
|
|
@@ -36,28 +42,70 @@ export async function limitsData(env, withAccounts = true) {
|
|
|
36
42
|
};
|
|
37
43
|
});
|
|
38
44
|
}
|
|
45
|
+
const SHOW_SPEC = { ...JSON_FLAG, ...WATCH };
|
|
46
|
+
/** `turno limit show --json`: one element per profile. */
|
|
47
|
+
const SHOW_JSON = jsonOutput(["profile", "agent", "email", "plan", "exhaustedUntil", "fiveHour", "week", "updatedAt"]);
|
|
48
|
+
/** How often `limit show --watch --json` prints the profiles again. */
|
|
49
|
+
const WATCH_EVERY_MS = 30_000;
|
|
39
50
|
async function show(args, io) {
|
|
40
|
-
const p = parseFlags(args,
|
|
51
|
+
const p = parseFlags(args, SHOW_SPEC, 0);
|
|
41
52
|
if (bool(p, "json")) {
|
|
42
53
|
if (bool(p, "watch"))
|
|
43
|
-
|
|
44
|
-
|
|
54
|
+
return watchJson(io, p);
|
|
55
|
+
emit(io, p, SHOW_JSON, await limitsData(io.env));
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
|
58
|
+
const config = loadConfig(io.env);
|
|
59
|
+
if (!listProfiles(config, io.env).length) {
|
|
60
|
+
io.out("No profiles yet (turno profile add <name>).");
|
|
61
|
+
return 0;
|
|
62
|
+
}
|
|
63
|
+
if (!listProfiles(config, io.env, "claude").length) {
|
|
64
|
+
io.out("Usage limits come from Claude Code profiles, and there are none yet (turno profile add <name>).");
|
|
45
65
|
return 0;
|
|
46
66
|
}
|
|
47
67
|
return usage.run(bool(p, "watch") ? ["--watch"] : [], io);
|
|
48
68
|
}
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
69
|
+
/**
|
|
70
|
+
* `--watch --json`: every profile as one JSON line (NDJSON) now and every 30 s, until Ctrl-C or
|
|
71
|
+
* `signal`. A reader tells the rounds apart by `updatedAt` or by the profile coming back.
|
|
72
|
+
*/
|
|
73
|
+
export async function watchJson(io, p, signal, everyMs = WATCH_EVERY_MS) {
|
|
74
|
+
const stop = signal ?? interrupted();
|
|
75
|
+
while (!stop.aborted) {
|
|
76
|
+
emitLines(io, p, SHOW_JSON, await limitsData(io.env));
|
|
77
|
+
await new Promise((r) => {
|
|
78
|
+
const timer = setTimeout(r, everyMs);
|
|
79
|
+
stop.addEventListener("abort", () => {
|
|
80
|
+
clearTimeout(timer);
|
|
81
|
+
r();
|
|
82
|
+
}, { once: true });
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
return 0;
|
|
86
|
+
}
|
|
87
|
+
/** An abort signal for Ctrl-C. */
|
|
88
|
+
function interrupted() {
|
|
89
|
+
const c = new AbortController();
|
|
90
|
+
process.once("SIGINT", () => c.abort());
|
|
91
|
+
return c.signal;
|
|
92
|
+
}
|
|
93
|
+
async function profileArg(given, io, verb) {
|
|
94
|
+
const name = given ??
|
|
95
|
+
(await (await import("../picker.js")).pickProfile(io, {
|
|
96
|
+
command: `limit ${verb}`,
|
|
97
|
+
title: verb === "set" ? "Profile to mark exhausted" : "Profile to clear",
|
|
98
|
+
}));
|
|
52
99
|
if (!launcherPath(name, io.env))
|
|
53
100
|
fail(`no profile '${name}' (turno profile list shows them)`);
|
|
54
101
|
return name;
|
|
55
102
|
}
|
|
103
|
+
const SET_SPEC = { until: { type: "string" }, for: { type: "string" }, ...DRY_RUN };
|
|
56
104
|
async function set(args, io) {
|
|
57
105
|
// The bash form `exhausted <profile> until "YYYY-MM-DD HH:MM"` still works.
|
|
58
106
|
const legacy = args[1] === "until" || args[1] === "hasta";
|
|
59
|
-
const p = parseFlags(legacy ? [args[0], "--until", ...args.slice(2)] : args,
|
|
60
|
-
const name = profileArg(p.positionals[0], io, "set");
|
|
107
|
+
const p = parseFlags(legacy ? [args[0], "--until", ...args.slice(2)] : args, SET_SPEC, 1);
|
|
108
|
+
const name = await profileArg(p.positionals[0], io, "set");
|
|
61
109
|
const untilText = str(p, "until");
|
|
62
110
|
const forText = str(p, "for");
|
|
63
111
|
if (untilText && forText)
|
|
@@ -82,21 +130,41 @@ async function set(args, io) {
|
|
|
82
130
|
}
|
|
83
131
|
async function clear(args, io) {
|
|
84
132
|
const p = parseFlags(args, DRY_RUN, 1);
|
|
85
|
-
const name = profileArg(p.positionals[0], io, "clear");
|
|
133
|
+
const name = await profileArg(p.positionals[0], io, "clear");
|
|
86
134
|
if (!bool(p, "dry-run"))
|
|
87
135
|
clearExhausted(name, io.env);
|
|
88
136
|
io.out(`${name} available again${bool(p, "dry-run") ? " (dry run)" : ""}`);
|
|
89
137
|
return 0;
|
|
90
138
|
}
|
|
91
139
|
export const command = group("limit", "usage limits of each account, and the exhausted marks that move projects to the fallback", {
|
|
92
|
-
show: {
|
|
140
|
+
show: {
|
|
141
|
+
summary: "5 h and weekly usage of each account, as bars",
|
|
142
|
+
synopsis: "[--watch] [--json]",
|
|
143
|
+
flags: flagsOf(SHOW_SPEC),
|
|
144
|
+
json: SHOW_JSON,
|
|
145
|
+
run: show,
|
|
146
|
+
},
|
|
93
147
|
set: {
|
|
94
148
|
summary: "mark a profile exhausted (default for 5 h); its projects open with the fallback, if one is set",
|
|
95
149
|
synopsis: '<profile> [--until "YYYY-MM-DD HH:MM" | --for 2h] [--dry-run]',
|
|
96
150
|
args: ["profile"],
|
|
97
|
-
flags:
|
|
151
|
+
flags: flagsOf(SET_SPEC),
|
|
98
152
|
run: set,
|
|
99
153
|
},
|
|
100
|
-
clear: {
|
|
101
|
-
|
|
154
|
+
clear: {
|
|
155
|
+
summary: "clear a profile's exhausted mark",
|
|
156
|
+
synopsis: "<profile> [--dry-run]",
|
|
157
|
+
args: ["profile"],
|
|
158
|
+
flags: flagsOf(DRY_RUN),
|
|
159
|
+
run: clear,
|
|
160
|
+
},
|
|
161
|
+
}, {
|
|
162
|
+
fallback: "show",
|
|
163
|
+
examples: [
|
|
164
|
+
"turno limit show",
|
|
165
|
+
"turno limit show --watch --json # one JSON line per profile, every 30 s",
|
|
166
|
+
"turno limit set work --for 2h",
|
|
167
|
+
"turno limit clear work",
|
|
168
|
+
],
|
|
169
|
+
});
|
|
102
170
|
//# sourceMappingURL=limit.js.map
|
|
@@ -0,0 +1,240 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `turno mcp call <server> [tool]`: call one tool through mcpd from the terminal, the way an
|
|
3
|
+
* agent session of a profile would (its token, this folder), to debug a server without opening
|
|
4
|
+
* an agent. Loaded only when the subcommand runs: it brings in the MCP SDK client.
|
|
5
|
+
*/
|
|
6
|
+
import { gatewayUrl } from "../../agents/adapter.js";
|
|
7
|
+
import { loadConfig } from "../../core/config.js";
|
|
8
|
+
import { loadManifest, servesProfile } from "../../core/manifest.js";
|
|
9
|
+
import { resolveProfile } from "../../core/resolve.js";
|
|
10
|
+
import { packageInfo } from "../../core/version.js";
|
|
11
|
+
import { JSON_FLAG, bool, parseFlags, str } from "../args.js";
|
|
12
|
+
import { Exit } from "../exit.js";
|
|
13
|
+
import { CliError, UsageError, fail } from "../io.js";
|
|
14
|
+
import { emit, jsonOutput } from "../output.js";
|
|
15
|
+
import { duration, style } from "../style.js";
|
|
16
|
+
export const CALL_FLAGS = {
|
|
17
|
+
args: { type: "string" },
|
|
18
|
+
arg: { type: "string", multiple: true },
|
|
19
|
+
profile: { type: "string" },
|
|
20
|
+
...JSON_FLAG,
|
|
21
|
+
};
|
|
22
|
+
/**
|
|
23
|
+
* `turno mcp call --json`. A call fills `tool`, `isError`, `content` and
|
|
24
|
+
* `structuredContent`; without a tool, `tools` lists the server's tools and the rest is null.
|
|
25
|
+
*/
|
|
26
|
+
export const CALL_JSON = jsonOutput([
|
|
27
|
+
"server",
|
|
28
|
+
"profile",
|
|
29
|
+
"tool",
|
|
30
|
+
"isError",
|
|
31
|
+
"content",
|
|
32
|
+
"structuredContent",
|
|
33
|
+
"tools",
|
|
34
|
+
"ms",
|
|
35
|
+
]);
|
|
36
|
+
/**
|
|
37
|
+
* The tool arguments: `--args` (a JSON object), then each `--arg key=value` (a string) or
|
|
38
|
+
* `--arg key:=json` (any JSON value) on top of it, as httpie writes them.
|
|
39
|
+
*/
|
|
40
|
+
export function callArguments(json, pairs) {
|
|
41
|
+
let out = {};
|
|
42
|
+
if (json !== undefined) {
|
|
43
|
+
let v;
|
|
44
|
+
try {
|
|
45
|
+
v = JSON.parse(json);
|
|
46
|
+
}
|
|
47
|
+
catch (err) {
|
|
48
|
+
throw new UsageError(`--args is not JSON: ${err.message}`);
|
|
49
|
+
}
|
|
50
|
+
if (typeof v !== "object" || v === null || Array.isArray(v))
|
|
51
|
+
throw new UsageError('--args must be a JSON object, like \'{"query": "x"}\'');
|
|
52
|
+
out = { ...v };
|
|
53
|
+
}
|
|
54
|
+
for (const pair of pairs) {
|
|
55
|
+
const m = /^([^=:]+)(:?=)([\s\S]*)$/.exec(pair);
|
|
56
|
+
if (!m)
|
|
57
|
+
throw new UsageError(`--arg ${pair}: use key=value (a string) or key:=json (a number, true, a list...)`);
|
|
58
|
+
const [, key, op, raw] = m;
|
|
59
|
+
if (op === "=") {
|
|
60
|
+
out[key] = raw;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
out[key] = JSON.parse(raw);
|
|
65
|
+
}
|
|
66
|
+
catch (err) {
|
|
67
|
+
throw new UsageError(`--arg ${key}:= needs JSON: ${err.message}`);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return out;
|
|
71
|
+
}
|
|
72
|
+
/** The profile a session in `cwd` would use: --profile, else the folder's Claude Code profile, else the hub's. */
|
|
73
|
+
function callerProfile(given, env, cwd) {
|
|
74
|
+
if (given)
|
|
75
|
+
return given;
|
|
76
|
+
const config = loadConfig(env);
|
|
77
|
+
return resolveProfile(cwd, config, env).chosen || config.system || "default";
|
|
78
|
+
}
|
|
79
|
+
/** One line from an SDK transport error: the gateway's `{ "error": ... }` text when it sent one. */
|
|
80
|
+
function gatewayMessage(err) {
|
|
81
|
+
const e = err;
|
|
82
|
+
const message = e?.message ?? String(err);
|
|
83
|
+
const status = typeof e?.code === "number" && e.code >= 400 && e.code < 600 ? e.code : undefined;
|
|
84
|
+
const body = /Error POSTing to endpoint: (.*)$/s.exec(message)?.[1];
|
|
85
|
+
if (body) {
|
|
86
|
+
try {
|
|
87
|
+
const parsed = JSON.parse(body);
|
|
88
|
+
if (typeof parsed.error === "string")
|
|
89
|
+
return { ...(status ? { status } : {}), message: parsed.error };
|
|
90
|
+
if (parsed.error && typeof parsed.error.message === "string") {
|
|
91
|
+
return { ...(status ? { status } : {}), message: parsed.error.message };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
/* not JSON */
|
|
96
|
+
}
|
|
97
|
+
return { ...(status ? { status } : {}), message: body.trim().split("\n")[0] };
|
|
98
|
+
}
|
|
99
|
+
return { ...(status ? { status } : {}), message: message.split("\n")[0] };
|
|
100
|
+
}
|
|
101
|
+
/** A content item as terminal text: text as it is, anything else as one bracketed line. */
|
|
102
|
+
export function contentText(c) {
|
|
103
|
+
switch (c.type) {
|
|
104
|
+
case "text":
|
|
105
|
+
return c.text ?? "";
|
|
106
|
+
case "image":
|
|
107
|
+
case "audio":
|
|
108
|
+
return `[${c.type} ${c.mimeType ?? "?"}, ${Math.floor(((c.data ?? "").length * 3) / 4)} bytes]`;
|
|
109
|
+
case "resource":
|
|
110
|
+
return c.resource?.text !== undefined
|
|
111
|
+
? c.resource.text
|
|
112
|
+
: `[resource ${c.resource?.uri ?? "?"}${c.resource?.mimeType ? `, ${c.resource.mimeType}` : ""}]`;
|
|
113
|
+
case "resource_link":
|
|
114
|
+
return `[link ${c.uri ?? "?"}${c.name ? ` (${c.name})` : ""}]`;
|
|
115
|
+
default:
|
|
116
|
+
return `[${c.type}]`;
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
export async function call(args, io) {
|
|
120
|
+
const p = parseFlags(args, CALL_FLAGS, 2);
|
|
121
|
+
const [server, tool] = p.positionals;
|
|
122
|
+
if (!server)
|
|
123
|
+
return fail("usage: turno mcp call <server> [tool] [--args JSON] [--arg key=value ...] [--profile p] [--json]");
|
|
124
|
+
const pairs = p.values.arg ?? [];
|
|
125
|
+
const toolArgs = callArguments(str(p, "args"), pairs);
|
|
126
|
+
if (!tool && (str(p, "args") !== undefined || pairs.length))
|
|
127
|
+
fail("--args and --arg go with a tool: turno mcp call <server> <tool> ...");
|
|
128
|
+
const json = bool(p, "json");
|
|
129
|
+
const manifest = loadManifest(io.env);
|
|
130
|
+
const def = manifest.servers[server];
|
|
131
|
+
if (!def)
|
|
132
|
+
return fail(`unknown server '${server}' (turno mcp list shows them)`);
|
|
133
|
+
if (def.kind === "remote" && !def.proxy) {
|
|
134
|
+
throw new CliError(`${server} is a remote server that agents reach directly (no keychain: or env: header and no auth = "oauth"), so mcpd does not relay it; call it from the agent`);
|
|
135
|
+
}
|
|
136
|
+
const cwd = process.cwd();
|
|
137
|
+
const profile = callerProfile(str(p, "profile"), io.env, cwd);
|
|
138
|
+
if (!servesProfile(def, profile)) {
|
|
139
|
+
throw new CliError(`${server} is not served to profile ${profile} (profiles = ${JSON.stringify(def.profiles)} in mcp.toml); pick another with --profile`);
|
|
140
|
+
}
|
|
141
|
+
const { mcpdPort, readToken } = await import("../../mcpd/state.js");
|
|
142
|
+
const { profileToken } = await import("../../mcpd/tokens.js");
|
|
143
|
+
const master = readToken(io.env);
|
|
144
|
+
const down = () => new CliError("mcpd is not running (turno mcp daemon start)", Exit.gatewayDown);
|
|
145
|
+
if (!master)
|
|
146
|
+
throw down();
|
|
147
|
+
const port = mcpdPort(io.env);
|
|
148
|
+
const { Client } = await import("@modelcontextprotocol/sdk/client/index.js");
|
|
149
|
+
const { StreamableHTTPClientTransport } = await import("@modelcontextprotocol/sdk/client/streamableHttp.js");
|
|
150
|
+
const transport = new StreamableHTTPClientTransport(new URL(gatewayUrl(server, port)), {
|
|
151
|
+
requestInit: {
|
|
152
|
+
headers: {
|
|
153
|
+
Authorization: `Bearer ${profileToken(master, profile)}`,
|
|
154
|
+
"X-Turno-Profile": profile,
|
|
155
|
+
"X-Turno-Pid": String(process.pid),
|
|
156
|
+
// This folder, so its [[projects]] rules apply as they would to an agent here.
|
|
157
|
+
"X-Turno-Cwd-B64": Buffer.from(cwd, "utf8").toString("base64url"),
|
|
158
|
+
},
|
|
159
|
+
},
|
|
160
|
+
});
|
|
161
|
+
const client = new Client({ name: "turno-mcp-call", version: packageInfo().version }, { capabilities: {} });
|
|
162
|
+
const started = Date.now();
|
|
163
|
+
try {
|
|
164
|
+
try {
|
|
165
|
+
await client.connect(transport);
|
|
166
|
+
}
|
|
167
|
+
catch (err) {
|
|
168
|
+
const g = gatewayMessage(err);
|
|
169
|
+
if (g.status === undefined && /ECONNREFUSED|fetch failed|connect/i.test(g.message))
|
|
170
|
+
throw down();
|
|
171
|
+
throw new CliError(`mcpd refused the session for ${server} as profile ${profile}: ${g.message}`);
|
|
172
|
+
}
|
|
173
|
+
// A server the folder's set leaves out answers with no capabilities and says why.
|
|
174
|
+
if (client.getServerVersion()?.version === "hidden")
|
|
175
|
+
throw new CliError(client.getInstructions() ?? `${server} is hidden in this folder`);
|
|
176
|
+
if (!tool) {
|
|
177
|
+
const { tools } = await client.listTools();
|
|
178
|
+
const ms = Date.now() - started;
|
|
179
|
+
if (json) {
|
|
180
|
+
emit(io, p, CALL_JSON, {
|
|
181
|
+
server,
|
|
182
|
+
profile,
|
|
183
|
+
tool: null,
|
|
184
|
+
isError: null,
|
|
185
|
+
content: null,
|
|
186
|
+
structuredContent: null,
|
|
187
|
+
tools: tools.map((t) => ({ name: t.name, description: t.description ?? null })),
|
|
188
|
+
ms,
|
|
189
|
+
});
|
|
190
|
+
return 0;
|
|
191
|
+
}
|
|
192
|
+
const st = style(io);
|
|
193
|
+
if (!tools.length)
|
|
194
|
+
io.out(st.muted(`${server} has no tools for profile ${profile}`));
|
|
195
|
+
for (const t of tools)
|
|
196
|
+
io.out(st.wrap(`${st.bold(t.name)} `, st.muted((t.description ?? "").split("\n")[0] ?? "")));
|
|
197
|
+
if (io.isTty)
|
|
198
|
+
io.err(st.muted(`${tools.length} tools of ${server} as profile ${profile} in ${duration(ms)}; call one with: turno mcp call ${server} <tool> --arg key=value`));
|
|
199
|
+
return 0;
|
|
200
|
+
}
|
|
201
|
+
let result;
|
|
202
|
+
try {
|
|
203
|
+
result = await client.callTool({ name: tool, arguments: toolArgs });
|
|
204
|
+
}
|
|
205
|
+
catch (err) {
|
|
206
|
+
throw new CliError(`${server}/${tool}: ${gatewayMessage(err).message}`);
|
|
207
|
+
}
|
|
208
|
+
const ms = Date.now() - started;
|
|
209
|
+
const content = (Array.isArray(result.content) ? result.content : []);
|
|
210
|
+
const isError = result.isError === true;
|
|
211
|
+
if (json) {
|
|
212
|
+
emit(io, p, CALL_JSON, {
|
|
213
|
+
server,
|
|
214
|
+
profile,
|
|
215
|
+
tool,
|
|
216
|
+
isError,
|
|
217
|
+
content,
|
|
218
|
+
structuredContent: result.structuredContent ?? null,
|
|
219
|
+
tools: null,
|
|
220
|
+
ms,
|
|
221
|
+
});
|
|
222
|
+
return isError ? 1 : 0;
|
|
223
|
+
}
|
|
224
|
+
for (const c of content)
|
|
225
|
+
io.out(contentText(c));
|
|
226
|
+
if (!content.length && result.structuredContent !== undefined)
|
|
227
|
+
io.out(JSON.stringify(result.structuredContent, null, 2));
|
|
228
|
+
const st = style(io);
|
|
229
|
+
if (isError)
|
|
230
|
+
io.err(`turno: ${server}/${tool} returned an error (isError)`);
|
|
231
|
+
else if (io.isTty)
|
|
232
|
+
io.err(st.muted(`${server}/${tool} as profile ${profile} in ${duration(ms)}`));
|
|
233
|
+
return isError ? 1 : 0;
|
|
234
|
+
}
|
|
235
|
+
finally {
|
|
236
|
+
await transport.terminateSession().catch(() => { });
|
|
237
|
+
await client.close().catch(() => { });
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
//# sourceMappingURL=mcp-call.js.map
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { isValidProfileName } from "../../core/config.js";
|
|
3
|
+
import { loadManifest, servesProfile, variantKey } from "../../core/manifest.js";
|
|
4
|
+
import { NO_SECRET_STORE, keychainResolver, secretStore } from "../../core/secrets.js";
|
|
5
|
+
import { DRY_RUN, JSON_FLAG, bool, parseFlags, str } from "../args.js";
|
|
6
|
+
import { fail } from "../io.js";
|
|
7
|
+
import { emit, jsonOutput } from "../output.js";
|
|
8
|
+
/** `turno mcp login --json`. */
|
|
9
|
+
export const LOGIN_JSON = jsonOutput([
|
|
10
|
+
"server",
|
|
11
|
+
"variant",
|
|
12
|
+
"issuer",
|
|
13
|
+
"registration",
|
|
14
|
+
"scope",
|
|
15
|
+
"redirectUri",
|
|
16
|
+
"expiresAt",
|
|
17
|
+
"refreshToken",
|
|
18
|
+
"service",
|
|
19
|
+
"planned",
|
|
20
|
+
]);
|
|
21
|
+
/**
|
|
22
|
+
* `turno mcp login` and `turno mcp logout`: mcpd is the OAuth client of remote
|
|
23
|
+
* servers declared with `auth = "oauth"`, one login per server variant. Agents reach the server
|
|
24
|
+
* through mcpd and never log in themselves.
|
|
25
|
+
*/
|
|
26
|
+
export const LOGIN_FLAGS = {
|
|
27
|
+
profile: { type: "string" },
|
|
28
|
+
scope: { type: "string" },
|
|
29
|
+
"no-browser": { type: "boolean" },
|
|
30
|
+
...DRY_RUN,
|
|
31
|
+
...JSON_FLAG,
|
|
32
|
+
};
|
|
33
|
+
export const LOGOUT_FLAGS = {
|
|
34
|
+
profile: { type: "string" },
|
|
35
|
+
all: { type: "boolean" },
|
|
36
|
+
"no-revoke": { type: "boolean" },
|
|
37
|
+
...DRY_RUN,
|
|
38
|
+
};
|
|
39
|
+
function oauthServer(env, name, verb) {
|
|
40
|
+
if (!name)
|
|
41
|
+
fail(`usage: turno mcp ${verb} <server> [--profile <p>]`);
|
|
42
|
+
const def = loadManifest(env).servers[name];
|
|
43
|
+
if (!def)
|
|
44
|
+
fail(`no server "${name}" in mcp.toml`);
|
|
45
|
+
if (def.kind !== "remote" || !def.oauth)
|
|
46
|
+
fail(`${name} is not a remote server with auth = "oauth" in mcp.toml`);
|
|
47
|
+
return def;
|
|
48
|
+
}
|
|
49
|
+
function variantFor(server, profile) {
|
|
50
|
+
if (profile === undefined)
|
|
51
|
+
return "default";
|
|
52
|
+
if (!isValidProfileName(profile))
|
|
53
|
+
fail(`invalid profile name "${profile}"`);
|
|
54
|
+
if (!servesProfile(server, profile))
|
|
55
|
+
fail(`${server.name} is not served to profile ${profile} (profiles in mcp.toml)`);
|
|
56
|
+
return variantKey(server, profile);
|
|
57
|
+
}
|
|
58
|
+
function storeOf(env) {
|
|
59
|
+
const store = secretStore(env);
|
|
60
|
+
if (!store)
|
|
61
|
+
fail(NO_SECRET_STORE);
|
|
62
|
+
return store;
|
|
63
|
+
}
|
|
64
|
+
/** Who a variant's login serves, for messages. */
|
|
65
|
+
function whom(server, variant) {
|
|
66
|
+
if (variant !== "default")
|
|
67
|
+
return `profile ${variant}`;
|
|
68
|
+
return Object.keys(server.variants).length ? "every profile without its own variant" : "every profile";
|
|
69
|
+
}
|
|
70
|
+
/** Open the URL with the system browser (the profile's Chrome for claude.ai links, like turno open). */
|
|
71
|
+
async function openBrowser(url, profile, io) {
|
|
72
|
+
const { openInvocation } = await import("./open.js");
|
|
73
|
+
const inv = openInvocation(profile, url, io.env);
|
|
74
|
+
await new Promise((resolve) => {
|
|
75
|
+
const child = spawn(inv.command, inv.args, { stdio: "ignore", env: io.env, detached: true });
|
|
76
|
+
child.on("error", () => resolve());
|
|
77
|
+
child.on("spawn", () => {
|
|
78
|
+
child.unref();
|
|
79
|
+
resolve();
|
|
80
|
+
});
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
export async function login(args, io, deps = {}) {
|
|
84
|
+
const flags = parseFlags(args, LOGIN_FLAGS, 1);
|
|
85
|
+
const server = oauthServer(io.env, flags.positionals[0], "login");
|
|
86
|
+
const profile = str(flags, "profile");
|
|
87
|
+
const variant = variantFor(server, profile);
|
|
88
|
+
const store = storeOf(io.env);
|
|
89
|
+
const json = bool(flags, "json");
|
|
90
|
+
const noBrowser = bool(flags, "no-browser");
|
|
91
|
+
const { login: run, OAuthFlowError } = await import("../../mcpd/oauth.js");
|
|
92
|
+
const say = (line) => (json ? io.err(line) : io.out(line));
|
|
93
|
+
try {
|
|
94
|
+
const scope = str(flags, "scope");
|
|
95
|
+
const result = await run({
|
|
96
|
+
server,
|
|
97
|
+
variant,
|
|
98
|
+
store,
|
|
99
|
+
resolve: keychainResolver(io.env),
|
|
100
|
+
...(scope ? { scope } : {}),
|
|
101
|
+
...(deps.fetchFn ? { fetchFn: deps.fetchFn } : {}),
|
|
102
|
+
dryRun: bool(flags, "dry-run"),
|
|
103
|
+
open: async (url) => {
|
|
104
|
+
if (noBrowser) {
|
|
105
|
+
say(`Open this link in a browser to log in to ${server.name} (${whom(server, variant)}):`);
|
|
106
|
+
say(url);
|
|
107
|
+
}
|
|
108
|
+
else {
|
|
109
|
+
say(`Opening the browser to log in to ${server.name} (${whom(server, variant)}). If it does not open, visit:`);
|
|
110
|
+
say(url);
|
|
111
|
+
await (deps.open ?? openBrowser)(url, profile, io);
|
|
112
|
+
}
|
|
113
|
+
say("Waiting for the browser (Ctrl-C cancels)...");
|
|
114
|
+
},
|
|
115
|
+
});
|
|
116
|
+
if (json) {
|
|
117
|
+
emit(io, flags, LOGIN_JSON, { server: server.name, variant, ...result });
|
|
118
|
+
return 0;
|
|
119
|
+
}
|
|
120
|
+
if (result.planned) {
|
|
121
|
+
io.out(`would log in to ${server.name} (${whom(server, variant)}) through ${result.issuer}`);
|
|
122
|
+
io.out(` client: ${result.registration === "dynamic" ? "dynamic client registration" : result.registration === "metadata-document" ? "client ID metadata document" : "pre-registered client_id"}`);
|
|
123
|
+
io.out(` scope: ${result.scope ?? "(none requested)"}`);
|
|
124
|
+
io.out(` tokens would go to the ${store.label} as ${result.service}`);
|
|
125
|
+
return 0;
|
|
126
|
+
}
|
|
127
|
+
io.out(`Logged in to ${server.name} for ${whom(server, variant)} through ${result.issuer}.`);
|
|
128
|
+
io.out(`The tokens are in the ${store.label} as ${result.service}; mcpd refreshes them, and agents reach ${server.name} through mcpd.`);
|
|
129
|
+
if (!result.refreshToken)
|
|
130
|
+
io.out(`The server gave no refresh token: log in again when the access token expires.`);
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
catch (err) {
|
|
134
|
+
if (err instanceof OAuthFlowError)
|
|
135
|
+
fail(`login to ${server.name} failed: ${err.message}`);
|
|
136
|
+
throw err;
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
export async function logout(args, io, deps = {}) {
|
|
140
|
+
const flags = parseFlags(args, LOGOUT_FLAGS, 1);
|
|
141
|
+
const server = oauthServer(io.env, flags.positionals[0], "logout");
|
|
142
|
+
const all = bool(flags, "all");
|
|
143
|
+
if (all && str(flags, "profile") !== undefined)
|
|
144
|
+
fail("use --all or --profile, not both");
|
|
145
|
+
const variants = all ? ["default", ...Object.keys(server.variants)] : [variantFor(server, str(flags, "profile"))];
|
|
146
|
+
const store = storeOf(io.env);
|
|
147
|
+
const dry = bool(flags, "dry-run");
|
|
148
|
+
const { oauthService, parseRecord, revoke } = await import("../../mcpd/oauth.js");
|
|
149
|
+
const removed = [];
|
|
150
|
+
for (const variant of variants) {
|
|
151
|
+
const service = oauthService(server.name, variant);
|
|
152
|
+
const rec = parseRecord(await store.get(service));
|
|
153
|
+
const label = `${server.name} (${whom(server, variant)})`;
|
|
154
|
+
if (!rec && !(await store.has(service))) {
|
|
155
|
+
io.out(`${label}: not logged in`);
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (dry) {
|
|
159
|
+
io.out(`would remove ${service} from the ${store.label}${rec?.tokens && !bool(flags, "no-revoke") ? ` and revoke the token at ${rec.issuer}` : ""}`);
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
let revoked = "";
|
|
163
|
+
if (rec?.tokens && !bool(flags, "no-revoke")) {
|
|
164
|
+
const why = await revoke(server, rec, keychainResolver(io.env), deps.fetchFn);
|
|
165
|
+
revoked = why ? `; could not revoke it at ${rec.issuer} (${why})` : `; revoked it at ${rec.issuer}`;
|
|
166
|
+
}
|
|
167
|
+
await store.remove(service);
|
|
168
|
+
removed.push(variant);
|
|
169
|
+
io.out(`Logged out of ${label}: removed ${service} from the ${store.label}${revoked}.`);
|
|
170
|
+
}
|
|
171
|
+
if (!dry && removed.length)
|
|
172
|
+
io.out(await tellMcpd(io.env, server.name, removed));
|
|
173
|
+
return 0;
|
|
174
|
+
}
|
|
175
|
+
/** Tell a running mcpd to drop its copy of the login now; what to print about it. */
|
|
176
|
+
async function tellMcpd(env, server, variants) {
|
|
177
|
+
const { mcpdRequest } = await import("./mcp.js");
|
|
178
|
+
const query = variants.map((v) => `variant=${encodeURIComponent(v)}`).join("&");
|
|
179
|
+
const r = await mcpdRequest(env, "POST", `/logout/${encodeURIComponent(server)}?${query}`);
|
|
180
|
+
if (r === "down")
|
|
181
|
+
return "mcpd is not running; it reads the secret store when it starts.";
|
|
182
|
+
// An mcpd from before 0.2 has no /logout: it notices within a minute.
|
|
183
|
+
return r.status === 200
|
|
184
|
+
? "mcpd stopped using the old token."
|
|
185
|
+
: "mcpd stops using the old token within a minute (now: turno mcp daemon restart).";
|
|
186
|
+
}
|
|
187
|
+
/** Variants whose login is needed: "default" when some served profile has no variant of its own. */
|
|
188
|
+
export function loginVariants(server) {
|
|
189
|
+
const own = Object.keys(server.variants);
|
|
190
|
+
const needsDefault = server.profiles.includes("*") || server.profiles.some((p) => !server.variants[p]);
|
|
191
|
+
return [...(needsDefault ? ["default"] : []), ...own];
|
|
192
|
+
}
|
|
193
|
+
/** The login state of every OAuth server variant (reads the secret store, never prints a token). */
|
|
194
|
+
export async function oauthLogins(env) {
|
|
195
|
+
const servers = Object.values(loadManifest(env).servers).filter((s) => s.kind === "remote" && s.oauth !== undefined);
|
|
196
|
+
if (!servers.length)
|
|
197
|
+
return [];
|
|
198
|
+
const { loginState } = await import("../../mcpd/oauth.js");
|
|
199
|
+
const store = secretStore(env);
|
|
200
|
+
const rows = [];
|
|
201
|
+
for (const s of servers) {
|
|
202
|
+
for (const variant of loginVariants(s))
|
|
203
|
+
rows.push({ server: s.name, variant, ...(await loginState(store, s.name, variant)) });
|
|
204
|
+
}
|
|
205
|
+
return rows;
|
|
206
|
+
}
|
|
207
|
+
/** One short phrase per state, with the command that fixes it. */
|
|
208
|
+
export function describeLogin(r) {
|
|
209
|
+
const who = r.variant === "default" ? "" : ` --profile ${r.variant}`;
|
|
210
|
+
switch (r.state) {
|
|
211
|
+
case "logged in":
|
|
212
|
+
return "logged in";
|
|
213
|
+
case "expired":
|
|
214
|
+
return "logged in (token refreshes on next use)";
|
|
215
|
+
case "unknown":
|
|
216
|
+
return "unknown (no secret store)";
|
|
217
|
+
default:
|
|
218
|
+
return `${r.state}: turno mcp login ${r.server}${who}`;
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
//# sourceMappingURL=mcp-oauth.js.map
|