@nathapp/nax-agent-acp 0.3.1 → 0.85.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 +27 -0
- package/README.md +135 -4
- package/bin/nax-agent.js +4 -0
- package/dist/client/elicitation.d.ts +4 -2
- package/dist/client/elicitation.js +14 -1
- package/dist/client/errors.d.ts +1 -1
- package/dist/client/errors.js +2 -2
- package/dist/client/open.js +17 -3
- package/dist/server/auth.d.ts +47 -0
- package/dist/server/auth.js +87 -0
- package/dist/server/capabilities.d.ts +8 -0
- package/dist/server/capabilities.js +21 -0
- package/dist/server/cli.d.ts +27 -0
- package/dist/server/cli.js +90 -0
- package/dist/server/client-port.d.ts +39 -0
- package/dist/server/client-port.js +49 -0
- package/dist/server/connection.d.ts +22 -0
- package/dist/server/connection.js +56 -0
- package/dist/server/default-model.d.ts +36 -0
- package/dist/server/default-model.js +158 -0
- package/dist/server/errors.d.ts +21 -0
- package/dist/server/errors.js +70 -0
- package/dist/server/index.d.ts +4 -3
- package/dist/server/index.js +6 -1
- package/dist/server/logger.d.ts +7 -0
- package/dist/server/logger.js +25 -0
- package/dist/server/login.d.ts +20 -0
- package/dist/server/login.js +38 -0
- package/dist/server/main.d.ts +24 -0
- package/dist/server/main.js +152 -0
- package/dist/server/mcp/connect.d.ts +38 -0
- package/dist/server/mcp/connect.js +95 -0
- package/dist/server/mcp/naming.d.ts +12 -0
- package/dist/server/mcp/naming.js +43 -0
- package/dist/server/mcp/notices.d.ts +8 -0
- package/dist/server/mcp/notices.js +19 -0
- package/dist/server/mcp/parse.d.ts +24 -0
- package/dist/server/mcp/parse.js +107 -0
- package/dist/server/mcp/secrets.d.ts +4 -0
- package/dist/server/mcp/secrets.js +44 -0
- package/dist/server/mcp/session-tools.d.ts +37 -0
- package/dist/server/mcp/session-tools.js +70 -0
- package/dist/server/mcp/tool-shape.d.ts +19 -0
- package/dist/server/mcp/tool-shape.js +20 -0
- package/dist/server/nax-config.d.ts +31 -0
- package/dist/server/nax-config.js +139 -0
- package/dist/server/open-session.d.ts +38 -0
- package/dist/server/open-session.js +56 -0
- package/dist/server/options.d.ts +30 -0
- package/dist/server/options.js +72 -0
- package/dist/server/permissions.d.ts +44 -0
- package/dist/server/permissions.js +157 -0
- package/dist/server/process-entry.d.ts +15 -0
- package/dist/server/process-entry.js +28 -0
- package/dist/server/prompt.d.ts +8 -0
- package/dist/server/prompt.js +29 -0
- package/dist/server/questions.d.ts +33 -0
- package/dist/server/questions.js +90 -0
- package/dist/server/registry-open.d.ts +32 -0
- package/dist/server/registry-open.js +60 -0
- package/dist/server/registry.d.ts +79 -0
- package/dist/server/registry.js +333 -0
- package/dist/server/server-session.d.ts +45 -0
- package/dist/server/server-session.js +222 -0
- package/dist/server/session-config.d.ts +29 -0
- package/dist/server/session-config.js +104 -0
- package/dist/server/storage.d.ts +49 -0
- package/dist/server/storage.js +191 -0
- package/dist/server/translate/diff.d.ts +30 -0
- package/dist/server/translate/diff.js +81 -0
- package/dist/server/translate/events.d.ts +39 -0
- package/dist/server/translate/events.js +126 -0
- package/dist/server/translate/notice.d.ts +10 -0
- package/dist/server/translate/notice.js +14 -0
- package/dist/server/translate/replay.d.ts +11 -0
- package/dist/server/translate/replay.js +53 -0
- package/dist/server/translate/stop.d.ts +22 -0
- package/dist/server/translate/stop.js +48 -0
- package/dist/server/translate/tool-kind.d.ts +9 -0
- package/dist/server/translate/tool-kind.js +67 -0
- package/dist/server/version.d.ts +1 -0
- package/dist/server/version.js +17 -0
- package/package.json +5 -2
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `nax-agent` entry point as a function of its environment (S5 spec §6.1), so
|
|
3
|
+
* the unit suite covers it without spawning a process. Exit codes: 0 clean stop,
|
|
4
|
+
* 1 connection failure, 2 usage or option error.
|
|
5
|
+
*/
|
|
6
|
+
import { randomUUID } from "node:crypto";
|
|
7
|
+
import { configureCredentials, createFileTranscriptStore, redactSecrets, setAgentLogger } from "@nathapp/nax-agent";
|
|
8
|
+
import { connectMcp } from "@nathapp/nax-agent/mcp";
|
|
9
|
+
import { loadServerAuth, NAX_AGENT_AUTH } from "#src/server/auth";
|
|
10
|
+
import { parseCli, USAGE } from "#src/server/cli";
|
|
11
|
+
import { buildAgentApp, serveStdio } from "#src/server/connection";
|
|
12
|
+
import { NAX_AGENT_MODELS, NODE_CONFIG_WRITER, offerDefaultModel, } from "#src/server/default-model";
|
|
13
|
+
import { stderrLogger } from "#src/server/logger";
|
|
14
|
+
import { runLoginCommand } from "#src/server/login";
|
|
15
|
+
import { createMcpConnector } from "#src/server/mcp/connect";
|
|
16
|
+
import { credentialsFor, loadNaxConfig } from "#src/server/nax-config";
|
|
17
|
+
import { catalogOverridesFrom, nativeOpenSession } from "#src/server/open-session";
|
|
18
|
+
import { resolveConfigDir, resolveServerOptions } from "#src/server/options";
|
|
19
|
+
import { createSessionRegistry } from "#src/server/registry";
|
|
20
|
+
import { TURN_TIMEOUT_SECONDS } from "#src/server/server-session";
|
|
21
|
+
import { createSessionStorage } from "#src/server/storage";
|
|
22
|
+
import { fsReadOldText } from "#src/server/translate/diff";
|
|
23
|
+
import { packageVersion } from "#src/server/version";
|
|
24
|
+
export async function main(deps) {
|
|
25
|
+
const command = parseCli(deps.argv);
|
|
26
|
+
switch (command.kind) {
|
|
27
|
+
case "help":
|
|
28
|
+
deps.stdout.write(`${USAGE}\n`);
|
|
29
|
+
return 0;
|
|
30
|
+
case "version":
|
|
31
|
+
deps.stdout.write(`${packageVersion()}\n`);
|
|
32
|
+
return 0;
|
|
33
|
+
case "usage-error":
|
|
34
|
+
deps.writeErr(`nax-agent: ${command.message}\n\n${USAGE}\n`);
|
|
35
|
+
return 2;
|
|
36
|
+
case "login":
|
|
37
|
+
return login(command, deps);
|
|
38
|
+
case "acp":
|
|
39
|
+
return serveAcp(command.flags, deps);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function login(command, deps) {
|
|
43
|
+
// warn, not info: info lines would land in the middle of the interactive prompts.
|
|
44
|
+
setAgentLogger(stderrLogger(deps.env.NAX_AGENT_LOG === "debug" ? "debug" : "warn", deps.writeErr));
|
|
45
|
+
const configDir = resolveConfigDir(command.flags, deps.env, deps.homedir);
|
|
46
|
+
configureCredentials(credentialsFor(configDir, deps.readFile));
|
|
47
|
+
const auth = deps.auth ?? NAX_AGENT_AUTH;
|
|
48
|
+
const pinned = [command.flags.model, deps.env.NAX_AGENT_MODEL].some((m) => m !== undefined && m !== "");
|
|
49
|
+
return runLoginCommand({ provider: command.provider, ...(command.method !== undefined ? { method: command.method } : {}) }, {
|
|
50
|
+
isTTY: deps.isTTY,
|
|
51
|
+
out: (line) => deps.stdout.write(`${line}\n`),
|
|
52
|
+
err: (line) => deps.writeErr(`${line}\n`),
|
|
53
|
+
auth,
|
|
54
|
+
offerModel: (provider) => offerDefaultModel({
|
|
55
|
+
provider,
|
|
56
|
+
configDir,
|
|
57
|
+
isTTY: deps.isTTY,
|
|
58
|
+
pinned,
|
|
59
|
+
interaction: auth.interaction((line) => deps.stdout.write(`${line}\n`)),
|
|
60
|
+
out: (line) => deps.stdout.write(`${line}\n`),
|
|
61
|
+
models: deps.models ?? NAX_AGENT_MODELS,
|
|
62
|
+
readFile: deps.readFile,
|
|
63
|
+
write: deps.writeConfig ?? NODE_CONFIG_WRITER,
|
|
64
|
+
}),
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async function serveAcp(flags, deps) {
|
|
68
|
+
const logger = stderrLogger(deps.env.NAX_AGENT_LOG === "debug" ? "debug" : "info", deps.writeErr);
|
|
69
|
+
setAgentLogger(logger);
|
|
70
|
+
const configDir = resolveConfigDir(flags, deps.env, deps.homedir);
|
|
71
|
+
const loaded = await loadNaxConfig(configDir, deps.readFile);
|
|
72
|
+
if (loaded.warning !== undefined)
|
|
73
|
+
logger.warn("config", loaded.warning);
|
|
74
|
+
const resolved = resolveServerOptions({ flags, env: deps.env, file: loaded.config, configDir });
|
|
75
|
+
if (!resolved.ok) {
|
|
76
|
+
deps.writeErr(`nax-agent: ${resolved.message}\n`);
|
|
77
|
+
return 2;
|
|
78
|
+
}
|
|
79
|
+
configureCredentials(credentialsFor(configDir, deps.readFile));
|
|
80
|
+
const overrides = catalogOverridesFrom(resolved.options.catalogOverrides, logger);
|
|
81
|
+
const auth = await loadServerAuth({
|
|
82
|
+
options: resolved.options,
|
|
83
|
+
overrides,
|
|
84
|
+
ports: deps.auth ?? NAX_AGENT_AUTH,
|
|
85
|
+
logger,
|
|
86
|
+
});
|
|
87
|
+
const transcripts = createFileTranscriptStore(resolved.options.sessionsDir);
|
|
88
|
+
const storage = createSessionStorage({
|
|
89
|
+
dir: resolved.options.sessionsDir,
|
|
90
|
+
pid: process.pid,
|
|
91
|
+
now: () => new Date(),
|
|
92
|
+
logger,
|
|
93
|
+
});
|
|
94
|
+
const registry = createSessionRegistry({
|
|
95
|
+
options: resolved.options,
|
|
96
|
+
openSession: nativeOpenSession({
|
|
97
|
+
transcripts,
|
|
98
|
+
catalogOverrides: overrides,
|
|
99
|
+
turnTimeoutSeconds: TURN_TIMEOUT_SECONDS,
|
|
100
|
+
}),
|
|
101
|
+
storage,
|
|
102
|
+
transcripts,
|
|
103
|
+
newId: randomUUID,
|
|
104
|
+
now: () => new Date(),
|
|
105
|
+
readOldText: fsReadOldText(),
|
|
106
|
+
logger,
|
|
107
|
+
turnTimeoutSeconds: TURN_TIMEOUT_SECONDS,
|
|
108
|
+
ensureCredentials: (model) => auth.ensureCredentials(model),
|
|
109
|
+
reloadOptions: async () => {
|
|
110
|
+
const reloaded = await loadNaxConfig(configDir, deps.readFile);
|
|
111
|
+
const again = resolveServerOptions({ flags, env: deps.env, file: reloaded.config, configDir });
|
|
112
|
+
const problem = reloaded.warning ?? (again.ok ? undefined : again.message);
|
|
113
|
+
if (problem === undefined)
|
|
114
|
+
return again.ok ? { options: again.options } : {};
|
|
115
|
+
// Config paths and option names only, never file contents.
|
|
116
|
+
logger.warn("config", redactSecrets(problem));
|
|
117
|
+
return { ...(again.ok ? { options: again.options } : {}), problem: redactSecrets(problem) };
|
|
118
|
+
},
|
|
119
|
+
connectMcp: createMcpConnector({
|
|
120
|
+
connect: connectMcp,
|
|
121
|
+
timeoutMs: resolved.options.mcpConnectTimeoutSeconds * 1000,
|
|
122
|
+
clientVersion: packageVersion(),
|
|
123
|
+
}),
|
|
124
|
+
});
|
|
125
|
+
const connection = serveStdio(buildAgentApp({ version: packageVersion(), registry, logger, auth }), deps);
|
|
126
|
+
const stop = () => connection.close();
|
|
127
|
+
deps.onSignal(stop);
|
|
128
|
+
deps.stdin.once("end", stop);
|
|
129
|
+
logger.info("server", "nax-agent ACP server started", { configDir, sessionsDir: resolved.options.sessionsDir });
|
|
130
|
+
// Scalars only: catalog overrides can carry provider headers (API keys).
|
|
131
|
+
const { defaultModel, defaultMode, bashApproval, tiers, catalogOverrides, mcpConnectTimeoutSeconds } = resolved.options;
|
|
132
|
+
logger.debug("server", "resolved options", {
|
|
133
|
+
defaultModel,
|
|
134
|
+
defaultMode,
|
|
135
|
+
bashApproval,
|
|
136
|
+
tiers: tiers.map((t) => `${t.tier}=${t.model}`),
|
|
137
|
+
catalogOverrides: catalogOverrides.length,
|
|
138
|
+
mcpConnectTimeoutSeconds,
|
|
139
|
+
});
|
|
140
|
+
try {
|
|
141
|
+
await connection.closed;
|
|
142
|
+
return 0;
|
|
143
|
+
}
|
|
144
|
+
catch (error) {
|
|
145
|
+
logger.error("server", "connection failed", { error: error instanceof Error ? error.message : String(error) });
|
|
146
|
+
return 1;
|
|
147
|
+
}
|
|
148
|
+
finally {
|
|
149
|
+
// S5-2 shutdown (M-16): no running turn outlives its client.
|
|
150
|
+
await registry.closeAll();
|
|
151
|
+
}
|
|
152
|
+
}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Connects one ACP session's MCP servers (S5-5 spec §4.1, §5.1-§5.3): all in
|
|
3
|
+
* parallel through the shared layer, each bounded by the connect timeout; a
|
|
4
|
+
* failure skips that server with a scrubbed notice line (stderr tail included).
|
|
5
|
+
* Tools are taken server by server in list order up to MCP_MAX_TOOLS, shaped
|
|
6
|
+
* and named. If the signal aborts (shutdown), everything connected is closed.
|
|
7
|
+
*/
|
|
8
|
+
import type { connectMcp, McpToolInfo } from "@nathapp/nax-agent/mcp";
|
|
9
|
+
import { type NamedTool, type ToolRef } from "#src/server/mcp/naming";
|
|
10
|
+
import { type ParsedServers } from "#src/server/mcp/parse";
|
|
11
|
+
import { type Scrub } from "#src/server/mcp/secrets";
|
|
12
|
+
import { type BridgedTool, type McpSessionTools } from "#src/server/mcp/session-tools";
|
|
13
|
+
export declare const MCP_MAX_TOOLS = 200;
|
|
14
|
+
export interface SessionMcp {
|
|
15
|
+
readonly tools: McpSessionTools;
|
|
16
|
+
readonly noticeLines: readonly string[];
|
|
17
|
+
readonly scrub: Scrub;
|
|
18
|
+
}
|
|
19
|
+
export interface ConnectSessionMcpInput {
|
|
20
|
+
readonly parsed: ParsedServers;
|
|
21
|
+
readonly cwd: string;
|
|
22
|
+
readonly signal: AbortSignal;
|
|
23
|
+
readonly onDisconnect: (server: string, reason: string) => void;
|
|
24
|
+
}
|
|
25
|
+
export type ConnectSessionMcp = (input: ConnectSessionMcpInput) => Promise<SessionMcp>;
|
|
26
|
+
export interface McpConnectorDeps {
|
|
27
|
+
readonly connect: typeof connectMcp;
|
|
28
|
+
readonly timeoutMs: number;
|
|
29
|
+
readonly clientVersion: string;
|
|
30
|
+
readonly closeGraceMs?: number;
|
|
31
|
+
}
|
|
32
|
+
export declare const connectNothing: ConnectSessionMcp;
|
|
33
|
+
export interface Candidate extends ToolRef {
|
|
34
|
+
readonly info: McpToolInfo;
|
|
35
|
+
}
|
|
36
|
+
/** Names a candidate into what the model sees; candidates without matching info are skipped. */
|
|
37
|
+
export declare function bridgeTools(candidates: readonly Candidate[], named: readonly NamedTool[]): BridgedTool[];
|
|
38
|
+
export declare function createMcpConnector(deps: McpConnectorDeps): ConnectSessionMcp;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { McpConnectError } from "@nathapp/nax-agent/mcp";
|
|
2
|
+
import { nameTools } from "#src/server/mcp/naming";
|
|
3
|
+
import { cappedItems, displayName } from "#src/server/mcp/parse";
|
|
4
|
+
import { mcpSecrets, scrubber } from "#src/server/mcp/secrets";
|
|
5
|
+
import { createMcpSessionTools, NO_MCP_TOOLS, } from "#src/server/mcp/session-tools";
|
|
6
|
+
import { shapeDescription, shapeSchema } from "#src/server/mcp/tool-shape";
|
|
7
|
+
export const MCP_MAX_TOOLS = 200;
|
|
8
|
+
export const connectNothing = async () => ({
|
|
9
|
+
tools: NO_MCP_TOOLS,
|
|
10
|
+
noticeLines: [],
|
|
11
|
+
scrub: (t) => t,
|
|
12
|
+
});
|
|
13
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
14
|
+
function failureLine(server, error) {
|
|
15
|
+
const tail = error instanceof McpConnectError && error.stderrTail !== undefined ? ` (stderr: ${error.stderrTail})` : "";
|
|
16
|
+
return `\`${displayName(server.name)}\`: ${messageOf(error)}${tail}`;
|
|
17
|
+
}
|
|
18
|
+
function collectTools(live, lines) {
|
|
19
|
+
const kept = [];
|
|
20
|
+
const overLimit = [];
|
|
21
|
+
const schemaDropped = [];
|
|
22
|
+
for (const server of live) {
|
|
23
|
+
for (const info of server.connection.tools) {
|
|
24
|
+
const shaped = shapeSchema(info.inputSchema);
|
|
25
|
+
if (!shaped.ok) {
|
|
26
|
+
schemaDropped.push(`\`${displayName(server.name)}\`: tool \`${displayName(info.name)}\` dropped: ${shaped.reason}`);
|
|
27
|
+
}
|
|
28
|
+
else if (kept.length >= MCP_MAX_TOOLS) {
|
|
29
|
+
overLimit.push(`\`${displayName(server.name)}\`: ${displayName(info.name)}`);
|
|
30
|
+
}
|
|
31
|
+
else {
|
|
32
|
+
kept.push({ server: server.name, tool: info.name, info: { ...info, inputSchema: shaped.schema } });
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
lines.push(...cappedItems(schemaDropped));
|
|
37
|
+
if (overLimit.length > 0)
|
|
38
|
+
lines.push(`MCP tool limit (${MCP_MAX_TOOLS}) reached; dropped ${overLimit.length} tools: ${cappedItems(overLimit).join("; ")}`);
|
|
39
|
+
return kept;
|
|
40
|
+
}
|
|
41
|
+
/** Names a candidate into what the model sees; candidates without matching info are skipped. */
|
|
42
|
+
export function bridgeTools(candidates, named) {
|
|
43
|
+
const infoOf = new Map(candidates.map((c) => [`${c.server}\0${c.tool}`, c.info]));
|
|
44
|
+
return named.flatMap((n) => {
|
|
45
|
+
const info = infoOf.get(`${n.server}\0${n.tool}`);
|
|
46
|
+
if (info === undefined)
|
|
47
|
+
return [];
|
|
48
|
+
return [
|
|
49
|
+
{
|
|
50
|
+
modelName: n.modelName,
|
|
51
|
+
server: n.server,
|
|
52
|
+
tool: n.tool,
|
|
53
|
+
description: shapeDescription(displayName(n.server), info.description),
|
|
54
|
+
inputSchema: info.inputSchema,
|
|
55
|
+
},
|
|
56
|
+
];
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
function bridged(candidates, lines) {
|
|
60
|
+
const { named, dropped } = nameTools(candidates);
|
|
61
|
+
lines.push(...cappedItems(dropped.map((ref) => `\`${displayName(ref.server)}\`: tool \`${displayName(ref.tool)}\` dropped: duplicate name`)));
|
|
62
|
+
return bridgeTools(candidates, named);
|
|
63
|
+
}
|
|
64
|
+
export function createMcpConnector(deps) {
|
|
65
|
+
return async (input) => {
|
|
66
|
+
const scrub = scrubber(mcpSecrets(input.parsed.servers));
|
|
67
|
+
const settled = await Promise.allSettled(input.parsed.servers.map((server) => deps.connect(server.kind === "stdio"
|
|
68
|
+
? { kind: "stdio", command: server.command, args: server.args, env: server.env, cwd: input.cwd }
|
|
69
|
+
: { kind: "http", url: server.url, headers: server.headers }, {
|
|
70
|
+
signal: input.signal,
|
|
71
|
+
timeoutMs: deps.timeoutMs,
|
|
72
|
+
clientInfo: { name: "nax-agent", version: deps.clientVersion },
|
|
73
|
+
...(deps.closeGraceMs !== undefined ? { closeGraceMs: deps.closeGraceMs } : {}),
|
|
74
|
+
})));
|
|
75
|
+
const live = [];
|
|
76
|
+
const lines = [...input.parsed.skipped];
|
|
77
|
+
input.parsed.servers.forEach((server, i) => {
|
|
78
|
+
const result = settled[i];
|
|
79
|
+
if (result?.status === "fulfilled")
|
|
80
|
+
live.push({ name: server.name, connection: result.value });
|
|
81
|
+
else if (result !== undefined)
|
|
82
|
+
lines.push(failureLine(server, result.reason));
|
|
83
|
+
});
|
|
84
|
+
if (input.signal.aborted) {
|
|
85
|
+
await Promise.all(live.map((s) => s.connection.close().catch(() => undefined)));
|
|
86
|
+
throw new McpConnectError("MCP connect aborted: the server is shutting down");
|
|
87
|
+
}
|
|
88
|
+
const tools = bridged(collectTools(live, lines), lines);
|
|
89
|
+
return {
|
|
90
|
+
tools: createMcpSessionTools({ servers: live, tools, scrub, onDisconnect: input.onDisconnect }),
|
|
91
|
+
noticeLines: lines.map(scrub),
|
|
92
|
+
scrub,
|
|
93
|
+
};
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export declare const TOOL_NAME_MAX = 64;
|
|
2
|
+
export interface ToolRef {
|
|
3
|
+
readonly server: string;
|
|
4
|
+
readonly tool: string;
|
|
5
|
+
}
|
|
6
|
+
export interface NamedTool extends ToolRef {
|
|
7
|
+
readonly modelName: string;
|
|
8
|
+
}
|
|
9
|
+
export declare function nameTools(refs: readonly ToolRef[]): {
|
|
10
|
+
readonly named: readonly NamedTool[];
|
|
11
|
+
readonly dropped: readonly ToolRef[];
|
|
12
|
+
};
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Model-facing MCP tool names (S5-5 spec §5.1): `<server>__<tool>`, each part
|
|
3
|
+
* reduced to [A-Za-z0-9_-], a server part starting with a non-letter prefixed
|
|
4
|
+
* `m`. Over 64 characters, or colliding with another tool's name, a name is cut
|
|
5
|
+
* to 55 and given `_` + 8 hex chars of SHA-256 over `server\0tool`.
|
|
6
|
+
*
|
|
7
|
+
* The 55-char cut can drop the `__` separator when the sanitised server part is
|
|
8
|
+
* long, but every produced name still satisfies `^[A-Za-z][A-Za-z0-9_-]{0,63}$`
|
|
9
|
+
* and is unique, and built-in tool names are short and contain no `__`, so a
|
|
10
|
+
* produced name can never equal a built-in.
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from "node:crypto";
|
|
13
|
+
export const TOOL_NAME_MAX = 64;
|
|
14
|
+
const CUT = 55;
|
|
15
|
+
const clean = (part) => part.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
16
|
+
function baseName(ref) {
|
|
17
|
+
const server = clean(ref.server);
|
|
18
|
+
return `${/^[A-Za-z]/.test(server) ? server : `m${server}`}__${clean(ref.tool)}`;
|
|
19
|
+
}
|
|
20
|
+
function hashed(ref, base) {
|
|
21
|
+
const digest = createHash("sha256").update(`${ref.server}\0${ref.tool}`).digest("hex").slice(0, 8);
|
|
22
|
+
return `${base.slice(0, CUT)}_${digest}`;
|
|
23
|
+
}
|
|
24
|
+
export function nameTools(refs) {
|
|
25
|
+
const bases = refs.map(baseName);
|
|
26
|
+
const counts = new Map();
|
|
27
|
+
for (const base of bases)
|
|
28
|
+
counts.set(base, (counts.get(base) ?? 0) + 1);
|
|
29
|
+
const named = [];
|
|
30
|
+
const dropped = [];
|
|
31
|
+
const used = new Set();
|
|
32
|
+
refs.forEach((ref, i) => {
|
|
33
|
+
const base = bases[i] ?? "";
|
|
34
|
+
const modelName = base.length > TOOL_NAME_MAX || (counts.get(base) ?? 0) > 1 ? hashed(ref, base) : base;
|
|
35
|
+
if (used.has(modelName)) {
|
|
36
|
+
dropped.push(ref);
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
used.add(modelName);
|
|
40
|
+
named.push({ ...ref, modelName });
|
|
41
|
+
});
|
|
42
|
+
return { named, dropped };
|
|
43
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/** MCP notice texts (S5-5 spec §6, §6.2). Lines come from client config and servers: stripped and scrubbed. */
|
|
2
|
+
import type { SessionUpdate } from "@agentclientprotocol/sdk";
|
|
3
|
+
import type { AgentSessionProfile } from "@nathapp/nax-agent";
|
|
4
|
+
import type { Scrub } from "#src/server/mcp/secrets";
|
|
5
|
+
export declare const OPEN_NOTICE_TITLE = "Some MCP servers or tools are not available";
|
|
6
|
+
export declare function openNotice(notices: boolean, lines: readonly string[], scrub: Scrub): SessionUpdate | undefined;
|
|
7
|
+
export declare function modeNotice(notices: boolean, mode: AgentSessionProfile): SessionUpdate;
|
|
8
|
+
export declare function disconnectNotice(notices: boolean, server: string, reason: string, scrub: Scrub): SessionUpdate;
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import { stripControl, stripInvisible } from "#src/client/text";
|
|
2
|
+
import { announce } from "#src/server/translate/notice";
|
|
3
|
+
export const OPEN_NOTICE_TITLE = "Some MCP servers or tools are not available";
|
|
4
|
+
const clean = (text, scrub) => scrub(stripInvisible(stripControl(text)));
|
|
5
|
+
export function openNotice(notices, lines, scrub) {
|
|
6
|
+
if (lines.length === 0)
|
|
7
|
+
return undefined;
|
|
8
|
+
return announce(notices, "warning", OPEN_NOTICE_TITLE, lines.map((line) => clean(line, scrub)).join("\n"));
|
|
9
|
+
}
|
|
10
|
+
export function modeNotice(notices, mode) {
|
|
11
|
+
const title = `MCP tools are off in ${mode} mode`;
|
|
12
|
+
// As an agent message the title and advice are one sentence.
|
|
13
|
+
if (!notices)
|
|
14
|
+
return announce(false, "info", `${title}; switch to ask or full to use them.`);
|
|
15
|
+
return announce(true, "info", title, "Switch to ask or full to use them.");
|
|
16
|
+
}
|
|
17
|
+
export function disconnectNotice(notices, server, reason, scrub) {
|
|
18
|
+
return announce(notices, "warning", `MCP server \`${clean(server, scrub)}\` disconnected`, `${clean(reason, scrub)}; reopen the session to reconnect`);
|
|
19
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
export declare const MCP_MAX_SERVERS = 20;
|
|
2
|
+
/** Client-supplied lists in notices are shown at most this long, then `; and N more`. */
|
|
3
|
+
export declare const NOTICE_LIST_MAX = 10;
|
|
4
|
+
export type ParsedServer = {
|
|
5
|
+
readonly kind: "stdio";
|
|
6
|
+
readonly name: string;
|
|
7
|
+
readonly command: string;
|
|
8
|
+
readonly args: readonly string[];
|
|
9
|
+
readonly env: Readonly<Record<string, string>>;
|
|
10
|
+
} | {
|
|
11
|
+
readonly kind: "http";
|
|
12
|
+
readonly name: string;
|
|
13
|
+
readonly url: string;
|
|
14
|
+
readonly headers: Readonly<Record<string, string>>;
|
|
15
|
+
};
|
|
16
|
+
export interface ParsedServers {
|
|
17
|
+
readonly servers: readonly ParsedServer[];
|
|
18
|
+
readonly skipped: readonly string[];
|
|
19
|
+
}
|
|
20
|
+
export declare const NO_SERVERS: ParsedServers;
|
|
21
|
+
export declare function displayName(name: string): string;
|
|
22
|
+
/** At most NOTICE_LIST_MAX items; when longer, the last item carries `; and N more`. */
|
|
23
|
+
export declare function cappedItems(items: readonly string[]): string[];
|
|
24
|
+
export declare function parseMcpServers(raw: readonly unknown[]): ParsedServers;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Client-supplied mcpServers (S5-5 spec §6, plan M-39..M-41). Structurally
|
|
3
|
+
* invalid input fails the request (invalid_params); unsupported transports,
|
|
4
|
+
* semantic problems and servers past the limit are skipped with a notice line.
|
|
5
|
+
*/
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { stripControl, stripInvisible } from "#src/client/text";
|
|
8
|
+
import { invalidParams } from "#src/server/errors";
|
|
9
|
+
export const MCP_MAX_SERVERS = 20;
|
|
10
|
+
/** Client-supplied lists in notices are shown at most this long, then `; and N more`. */
|
|
11
|
+
export const NOTICE_LIST_MAX = 10;
|
|
12
|
+
export const NO_SERVERS = { servers: [], skipped: [] };
|
|
13
|
+
const NameValues = z.array(z.object({ name: z.string(), value: z.string() })).default([]);
|
|
14
|
+
const Base = z.object({ name: z.string(), type: z.string().optional() });
|
|
15
|
+
const Stdio = z.object({
|
|
16
|
+
name: z.string(),
|
|
17
|
+
command: z.string(),
|
|
18
|
+
args: z.array(z.string()).default([]),
|
|
19
|
+
env: NameValues,
|
|
20
|
+
});
|
|
21
|
+
const Http = z.object({ name: z.string(), url: z.string(), headers: NameValues });
|
|
22
|
+
export function displayName(name) {
|
|
23
|
+
return stripInvisible(stripControl(name)).replace(/\s+/g, " ").trim();
|
|
24
|
+
}
|
|
25
|
+
/** At most NOTICE_LIST_MAX items; when longer, the last item carries `; and N more`. */
|
|
26
|
+
export function cappedItems(items) {
|
|
27
|
+
if (items.length <= NOTICE_LIST_MAX)
|
|
28
|
+
return [...items];
|
|
29
|
+
const kept = items.slice(0, NOTICE_LIST_MAX);
|
|
30
|
+
const last = kept.length - 1;
|
|
31
|
+
return [...kept.slice(0, last), `${kept[last]}; and ${items.length - NOTICE_LIST_MAX} more`];
|
|
32
|
+
}
|
|
33
|
+
const record = (items) => Object.fromEntries(items.map((item) => [item.name, item.value]));
|
|
34
|
+
function structural(schema, value, index) {
|
|
35
|
+
const parsed = schema.safeParse(value);
|
|
36
|
+
if (parsed.success)
|
|
37
|
+
return parsed.data;
|
|
38
|
+
const issue = parsed.error.issues[0];
|
|
39
|
+
const path = [`mcpServers[${index}]`, ...(issue?.path ?? []).map(String)].join(".");
|
|
40
|
+
throw invalidParams(`${path}: ${issue?.message ?? "invalid"}`);
|
|
41
|
+
}
|
|
42
|
+
function httpEntry(name, value, index) {
|
|
43
|
+
const http = structural(Http, value, index);
|
|
44
|
+
let url;
|
|
45
|
+
try {
|
|
46
|
+
url = new URL(http.url);
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
return { kind: "skip", line: `\`${displayName(name)}\`: url is not valid` };
|
|
50
|
+
}
|
|
51
|
+
if (url.protocol !== "http:" && url.protocol !== "https:")
|
|
52
|
+
return { kind: "skip", line: `\`${displayName(name)}\`: url must be http or https` };
|
|
53
|
+
return { kind: "server", server: { kind: "http", name, url: http.url, headers: record(http.headers) } };
|
|
54
|
+
}
|
|
55
|
+
function stdioEntry(name, value, index) {
|
|
56
|
+
const stdio = structural(Stdio, value, index);
|
|
57
|
+
if (stdio.command.trim() === "")
|
|
58
|
+
return { kind: "skip", line: `\`${displayName(name)}\`: empty command` };
|
|
59
|
+
return {
|
|
60
|
+
kind: "server",
|
|
61
|
+
server: { kind: "stdio", name, command: stdio.command, args: stdio.args, env: record(stdio.env) },
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function entryOf(value, index) {
|
|
65
|
+
const base = structural(Base, value, index);
|
|
66
|
+
const name = displayName(base.name);
|
|
67
|
+
if (name === "")
|
|
68
|
+
return { kind: "skip", line: "a server with an empty name was skipped" };
|
|
69
|
+
switch (base.type) {
|
|
70
|
+
case undefined:
|
|
71
|
+
case "stdio":
|
|
72
|
+
return stdioEntry(base.name, value, index);
|
|
73
|
+
case "http":
|
|
74
|
+
return httpEntry(base.name, value, index);
|
|
75
|
+
case "sse":
|
|
76
|
+
return { kind: "skip", line: `\`${name}\`: SSE transport is not supported` };
|
|
77
|
+
case "acp":
|
|
78
|
+
return { kind: "skip", line: `\`${name}\`: ACP-tunnelled MCP is not supported` };
|
|
79
|
+
default:
|
|
80
|
+
return { kind: "skip", line: `\`${name}\`: unsupported transport type ${JSON.stringify(base.type)}` };
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
export function parseMcpServers(raw) {
|
|
84
|
+
const entries = raw.map(entryOf); // every structural check runs before anything is kept
|
|
85
|
+
const servers = [];
|
|
86
|
+
const skipped = [];
|
|
87
|
+
const seen = new Set();
|
|
88
|
+
const overLimit = [];
|
|
89
|
+
for (const entry of entries) {
|
|
90
|
+
if (entry.kind === "skip") {
|
|
91
|
+
skipped.push(entry.line);
|
|
92
|
+
}
|
|
93
|
+
else if (seen.has(entry.server.name)) {
|
|
94
|
+
skipped.push(`\`${displayName(entry.server.name)}\`: duplicate server name (the first one is used)`);
|
|
95
|
+
}
|
|
96
|
+
else if (servers.length >= MCP_MAX_SERVERS) {
|
|
97
|
+
overLimit.push(`\`${displayName(entry.server.name)}\``);
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
seen.add(entry.server.name);
|
|
101
|
+
servers.push(entry.server);
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
if (overLimit.length > 0)
|
|
105
|
+
skipped.push(`MCP server limit (${MCP_MAX_SERVERS}) reached; not started: ${cappedItems(overLimit).join(", ")}`);
|
|
106
|
+
return { servers, skipped };
|
|
107
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The secret values of a session's MCP servers (S5-5 spec §6.1): env values
|
|
3
|
+
* whose names look secret (the ACP client's SECRET_KEY rule), every HTTP header
|
|
4
|
+
* value plus the token after an auth scheme, and an http url's password and
|
|
5
|
+
* query values. Scrubbing is value-based (min 8 chars) on top of redactSecrets.
|
|
6
|
+
*/
|
|
7
|
+
import { redactSecrets } from "@nathapp/nax-agent";
|
|
8
|
+
import { secretValues } from "#src/client/env";
|
|
9
|
+
import { scrubSecrets } from "#src/client/text";
|
|
10
|
+
const AUTH_SCHEME = /^\s*[A-Za-z][A-Za-z0-9._~+/-]*\s+(\S+)\s*$/;
|
|
11
|
+
function headerSecrets(headers) {
|
|
12
|
+
return Object.values(headers).flatMap((value) => {
|
|
13
|
+
const token = AUTH_SCHEME.exec(value)?.[1];
|
|
14
|
+
return token === undefined ? [value] : [value, token];
|
|
15
|
+
});
|
|
16
|
+
}
|
|
17
|
+
function decoded(value) {
|
|
18
|
+
try {
|
|
19
|
+
return decodeURIComponent(value);
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return value;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function urlSecrets(raw) {
|
|
26
|
+
let url;
|
|
27
|
+
try {
|
|
28
|
+
url = new URL(raw);
|
|
29
|
+
}
|
|
30
|
+
catch {
|
|
31
|
+
return [];
|
|
32
|
+
}
|
|
33
|
+
const query = [...url.searchParams.values()];
|
|
34
|
+
return url.password === "" ? query : [decoded(url.password), url.password, ...query];
|
|
35
|
+
}
|
|
36
|
+
export function mcpSecrets(servers) {
|
|
37
|
+
const all = servers.flatMap((server) => server.kind === "stdio"
|
|
38
|
+
? [...secretValues(server.env)]
|
|
39
|
+
: [...headerSecrets(server.headers), ...urlSecrets(server.url)]);
|
|
40
|
+
return [...new Set(all.filter((value) => value !== ""))];
|
|
41
|
+
}
|
|
42
|
+
export function scrubber(secrets) {
|
|
43
|
+
return (text) => scrubSecrets(redactSecrets(text), secrets);
|
|
44
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The MCP tools of ONE ACP session (S5-5 spec §3.2, §4.2-§4.5, §5.5). Owned by
|
|
3
|
+
* the registry entry, so connections survive mode and model switches; the tools
|
|
4
|
+
* handed to each reopened S3 session follow the mode (ask: approval always,
|
|
5
|
+
* full: never, none/read: none). A stdio server that exits is marked dead once;
|
|
6
|
+
* its tools then answer with an error result until the session is reopened.
|
|
7
|
+
*/
|
|
8
|
+
import type { AgentSessionProfile, EmbedderTool, JSONSchema } from "@nathapp/nax-agent";
|
|
9
|
+
import type { McpConnection } from "@nathapp/nax-agent/mcp";
|
|
10
|
+
import type { Scrub } from "#src/server/mcp/secrets";
|
|
11
|
+
export declare const MCP_RESULT_BYTES = 1048576;
|
|
12
|
+
export declare const MCP_CALL_TIMEOUT_MS = 600000;
|
|
13
|
+
export interface BridgedTool {
|
|
14
|
+
readonly modelName: string;
|
|
15
|
+
readonly server: string;
|
|
16
|
+
readonly tool: string;
|
|
17
|
+
readonly description: string;
|
|
18
|
+
readonly inputSchema: JSONSchema;
|
|
19
|
+
}
|
|
20
|
+
export interface LiveServer {
|
|
21
|
+
readonly name: string;
|
|
22
|
+
readonly connection: McpConnection;
|
|
23
|
+
}
|
|
24
|
+
export interface McpSessionTools {
|
|
25
|
+
readonly connectedCount: number;
|
|
26
|
+
offersTools(mode: AgentSessionProfile): boolean;
|
|
27
|
+
embedderTools(mode: AgentSessionProfile): readonly EmbedderTool[];
|
|
28
|
+
titleFor(modelName: string): string | undefined;
|
|
29
|
+
closeAll(): Promise<void>;
|
|
30
|
+
}
|
|
31
|
+
export declare const NO_MCP_TOOLS: McpSessionTools;
|
|
32
|
+
export declare function createMcpSessionTools(input: {
|
|
33
|
+
readonly servers: readonly LiveServer[];
|
|
34
|
+
readonly tools: readonly BridgedTool[];
|
|
35
|
+
readonly scrub: Scrub;
|
|
36
|
+
readonly onDisconnect: (server: string, reason: string) => void;
|
|
37
|
+
}): McpSessionTools;
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
import { displayName } from "#src/server/mcp/parse";
|
|
2
|
+
import { displayLine } from "#src/server/translate/tool-kind";
|
|
3
|
+
export const MCP_RESULT_BYTES = 1_048_576;
|
|
4
|
+
export const MCP_CALL_TIMEOUT_MS = 600_000;
|
|
5
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
6
|
+
const offers = (mode) => mode === "ask" || mode === "full";
|
|
7
|
+
export const NO_MCP_TOOLS = {
|
|
8
|
+
connectedCount: 0,
|
|
9
|
+
offersTools: offers,
|
|
10
|
+
embedderTools: () => [],
|
|
11
|
+
titleFor: () => undefined,
|
|
12
|
+
closeAll: async () => { },
|
|
13
|
+
};
|
|
14
|
+
export function createMcpSessionTools(input) {
|
|
15
|
+
const dead = new Map();
|
|
16
|
+
const byName = new Map(input.servers.map((s) => [s.name, s.connection]));
|
|
17
|
+
let closing;
|
|
18
|
+
for (const server of input.servers) {
|
|
19
|
+
server.connection.onClose((reason) => {
|
|
20
|
+
if (closing !== undefined || dead.has(server.name))
|
|
21
|
+
return;
|
|
22
|
+
dead.set(server.name, reason);
|
|
23
|
+
input.onDisconnect(server.name, reason);
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
async function run(tool, args, signal) {
|
|
27
|
+
const shown = displayName(tool.server);
|
|
28
|
+
const reason = dead.get(tool.server);
|
|
29
|
+
if (reason !== undefined)
|
|
30
|
+
return {
|
|
31
|
+
content: input.scrub(`MCP server \`${shown}\` disconnected: ${reason}; reopen the session to reconnect`),
|
|
32
|
+
isError: true,
|
|
33
|
+
};
|
|
34
|
+
const connection = byName.get(tool.server);
|
|
35
|
+
if (connection === undefined)
|
|
36
|
+
return { content: `MCP server \`${shown}\` is not connected`, isError: true };
|
|
37
|
+
try {
|
|
38
|
+
const result = await connection.call(tool.tool, args, {
|
|
39
|
+
signal,
|
|
40
|
+
timeoutMs: MCP_CALL_TIMEOUT_MS,
|
|
41
|
+
maxBytes: MCP_RESULT_BYTES,
|
|
42
|
+
});
|
|
43
|
+
return { content: input.scrub(result.text), isError: result.isError };
|
|
44
|
+
}
|
|
45
|
+
catch (error) {
|
|
46
|
+
return { content: input.scrub(`MCP server \`${shown}\`: ${messageOf(error)}`), isError: true };
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
const titles = new Map(input.tools.map((t) => [t.modelName, displayLine(`${t.server}: ${t.tool}`)]));
|
|
50
|
+
return {
|
|
51
|
+
connectedCount: input.servers.length,
|
|
52
|
+
offersTools: offers,
|
|
53
|
+
embedderTools(mode) {
|
|
54
|
+
if (!offers(mode))
|
|
55
|
+
return [];
|
|
56
|
+
return input.tools.map((tool) => ({
|
|
57
|
+
name: tool.modelName,
|
|
58
|
+
description: tool.description,
|
|
59
|
+
inputSchema: tool.inputSchema,
|
|
60
|
+
approval: mode === "ask" ? "always" : "never",
|
|
61
|
+
run: (args, ctx) => run(tool, args, ctx.signal),
|
|
62
|
+
}));
|
|
63
|
+
},
|
|
64
|
+
titleFor: (modelName) => titles.get(modelName),
|
|
65
|
+
closeAll() {
|
|
66
|
+
closing ??= Promise.all(input.servers.map((s) => s.connection.close().catch(() => undefined))).then(() => undefined);
|
|
67
|
+
return closing;
|
|
68
|
+
},
|
|
69
|
+
};
|
|
70
|
+
}
|