@nathapp/nax-agent-acp 0.84.0 → 0.85.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/CHANGELOG.md +21 -0
- package/README.md +54 -4
- package/dist/server/auth.d.ts +2 -0
- package/dist/server/auth.js +6 -6
- package/dist/server/capabilities.d.ts +2 -1
- package/dist/server/capabilities.js +3 -1
- package/dist/server/cli.d.ts +1 -0
- package/dist/server/cli.js +3 -0
- package/dist/server/default-model.d.ts +36 -0
- package/dist/server/default-model.js +158 -0
- package/dist/server/login.d.ts +2 -0
- package/dist/server/login.js +9 -0
- package/dist/server/main.d.ts +5 -0
- package/dist/server/main.js +36 -3
- 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 +6 -1
- package/dist/server/nax-config.js +41 -1
- package/dist/server/open-session.d.ts +5 -2
- package/dist/server/open-session.js +2 -0
- package/dist/server/options.d.ts +6 -1
- package/dist/server/options.js +19 -1
- package/dist/server/questions.js +13 -2
- package/dist/server/registry-open.d.ts +1 -2
- package/dist/server/registry-open.js +8 -10
- package/dist/server/registry.d.ts +18 -3
- package/dist/server/registry.js +116 -45
- package/dist/server/server-session.d.ts +2 -0
- package/dist/server/server-session.js +1 -0
- package/dist/server/session-config.d.ts +4 -2
- package/dist/server/session-config.js +11 -0
- package/dist/server/translate/events.d.ts +2 -0
- package/dist/server/translate/events.js +1 -1
- package/dist/server/translate/replay.d.ts +1 -1
- package/dist/server/translate/replay.js +6 -6
- package/package.json +3 -3
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What the model sees of an MCP tool (S5-5 spec §5.2): a control-stripped,
|
|
3
|
+
* 2 KiB-capped description prefixed with its server, and an input schema that
|
|
4
|
+
* must be a JSON object of type "object" (`$schema` removed, missing
|
|
5
|
+
* `properties` added) within 32 KiB. A schema the provider rejects for other
|
|
6
|
+
* reasons is not contained here.
|
|
7
|
+
*/
|
|
8
|
+
import type { JSONSchema } from "@nathapp/nax-agent";
|
|
9
|
+
export declare const MCP_DESCRIPTION_BYTES = 2048;
|
|
10
|
+
export declare const MCP_SCHEMA_BYTES = 32768;
|
|
11
|
+
export type ShapedSchema = {
|
|
12
|
+
readonly ok: true;
|
|
13
|
+
readonly schema: JSONSchema;
|
|
14
|
+
} | {
|
|
15
|
+
readonly ok: false;
|
|
16
|
+
readonly reason: string;
|
|
17
|
+
};
|
|
18
|
+
export declare function shapeDescription(server: string, description: string): string;
|
|
19
|
+
export declare function shapeSchema(schema: unknown): ShapedSchema;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { capBytes, isRecord, stripControl, stripInvisible } from "#src/client/text";
|
|
2
|
+
export const MCP_DESCRIPTION_BYTES = 2048;
|
|
3
|
+
export const MCP_SCHEMA_BYTES = 32_768;
|
|
4
|
+
export function shapeDescription(server, description) {
|
|
5
|
+
const text = stripInvisible(stripControl(description)).trim();
|
|
6
|
+
return capBytes(text === "" ? `[${server}]` : `[${server}] ${text}`, MCP_DESCRIPTION_BYTES);
|
|
7
|
+
}
|
|
8
|
+
export function shapeSchema(schema) {
|
|
9
|
+
if (!isRecord(schema))
|
|
10
|
+
return { ok: false, reason: "input schema is not an object" };
|
|
11
|
+
if (schema.type !== "object")
|
|
12
|
+
return { ok: false, reason: 'input schema type must be "object"' };
|
|
13
|
+
if (schema.properties !== undefined && !isRecord(schema.properties))
|
|
14
|
+
return { ok: false, reason: "input schema properties must be an object" };
|
|
15
|
+
const { $schema: _dropped, ...rest } = schema;
|
|
16
|
+
const shaped = { ...rest, properties: schema.properties ?? {} };
|
|
17
|
+
if (Buffer.byteLength(JSON.stringify(shaped), "utf8") > MCP_SCHEMA_BYTES)
|
|
18
|
+
return { ok: false, reason: `input schema is larger than ${MCP_SCHEMA_BYTES} bytes` };
|
|
19
|
+
return { ok: true, schema: shaped };
|
|
20
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type AgentSessionProfile, type CredentialAuthConfig, type CredentialsConfig, type NativeBackendOptions } from "@nathapp/nax-agent";
|
|
2
2
|
export type ReadTextFile = (path: string, encoding: "utf8") => Promise<string>;
|
|
3
3
|
export type BashApproval = "gated" | "escalate" | "raw";
|
|
4
4
|
export declare const TIERS: readonly ["fast", "balanced", "powerful"];
|
|
@@ -11,12 +11,17 @@ export interface AgentServerSection {
|
|
|
11
11
|
readonly defaultMode?: AgentSessionProfile;
|
|
12
12
|
readonly bashApproval?: BashApproval;
|
|
13
13
|
readonly sessionsDir?: string;
|
|
14
|
+
readonly mcpConnectTimeoutSeconds?: number;
|
|
14
15
|
}
|
|
16
|
+
/** `execution.compaction` as nax-agent's native backend takes it; nax-agent validates and applies the defaults. */
|
|
17
|
+
export type CompactionSettings = NonNullable<NativeBackendOptions["compaction"]>;
|
|
15
18
|
export interface NaxConfigSubset {
|
|
16
19
|
readonly tiers: readonly TierModel[];
|
|
17
20
|
readonly catalogOverrides: readonly Readonly<Record<string, unknown>>[];
|
|
18
21
|
readonly auth: CredentialAuthConfig;
|
|
19
22
|
readonly agentServer: AgentServerSection;
|
|
23
|
+
/** The raw `execution.compaction` object; absent when the file sets none. */
|
|
24
|
+
readonly compaction?: CompactionSettings;
|
|
20
25
|
}
|
|
21
26
|
export interface LoadedNaxConfig {
|
|
22
27
|
readonly config: NaxConfigSubset;
|
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* warning; the server still starts.
|
|
6
6
|
*/
|
|
7
7
|
import { join } from "node:path";
|
|
8
|
+
import { nativeBackend, } from "@nathapp/nax-agent";
|
|
8
9
|
import { z } from "zod";
|
|
9
10
|
export const TIERS = ["fast", "balanced", "powerful"];
|
|
10
11
|
export const MODES = ["none", "read", "ask", "full"];
|
|
@@ -38,11 +39,14 @@ const SubsetSchema = z.object({
|
|
|
38
39
|
})
|
|
39
40
|
.optional(),
|
|
40
41
|
auth: AuthSchema.optional(),
|
|
42
|
+
// nax owns the rest of `execution`; only compaction is read, and only when it is there.
|
|
43
|
+
execution: z.unknown().optional(),
|
|
41
44
|
agentServer: z
|
|
42
45
|
.object({
|
|
43
46
|
defaultMode: z.enum(MODES).optional(),
|
|
44
47
|
bashApproval: z.enum(BASH_APPROVALS).optional(),
|
|
45
48
|
sessionsDir: z.string().min(1).optional(),
|
|
49
|
+
mcpConnectTimeoutSeconds: z.number().int().min(1).max(300).optional(),
|
|
46
50
|
})
|
|
47
51
|
.optional(),
|
|
48
52
|
});
|
|
@@ -81,6 +85,35 @@ function tiersFrom(native) {
|
|
|
81
85
|
}
|
|
82
86
|
return { tiers };
|
|
83
87
|
}
|
|
88
|
+
function isPlainRecord(value) {
|
|
89
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
90
|
+
}
|
|
91
|
+
const PROBE_MODEL = "openai/compaction-probe";
|
|
92
|
+
const OPTIONS_PREFIX = /^Invalid agent session options: backend\./;
|
|
93
|
+
/**
|
|
94
|
+
* The server does not know the compaction rules: nax-agent owns the schema (it
|
|
95
|
+
* is not importable from here). nativeBackend validates its options when it is
|
|
96
|
+
* built and does no I/O, so building one is the check. That is safe because
|
|
97
|
+
* construction is validation-only: it resolves no credentials and loads no
|
|
98
|
+
* catalog, and the probe model need not exist. nax-agent's native-backend test
|
|
99
|
+
* "construction is validation-only" guards this. The error text is the schema's
|
|
100
|
+
* own message, which never echoes the offending value.
|
|
101
|
+
*/
|
|
102
|
+
function compactionFrom(execution) {
|
|
103
|
+
if (!isPlainRecord(execution) || execution.compaction === undefined)
|
|
104
|
+
return {};
|
|
105
|
+
const raw = execution.compaction;
|
|
106
|
+
if (!isPlainRecord(raw))
|
|
107
|
+
return { issue: "execution.compaction: expected an object" };
|
|
108
|
+
const compaction = raw;
|
|
109
|
+
try {
|
|
110
|
+
nativeBackend({ model: PROBE_MODEL, compaction });
|
|
111
|
+
}
|
|
112
|
+
catch (error) {
|
|
113
|
+
return { issue: message(error).replace(OPTIONS_PREFIX, "execution.") };
|
|
114
|
+
}
|
|
115
|
+
return { compaction };
|
|
116
|
+
}
|
|
84
117
|
function authFrom(auth) {
|
|
85
118
|
if (auth === undefined)
|
|
86
119
|
return DEFAULT_AUTH;
|
|
@@ -91,7 +124,10 @@ function authFrom(auth) {
|
|
|
91
124
|
};
|
|
92
125
|
}
|
|
93
126
|
function fallback(path, reason) {
|
|
94
|
-
return {
|
|
127
|
+
return {
|
|
128
|
+
config: EMPTY_NAX_CONFIG,
|
|
129
|
+
warning: `ignoring ${path}: ${reason}; using built-in defaults (model tiers, auth and agentServer from this file are ignored too)`,
|
|
130
|
+
};
|
|
95
131
|
}
|
|
96
132
|
export async function loadNaxConfig(configDir, readFile) {
|
|
97
133
|
const path = join(configDir, "config.json");
|
|
@@ -120,8 +156,12 @@ export async function loadNaxConfig(configDir, readFile) {
|
|
|
120
156
|
const { tiers, issue } = tiersFrom(parsed.data.models?.native);
|
|
121
157
|
if (issue !== undefined)
|
|
122
158
|
return fallback(path, issue);
|
|
159
|
+
const compacted = compactionFrom(parsed.data.execution);
|
|
160
|
+
if (compacted.issue !== undefined)
|
|
161
|
+
return fallback(path, compacted.issue);
|
|
123
162
|
return {
|
|
124
163
|
config: {
|
|
164
|
+
...(compacted.compaction !== undefined ? { compaction: compacted.compaction } : {}),
|
|
125
165
|
tiers,
|
|
126
166
|
catalogOverrides: parsed.data.agent?.native?.catalogOverrides ?? [],
|
|
127
167
|
auth: authFrom(parsed.data.auth),
|
|
@@ -4,14 +4,15 @@
|
|
|
4
4
|
* store, resuming a stored session or creating a new one (S5-3 M-21). The
|
|
5
5
|
* facade factories are injectable for tests.
|
|
6
6
|
*/
|
|
7
|
-
import { type AgentLogger, type AgentSession, type AgentSessionProfile, type CreateAgentSessionOptions, type NativeBackendOptions, type NativeCatalogOverrides, type SessionBackend, type TranscriptDoc, type TranscriptStore } from "@nathapp/nax-agent";
|
|
8
|
-
import type { BashApproval } from "#src/server/nax-config";
|
|
7
|
+
import { type AgentLogger, type AgentSession, type AgentSessionProfile, type CreateAgentSessionOptions, type EmbedderTool, type NativeBackendOptions, type NativeCatalogOverrides, type SessionBackend, type TranscriptDoc, type TranscriptStore } from "@nathapp/nax-agent";
|
|
8
|
+
import type { BashApproval, CompactionSettings } from "#src/server/nax-config";
|
|
9
9
|
export interface OpenSessionRequest {
|
|
10
10
|
readonly sessionId: string;
|
|
11
11
|
readonly cwd: string;
|
|
12
12
|
readonly model: string;
|
|
13
13
|
readonly profile: AgentSessionProfile;
|
|
14
14
|
readonly bashApproval: BashApproval;
|
|
15
|
+
readonly tools: readonly EmbedderTool[];
|
|
15
16
|
}
|
|
16
17
|
export interface OpenedSession {
|
|
17
18
|
readonly session: AgentSession;
|
|
@@ -25,6 +26,8 @@ export interface NativeOpenDeps {
|
|
|
25
26
|
readonly transcripts: TranscriptStore;
|
|
26
27
|
readonly catalogOverrides: NativeCatalogOverrides;
|
|
27
28
|
readonly turnTimeoutSeconds: number;
|
|
29
|
+
/** `execution.compaction` from config.json; absent leaves nax-agent's defaults (on). */
|
|
30
|
+
readonly compaction?: CompactionSettings;
|
|
28
31
|
readonly create?: (options: CreateAgentSessionOptions) => Promise<AgentSession>;
|
|
29
32
|
readonly resume?: (sessionId: string, options: CreateAgentSessionOptions) => Promise<AgentSession>;
|
|
30
33
|
readonly backend?: (options: NativeBackendOptions) => SessionBackend;
|
|
@@ -42,10 +42,12 @@ export function nativeOpenSession(deps) {
|
|
|
42
42
|
carryHistoryAcrossModels: true,
|
|
43
43
|
...(TOOL_PROFILES.has(request.profile) ? { bashApproval: request.bashApproval } : {}),
|
|
44
44
|
...(deps.catalogOverrides.length > 0 ? { catalogOverrides: deps.catalogOverrides } : {}),
|
|
45
|
+
...(deps.compaction !== undefined ? { compaction: deps.compaction } : {}),
|
|
45
46
|
}),
|
|
46
47
|
sessionId: request.sessionId,
|
|
47
48
|
profile: request.profile,
|
|
48
49
|
...(request.profile !== "none" ? { workdir: request.cwd } : {}),
|
|
50
|
+
...(request.tools.length > 0 ? { tools: request.tools } : {}),
|
|
49
51
|
transcriptStore: deps.transcripts,
|
|
50
52
|
turnTimeoutSeconds: deps.turnTimeoutSeconds,
|
|
51
53
|
};
|