@nathapp/nax-agent-acp 0.84.0 → 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 +11 -0
- package/README.md +52 -3
- 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 +35 -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 +1 -0
- package/dist/server/nax-config.js +1 -0
- package/dist/server/open-session.d.ts +2 -1
- package/dist/server/open-session.js +1 -0
- package/dist/server/options.d.ts +3 -0
- package/dist/server/options.js +17 -0
- 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 +2 -2
|
@@ -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
|
+
}
|
|
@@ -11,6 +11,7 @@ export interface AgentServerSection {
|
|
|
11
11
|
readonly defaultMode?: AgentSessionProfile;
|
|
12
12
|
readonly bashApproval?: BashApproval;
|
|
13
13
|
readonly sessionsDir?: string;
|
|
14
|
+
readonly mcpConnectTimeoutSeconds?: number;
|
|
14
15
|
}
|
|
15
16
|
export interface NaxConfigSubset {
|
|
16
17
|
readonly tiers: readonly TierModel[];
|
|
@@ -43,6 +43,7 @@ const SubsetSchema = z.object({
|
|
|
43
43
|
defaultMode: z.enum(MODES).optional(),
|
|
44
44
|
bashApproval: z.enum(BASH_APPROVALS).optional(),
|
|
45
45
|
sessionsDir: z.string().min(1).optional(),
|
|
46
|
+
mcpConnectTimeoutSeconds: z.number().int().min(1).max(300).optional(),
|
|
46
47
|
})
|
|
47
48
|
.optional(),
|
|
48
49
|
});
|
|
@@ -4,7 +4,7 @@
|
|
|
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";
|
|
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
8
|
import type { BashApproval } from "#src/server/nax-config";
|
|
9
9
|
export interface OpenSessionRequest {
|
|
10
10
|
readonly sessionId: string;
|
|
@@ -12,6 +12,7 @@ export interface OpenSessionRequest {
|
|
|
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;
|
|
@@ -46,6 +46,7 @@ export function nativeOpenSession(deps) {
|
|
|
46
46
|
sessionId: request.sessionId,
|
|
47
47
|
profile: request.profile,
|
|
48
48
|
...(request.profile !== "none" ? { workdir: request.cwd } : {}),
|
|
49
|
+
...(request.tools.length > 0 ? { tools: request.tools } : {}),
|
|
49
50
|
transcriptStore: deps.transcripts,
|
|
50
51
|
turnTimeoutSeconds: deps.turnTimeoutSeconds,
|
|
51
52
|
};
|
package/dist/server/options.d.ts
CHANGED
|
@@ -2,6 +2,8 @@ import type { AgentSessionProfile } from "@nathapp/nax-agent";
|
|
|
2
2
|
import type { CliFlags } from "#src/server/cli";
|
|
3
3
|
import { type BashApproval, type NaxConfigSubset, type TierModel } from "#src/server/nax-config";
|
|
4
4
|
export type Env = Readonly<Record<string, string | undefined>>;
|
|
5
|
+
/** S5-5b: the per-server MCP connect timeout, in seconds (1-300). */
|
|
6
|
+
export declare const MCP_CONNECT_TIMEOUT_SECONDS = 30;
|
|
5
7
|
export interface ServerOptions {
|
|
6
8
|
readonly configDir: string;
|
|
7
9
|
readonly sessionsDir: string;
|
|
@@ -10,6 +12,7 @@ export interface ServerOptions {
|
|
|
10
12
|
readonly bashApproval: BashApproval;
|
|
11
13
|
readonly tiers: readonly TierModel[];
|
|
12
14
|
readonly catalogOverrides: readonly Readonly<Record<string, unknown>>[];
|
|
15
|
+
readonly mcpConnectTimeoutSeconds: number;
|
|
13
16
|
}
|
|
14
17
|
export type OptionsResult = {
|
|
15
18
|
readonly ok: true;
|
package/dist/server/options.js
CHANGED
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
*/
|
|
5
5
|
import { join } from "node:path";
|
|
6
6
|
import { BASH_APPROVALS, MODES } from "#src/server/nax-config";
|
|
7
|
+
/** S5-5b: the per-server MCP connect timeout, in seconds (1-300). */
|
|
8
|
+
export const MCP_CONNECT_TIMEOUT_SECONDS = 30;
|
|
7
9
|
function firstSet(...candidates) {
|
|
8
10
|
return candidates.find((c) => c !== undefined && c.value !== "");
|
|
9
11
|
}
|
|
@@ -24,6 +26,17 @@ function pickEnum(label, allowed, chosen, fallbackValue) {
|
|
|
24
26
|
message: `invalid ${label} "${chosen.value}" (from ${chosen.source}); expected one of ${allowed.join(", ")}`,
|
|
25
27
|
};
|
|
26
28
|
}
|
|
29
|
+
function pickSeconds(chosen, fallbackValue) {
|
|
30
|
+
if (chosen === undefined)
|
|
31
|
+
return { ok: true, value: fallbackValue };
|
|
32
|
+
const value = Number(chosen.value);
|
|
33
|
+
if (Number.isInteger(value) && value >= 1 && value <= 300)
|
|
34
|
+
return { ok: true, value };
|
|
35
|
+
return {
|
|
36
|
+
ok: false,
|
|
37
|
+
message: `invalid mcp connect timeout "${chosen.value}" (from ${chosen.source}); expected whole seconds 1-300`,
|
|
38
|
+
};
|
|
39
|
+
}
|
|
27
40
|
export function resolveServerOptions(input) {
|
|
28
41
|
const { flags, env, file, configDir } = input;
|
|
29
42
|
const mode = pickEnum("mode", MODES, firstSet(from(flags.mode, "--mode"), from(env.NAX_AGENT_MODE, "NAX_AGENT_MODE"), from(file.agentServer.defaultMode, "config.json agentServer.defaultMode")), "ask");
|
|
@@ -38,6 +51,9 @@ export function resolveServerOptions(input) {
|
|
|
38
51
|
message: `bash approval "${bash.value}" cannot be used with mode "ask"; ask requires gated`,
|
|
39
52
|
};
|
|
40
53
|
}
|
|
54
|
+
const mcpTimeout = pickSeconds(firstSet(from(flags.mcpConnectTimeout, "--mcp-connect-timeout"), from(env.NAX_AGENT_MCP_CONNECT_TIMEOUT, "NAX_AGENT_MCP_CONNECT_TIMEOUT"), from(file.agentServer.mcpConnectTimeoutSeconds?.toString(), "config.json agentServer.mcpConnectTimeoutSeconds")), MCP_CONNECT_TIMEOUT_SECONDS);
|
|
55
|
+
if (!mcpTimeout.ok)
|
|
56
|
+
return mcpTimeout;
|
|
41
57
|
const sessionsDir = firstSet(from(flags.sessionsDir, "--sessions-dir"), from(env.NAX_AGENT_SESSIONS_DIR, "NAX_AGENT_SESSIONS_DIR"), from(file.agentServer.sessionsDir, "config.json agentServer.sessionsDir"))?.value ?? join(configDir, ".agent-server", "sessions");
|
|
42
58
|
const defaultModel = firstSet(from(flags.model, "--model"), from(env.NAX_AGENT_MODEL, "NAX_AGENT_MODEL"), from(file.tiers.find((t) => t.tier === "balanced")?.model, "config.json models.native.balanced"))?.value;
|
|
43
59
|
return {
|
|
@@ -50,6 +66,7 @@ export function resolveServerOptions(input) {
|
|
|
50
66
|
bashApproval: bash.value,
|
|
51
67
|
tiers: file.tiers,
|
|
52
68
|
catalogOverrides: file.catalogOverrides,
|
|
69
|
+
mcpConnectTimeoutSeconds: mcpTimeout.value,
|
|
53
70
|
},
|
|
54
71
|
};
|
|
55
72
|
}
|
package/dist/server/questions.js
CHANGED
|
@@ -22,6 +22,17 @@ function answerText(response) {
|
|
|
22
22
|
const value = typeof content === "object" && content !== null ? Reflect.get(content, ANSWER_FIELD) : undefined;
|
|
23
23
|
return typeof value === "string" && value.trim() !== "" ? value : DECLINED_TEXT;
|
|
24
24
|
}
|
|
25
|
+
const MAX_TIMER_DELAY = 2_147_483_647;
|
|
26
|
+
function armExpiry(expiresAt, now, onExpire) {
|
|
27
|
+
let timer;
|
|
28
|
+
const arm = () => {
|
|
29
|
+
const delta = Date.parse(expiresAt) - now();
|
|
30
|
+
const remaining = delta > 0 ? delta : 0;
|
|
31
|
+
timer = remaining > MAX_TIMER_DELAY ? setTimeout(arm, MAX_TIMER_DELAY) : setTimeout(onExpire, remaining);
|
|
32
|
+
};
|
|
33
|
+
arm();
|
|
34
|
+
return () => clearTimeout(timer);
|
|
35
|
+
}
|
|
25
36
|
export function createQuestionBroker(deps) {
|
|
26
37
|
const now = deps.now ?? Date.now;
|
|
27
38
|
const open = new Set();
|
|
@@ -30,7 +41,7 @@ export function createQuestionBroker(deps) {
|
|
|
30
41
|
async function elicit(event) {
|
|
31
42
|
const controller = new AbortController();
|
|
32
43
|
open.add(controller);
|
|
33
|
-
const
|
|
44
|
+
const clearExpiry = armExpiry(event.expiresAt, now, () => controller.abort());
|
|
34
45
|
let text;
|
|
35
46
|
try {
|
|
36
47
|
text = answerText(await untilAborted(deps.port.elicit(formFor(event.text), controller.signal), controller.signal));
|
|
@@ -42,7 +53,7 @@ export function createQuestionBroker(deps) {
|
|
|
42
53
|
text = NO_ANSWER_TEXT;
|
|
43
54
|
}
|
|
44
55
|
finally {
|
|
45
|
-
|
|
56
|
+
clearExpiry();
|
|
46
57
|
open.delete(controller);
|
|
47
58
|
}
|
|
48
59
|
deps.answer(event.requestId, { text });
|
|
@@ -17,13 +17,12 @@ export interface ReopenDeps {
|
|
|
17
17
|
readonly storage: SessionStorage;
|
|
18
18
|
readonly transcripts: TranscriptStore;
|
|
19
19
|
readonly logger: AgentLogger;
|
|
20
|
-
readonly openEntry: (meta: SessionMeta, port: ClientPort) => Promise<{
|
|
20
|
+
readonly openEntry: (meta: SessionMeta, port: ClientPort, mcpServers: readonly unknown[]) => Promise<{
|
|
21
21
|
readonly server: ServerSession;
|
|
22
22
|
readonly opened: OpenedSession;
|
|
23
23
|
}>;
|
|
24
24
|
readonly closeEntry: (sessionId: string, entry: Entry) => Promise<void>;
|
|
25
25
|
readonly stateOf: (settings: SessionSettings) => SessionState;
|
|
26
|
-
readonly mcpNotice: string;
|
|
27
26
|
readonly interruptedNotice: string;
|
|
28
27
|
}
|
|
29
28
|
export interface Reopener {
|
|
@@ -7,22 +7,22 @@ export const settingsOf = (meta) => ({
|
|
|
7
7
|
bashApproval: meta.bashApproval,
|
|
8
8
|
});
|
|
9
9
|
export function createReopen(deps) {
|
|
10
|
-
async function replayTo(port, messages, cwd) {
|
|
11
|
-
for (const update of replayTranscript(messages, cwd))
|
|
10
|
+
async function replayTo(port, messages, cwd, titleFor) {
|
|
11
|
+
for (const update of replayTranscript(messages, cwd, titleFor))
|
|
12
12
|
await port.update(update);
|
|
13
13
|
}
|
|
14
|
-
async function replayOpened(port, opened, cwd) {
|
|
15
|
-
await replayTo(port, opened.doc?.messages ?? [], cwd);
|
|
14
|
+
async function replayOpened(port, sessionId, opened, cwd) {
|
|
15
|
+
await replayTo(port, opened.doc?.messages ?? [], cwd, (name) => deps.entries.get(sessionId)?.mcp.titleFor(name));
|
|
16
16
|
if (opened.session.lastTurn?.status === "interrupted") {
|
|
17
17
|
await port.update(announce(port.features.updates.notices, "warning", deps.interruptedNotice));
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
async function openAndReplay(sessionId, meta, input, replay) {
|
|
21
21
|
const port = input.port(sessionId);
|
|
22
|
-
const {
|
|
22
|
+
const { opened } = await deps.openEntry(meta, port, input.mcpServers);
|
|
23
23
|
if (replay) {
|
|
24
24
|
try {
|
|
25
|
-
await replayOpened(port, opened, meta.cwd);
|
|
25
|
+
await replayOpened(port, sessionId, opened, meta.cwd);
|
|
26
26
|
}
|
|
27
27
|
catch (error) {
|
|
28
28
|
// The client did not get its history: do not leave the session open and locked.
|
|
@@ -32,16 +32,14 @@ export function createReopen(deps) {
|
|
|
32
32
|
throw error;
|
|
33
33
|
}
|
|
34
34
|
}
|
|
35
|
-
if (input.mcpServers.length > 0) {
|
|
36
|
-
server.queueNotice(announce(port.features.updates.notices, "warning", deps.mcpNotice));
|
|
37
|
-
}
|
|
38
35
|
}
|
|
39
36
|
return {
|
|
40
37
|
async reopen(sessionId, input, replay) {
|
|
41
38
|
const open = deps.entries.get(sessionId);
|
|
42
39
|
if (open !== undefined) {
|
|
40
|
+
// An already-open session keeps its connection and ignores input.mcpServers (§4.4).
|
|
43
41
|
if (replay) {
|
|
44
|
-
await replayTo(open.port, (await deps.transcripts.load(sessionId))?.messages ?? [], open.meta.cwd);
|
|
42
|
+
await replayTo(open.port, (await deps.transcripts.load(sessionId))?.messages ?? [], open.meta.cwd, (name) => open.mcp.titleFor(name));
|
|
45
43
|
}
|
|
46
44
|
return deps.stateOf(settingsOf(open.meta));
|
|
47
45
|
}
|