pi-mcp-extension 1.16.7 → 1.16.8
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/README.md +1 -1
- package/package.json +1 -1
- package/src/index.ts +15 -4
- package/src/mcp-servers-prompt.ts +3 -8
- package/src/register-commands.ts +11 -2
- package/src/register-tools.ts +6 -4
- package/src/tool-bridge.ts +444 -14
- package/src/tool-names.ts +68 -21
- package/src/tool-reconcile.ts +261 -1
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@
|
|
|
25
25
|
- **Smart reconnection** — Fixed delay retry schedule (1s → 3s → 5s → 10s → 30s), configurable max retries, automatic recovery when a server transport closes or errors unexpectedly, and mid-session HTTP `401` / `403 insufficient_scope` detection that invalidates stale tokens and prompts for re-authorization
|
|
26
26
|
- **Health checks** — Opt-in periodic pings to detect stale connections
|
|
27
27
|
- **Safe process lifecycle** — Child PID tracking with tree-aware cleanup: descendants of wrapper commands (`npx`, `npm exec`, `uvx`, `sh -c`) are terminated too, and inherited pipes are released so teardown never stalls
|
|
28
|
-
- **Stable tool names** — Sanitized, collision-avoiding names (`<prefix>_<server>_<tool>`, max 64 chars) that stay constant across reconnects
|
|
28
|
+
- **Stable tool names** — Sanitized, collision-avoiding names (`<prefix>_<server>_<tool>`, max 64 chars) that stay constant across reconnects and connection orders: within a server, the raw name needing no substitution keeps the unhashed form (`my_tool` wins over `my-tool`) and ties break by raw-name order; across configured peers with the same sanitized stem (`my_srv` vs `my-srv`), the lossless/code-point winner keeps the unhashed form while losing peers hash; cross-server `_` boundary collisions (`a`/`b_c` vs `a_b`/`c`) symmetrically settle both tools onto deterministic hashed identifiers without stealing names across `tools/list_changed` refreshes; and built-in management/resource tools and peer-extension tools are never overwritten or disabled
|
|
29
29
|
- **Stable tool order** — Active MCP tools keep one deterministic order across session starts, `/tree` navigation, and idle or mid-turn `setActiveTools` updates (including `tool_search`): each active owned tool is sorted by Pi name among the slots it occupies, inactive tools stay off, and other extensions' tools never move. The same order is applied to outgoing provider tool declarations (top-level `tools`, AWS Bedrock Converse `toolConfig.tools`, Google/Vertex `config.tools[].functionDeclarations`, and `pi-messages` `context.messages[].toolsAdded`), which Pi otherwise rebuilds from the transcript's first-appearance order, so the system prompt's tool section and the tools this extension declares stay identical across session starts whatever order the eager servers connected in or the servers list their tools in — keeping a server-side prefix cache warm. A server that connects after an earlier turn is announced on that later turn through the provider's mid-conversation tool-addition channel, which cannot move back into earlier turns
|
|
30
30
|
- **No tool churn** — Activate/deactivate pattern ensures tools don't flicker during reconnection
|
|
31
31
|
- **Tool exposure control** — Honor Pi 1.3.0's `exposure` / `toolExposure`: declare only the handful of tools a task needs `direct`, leave the rest to Pi's `tool_search` and codemode on-demand loading, or hide them entirely — so a 30–80-tool server (GitHub, Supabase, Playwright, Notion) no longer spends 10k–30k tokens of tool declarations per turn or degrades tool selection
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "pi-mcp-extension",
|
|
3
|
-
"version": "1.16.
|
|
3
|
+
"version": "1.16.8",
|
|
4
4
|
"description": "Full-featured, lightweight MCP extension for the Pi coding agent: stdio, SSE & Streamable HTTP transports, OAuth 2.1 (PKCE + DCR), lazy/eager lifecycles — minimal dependencies, zero bloat.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"keywords": [
|
package/src/index.ts
CHANGED
|
@@ -171,6 +171,7 @@ export default async function (
|
|
|
171
171
|
|
|
172
172
|
// ── 3. Session lifecycle ──────────────────────────────────────────────────
|
|
173
173
|
pi.on("session_start", (_event, ctx: ExtensionContext) => {
|
|
174
|
+
bridge.clearPreTreeSnapshot();
|
|
174
175
|
seenDiscoveryWarnings.clear();
|
|
175
176
|
return lifecycle.handleSessionStart(ctx);
|
|
176
177
|
});
|
|
@@ -186,11 +187,15 @@ export default async function (
|
|
|
186
187
|
const normalizeActiveTools = (): void => {
|
|
187
188
|
bridge.orderActiveTools();
|
|
188
189
|
};
|
|
190
|
+
pi.on("session_before_tree", () => {
|
|
191
|
+
bridge.snapshotPreTreeActiveTools();
|
|
192
|
+
});
|
|
189
193
|
pi.on("session_tree", () => {
|
|
190
194
|
restoreSessionTreeTools(manager, bridge);
|
|
191
195
|
});
|
|
192
196
|
pi.on("input", normalizeActiveTools);
|
|
193
197
|
pi.on("before_agent_start", (event) => {
|
|
198
|
+
bridge.clearPreTreeSnapshot();
|
|
194
199
|
bridge.orderActiveTools();
|
|
195
200
|
// WHY: read `pi.getActiveTools()` rather than `event.systemPromptOptions?.selectedTools` — an
|
|
196
201
|
// earlier `before_agent_start` handler may have called `pi.setActiveTools(...)`, which Pi only
|
|
@@ -201,9 +206,14 @@ export default async function (
|
|
|
201
206
|
pi.on("before_provider_request", (event) => bridge.orderPayloadTools(event.payload));
|
|
202
207
|
|
|
203
208
|
pi.on("session_shutdown", async (event, ctx: ExtensionContext) => {
|
|
204
|
-
|
|
209
|
+
const isReload = event?.reason === "reload";
|
|
210
|
+
bridge.clearPreTreeSnapshot();
|
|
211
|
+
bridge.setReloadShutdown(isReload);
|
|
205
212
|
try {
|
|
206
213
|
await lifecycle.handleSessionShutdown(ctx);
|
|
214
|
+
if (!isReload) {
|
|
215
|
+
bridge.resetSessionState();
|
|
216
|
+
}
|
|
207
217
|
} finally {
|
|
208
218
|
bridge.setReloadShutdown(false);
|
|
209
219
|
}
|
|
@@ -233,9 +243,10 @@ export default async function (
|
|
|
233
243
|
|
|
234
244
|
function restoreSessionTreeTools(manager: ServerManager, bridge: ToolBridge): void {
|
|
235
245
|
// WHY: `/tree` runs `AgentSession._restoreToolsFromTranscript()`, which resets `activeTools` to
|
|
236
|
-
// the target turn's declared loadout.
|
|
237
|
-
//
|
|
238
|
-
//
|
|
246
|
+
// the target turn's declared loadout. Record which `direct` tools `/tree` stripped before
|
|
247
|
+
// re-ensuring reaching discovery tools so `mcp_connect` / `/mcp:start` can restore only those
|
|
248
|
+
// tools later without overriding another extension's restrictions (#257, #278, #333).
|
|
249
|
+
bridge.recordTreeDeactivations();
|
|
239
250
|
bridge.ensureDiscoveryTools(
|
|
240
251
|
collectRequiredDiscoveryExposures(
|
|
241
252
|
manager.getAllServers().map((server) => server.config),
|
|
@@ -17,6 +17,7 @@ import {
|
|
|
17
17
|
type McpExposure,
|
|
18
18
|
type RegisteredToolSummary,
|
|
19
19
|
} from "./tool-exposure.js";
|
|
20
|
+
import { MANAGEMENT_TOOL_NAMES } from "./tool-names.js";
|
|
20
21
|
import {
|
|
21
22
|
resolveAllServerNamespaceIds,
|
|
22
23
|
sanitizeNamespaceText,
|
|
@@ -35,12 +36,6 @@ const MAX_SERVER_SUMMARY_CHARS = 250;
|
|
|
35
36
|
/** Bound for sanitized raw server names rendered inside `mcp_connect "<name>"` hints. */
|
|
36
37
|
const MAX_SAFE_SERVER_NAME_CHARS = 120;
|
|
37
38
|
|
|
38
|
-
/** Management tool name required to connect lazy/stopped servers from the prompt. */
|
|
39
|
-
const MCP_CONNECT_TOOL_NAME = "mcp_connect";
|
|
40
|
-
|
|
41
|
-
/** Management tool name that reports every configured server name verbatim. */
|
|
42
|
-
const MCP_STATUS_TOOL_NAME = "mcp_status";
|
|
43
|
-
|
|
44
39
|
export type IndirectReachMode = "codemode" | "tool_search";
|
|
45
40
|
|
|
46
41
|
export interface McpPromptServerEntry {
|
|
@@ -90,8 +85,8 @@ function resolveReachAvailability(
|
|
|
90
85
|
return {
|
|
91
86
|
codemode: isReachingAvailable(active, allTools, CODEMODE_TOOL_NAME),
|
|
92
87
|
toolSearch: isReachingAvailable(active, allTools, TOOL_SEARCH_TOOL_NAME),
|
|
93
|
-
mcpConnect: active ? active.has(
|
|
94
|
-
mcpStatus: active ? active.has(
|
|
88
|
+
mcpConnect: active ? active.has(MANAGEMENT_TOOL_NAMES.connect) : true,
|
|
89
|
+
mcpStatus: active ? active.has(MANAGEMENT_TOOL_NAMES.status) : true,
|
|
95
90
|
};
|
|
96
91
|
}
|
|
97
92
|
|
package/src/register-commands.ts
CHANGED
|
@@ -93,7 +93,7 @@ async function handleMcpStart(
|
|
|
93
93
|
ctx: ExtensionCommandContext,
|
|
94
94
|
deps: RegisterCommandsDeps,
|
|
95
95
|
): Promise<void> {
|
|
96
|
-
const { manager, coordinator } = deps;
|
|
96
|
+
const { manager, coordinator, bridge } = deps;
|
|
97
97
|
const serverName = args.trim();
|
|
98
98
|
if (!serverName) {
|
|
99
99
|
ctx.ui.notify("Usage: /mcp:start <server-name>", "error");
|
|
@@ -106,7 +106,16 @@ async function handleMcpStart(
|
|
|
106
106
|
}
|
|
107
107
|
try {
|
|
108
108
|
await coordinator.connect(serverName, ctx);
|
|
109
|
-
|
|
109
|
+
bridge.restoreTreeDeactivatedDirectTools(serverName);
|
|
110
|
+
const inactiveDirect = bridge.getInactiveDirectTools(serverName);
|
|
111
|
+
if (inactiveDirect.length > 0) {
|
|
112
|
+
ctx.ui.notify(
|
|
113
|
+
`pi-mcp: Started ${serverName}, but ${inactiveDirect.length} direct tool(s) remain inactive — run /mcp ${serverName} for details`,
|
|
114
|
+
"warning",
|
|
115
|
+
);
|
|
116
|
+
} else {
|
|
117
|
+
ctx.ui.notify(`pi-mcp: Started ${serverName}`, "info");
|
|
118
|
+
}
|
|
110
119
|
} catch (err) {
|
|
111
120
|
if (err instanceof AuthCancelledError) {
|
|
112
121
|
const message =
|
package/src/register-tools.ts
CHANGED
|
@@ -22,6 +22,7 @@ import {
|
|
|
22
22
|
type ServerStatusRow,
|
|
23
23
|
} from "./server-status.js";
|
|
24
24
|
import type { ToolActivity, ToolBridge } from "./tool-bridge.js";
|
|
25
|
+
import { MANAGEMENT_TOOL_NAMES } from "./tool-names.js";
|
|
25
26
|
|
|
26
27
|
export interface ManagementToolDeps {
|
|
27
28
|
manager: ServerManager;
|
|
@@ -114,7 +115,7 @@ export function registerManagementTools(
|
|
|
114
115
|
// when `codemode.mode` is `"only"`, and excludes them from `codemode`'s pre-snapshotted QuickJS
|
|
115
116
|
// `tools.*` helpers (`mcp_list_resources` / `mcp_read_resource` stay `"direct"` for scripts) (#257).
|
|
116
117
|
pi.registerTool({
|
|
117
|
-
name:
|
|
118
|
+
name: MANAGEMENT_TOOL_NAMES.status,
|
|
118
119
|
label: "MCP status",
|
|
119
120
|
description: "List configured MCP servers, lifecycle, connection and OAuth state. Use mcp_connect to connect one server.",
|
|
120
121
|
promptSnippet: "Inspect configured MCP servers, their connection state, discovered tools, and authentication status.",
|
|
@@ -130,7 +131,7 @@ export function registerManagementTools(
|
|
|
130
131
|
});
|
|
131
132
|
|
|
132
133
|
pi.registerTool({
|
|
133
|
-
name:
|
|
134
|
+
name: MANAGEMENT_TOOL_NAMES.connect,
|
|
134
135
|
label: "Connect MCP server",
|
|
135
136
|
description: "Connect one named configured MCP server and activate its tools. May request interactive OAuth authorization.",
|
|
136
137
|
promptSnippet: "Connect or reconnect to a configured MCP server by name and register its tools.",
|
|
@@ -147,6 +148,7 @@ export function registerManagementTools(
|
|
|
147
148
|
});
|
|
148
149
|
throw new Error(message);
|
|
149
150
|
}
|
|
151
|
+
bridge.restoreTreeDeactivatedDirectTools(name);
|
|
150
152
|
// WHY: check the tools whose exposure is `direct` by name, not every discovered one. A
|
|
151
153
|
// server configured with `exposure: "hidden"` plus a few `toolExposure` overrides, or one
|
|
152
154
|
// whose tools are all deferred to `tool_search`, is working as configured — the old
|
|
@@ -170,7 +172,7 @@ export function registerManagementTools(
|
|
|
170
172
|
});
|
|
171
173
|
|
|
172
174
|
pi.registerTool({
|
|
173
|
-
name:
|
|
175
|
+
name: MANAGEMENT_TOOL_NAMES.listResources,
|
|
174
176
|
label: "List MCP resources",
|
|
175
177
|
description: "List MCP resources and URI templates exposed by connected servers. Use mcp_read_resource to read one by URI.",
|
|
176
178
|
promptSnippet: "Discover read-only MCP resources (documents, schemas, data streams) and URI templates, optionally for one server.",
|
|
@@ -185,7 +187,7 @@ export function registerManagementTools(
|
|
|
185
187
|
});
|
|
186
188
|
|
|
187
189
|
pi.registerTool({
|
|
188
|
-
name:
|
|
190
|
+
name: MANAGEMENT_TOOL_NAMES.readResource,
|
|
189
191
|
label: "Read MCP resource",
|
|
190
192
|
description:
|
|
191
193
|
"Read one MCP resource by server and URI. Text resources return their text; valid image/svg+xml blobs decode to UTF-8 text; supported image blobs return an image; other or invalid binary blobs return a summary.",
|
package/src/tool-bridge.ts
CHANGED
|
@@ -36,18 +36,32 @@ import {
|
|
|
36
36
|
collectReboundToolDefinitions,
|
|
37
37
|
mergePeerServerNames,
|
|
38
38
|
} from "./tool-namespace.js";
|
|
39
|
+
import {
|
|
40
|
+
buildToolName,
|
|
41
|
+
RESERVED_MANAGEMENT_TOOL_NAMES,
|
|
42
|
+
resolveUniqueToolName,
|
|
43
|
+
} from "./tool-names.js";
|
|
39
44
|
import { orderOwnedEntries, orderPayloadToolEntries, sameToolList } from "./tool-order.js";
|
|
40
45
|
import {
|
|
46
|
+
collectAddedExposures,
|
|
47
|
+
collectReservedToolNames,
|
|
41
48
|
deleteServerOwnedTools,
|
|
42
49
|
filterOwnedTools,
|
|
50
|
+
forgetServerCollisionState,
|
|
43
51
|
mergePendingRestoredTools,
|
|
44
52
|
mergeRawToolExposures,
|
|
45
53
|
normalizeRefreshArgs,
|
|
46
54
|
orderOwnedActiveTools,
|
|
47
55
|
planActiveToolReconciliation,
|
|
48
56
|
planServerToolBatch,
|
|
57
|
+
planTreeDirectToolRestore,
|
|
58
|
+
pruneTreeDeactivatedDirectTools,
|
|
49
59
|
reconcileLiveRefreshState,
|
|
60
|
+
recordBaseNameCandidate,
|
|
61
|
+
recordCrossServerCollision,
|
|
50
62
|
snapshotActiveStateByRawName,
|
|
63
|
+
updateTreeDeactivatedDirectTools,
|
|
64
|
+
type ServerToolBatchPlan,
|
|
51
65
|
} from "./tool-reconcile.js";
|
|
52
66
|
|
|
53
67
|
export { buildToolName } from "./tool-names.js";
|
|
@@ -98,6 +112,34 @@ interface RegisterToolParams {
|
|
|
98
112
|
namespace: ToolNamespace;
|
|
99
113
|
}
|
|
100
114
|
|
|
115
|
+
interface DisplacementResult {
|
|
116
|
+
oldNames: Set<string>;
|
|
117
|
+
desiredActive: Set<string>;
|
|
118
|
+
cliFilteredDirectNames: Set<string>;
|
|
119
|
+
piExposures: Map<string, McpExposure>;
|
|
120
|
+
affectedIncumbents: Set<string>;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
interface DisplaceIncumbentContext {
|
|
124
|
+
baseName: string;
|
|
125
|
+
incumbentServer: string;
|
|
126
|
+
batchToolNames: ReadonlySet<string>;
|
|
127
|
+
collidedBaseNames: ReadonlySet<string>;
|
|
128
|
+
reservedNames: ReadonlySet<string>;
|
|
129
|
+
activeBeforeSet: ReadonlySet<string>;
|
|
130
|
+
allToolsBeforeNames: ReadonlySet<string> | undefined;
|
|
131
|
+
displacement: DisplacementResult;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
interface DisplaceCollisionsOptions {
|
|
135
|
+
incomingServer: string;
|
|
136
|
+
batch: ServerToolBatchPlan;
|
|
137
|
+
collidedBaseNames: Set<string>;
|
|
138
|
+
reservedNames: ReadonlySet<string>;
|
|
139
|
+
activeBeforeSet: ReadonlySet<string>;
|
|
140
|
+
allToolsBeforeNames: ReadonlySet<string> | undefined;
|
|
141
|
+
}
|
|
142
|
+
|
|
101
143
|
// ─── Tool Bridge ──────────────────────────────────────────────────────────────
|
|
102
144
|
|
|
103
145
|
/**
|
|
@@ -150,6 +192,23 @@ export class ToolBridge {
|
|
|
150
192
|
private readonly refreshGenerations = new Map<string, number>();
|
|
151
193
|
/** Per-server request timeout overrides resolved during refreshTools. */
|
|
152
194
|
private readonly serverTimeouts = new Map<string, number>();
|
|
195
|
+
/**
|
|
196
|
+
* Every Pi tool name ever registered by this bridge, so retired `hidden` placeholders in
|
|
197
|
+
* `pi.getAllTools()` are never misclassified as foreign tools (#332).
|
|
198
|
+
*/
|
|
199
|
+
private readonly bridgeRegisteredNames = new Set<string>();
|
|
200
|
+
/** Live registration inputs by Pi tool name so displaced cross-server incumbents can be rebound (#331). */
|
|
201
|
+
private readonly liveToolBindings = new Map<string, Omit<RegisterToolParams, "piName">>();
|
|
202
|
+
/** Unhashed `<prefix>_<server>_<tool>` ownership kept across transient withdrawals/stops (#331). */
|
|
203
|
+
private readonly baseNameOwners = new Map<string, string>();
|
|
204
|
+
/** Unhashed Pi base names -> servers advertising tools targeting that base name (#331). */
|
|
205
|
+
private readonly baseNameCandidates = new Map<string, Set<string>>();
|
|
206
|
+
/** Colliding unhashed Pi tool names -> competing server names (pruned when `< 2` remain) (#331). */
|
|
207
|
+
private readonly collidedBaseServers = new Map<string, Set<string>>();
|
|
208
|
+
/** Snapshot of `pi.getActiveTools()` taken on `session_before_tree` and consumed on `session_tree` (#333). */
|
|
209
|
+
private preTreeActiveSnapshot: Set<string> | undefined;
|
|
210
|
+
/** Per server, raw MCP tool names of `direct` tools deactivated by `/tree` for one-shot restore (#333). */
|
|
211
|
+
private readonly treeDeactivatedDirectTools = new Map<string, Set<string>>();
|
|
153
212
|
private onAuthError?: ToolAuthErrorHandler | undefined;
|
|
154
213
|
private onDiscoveryWarning?: ((message: string) => void) | undefined;
|
|
155
214
|
|
|
@@ -214,7 +273,13 @@ export class ToolBridge {
|
|
|
214
273
|
/** Update bridge settings when session config is reloaded on session_start. */
|
|
215
274
|
updateSettings(settings: Settings): void {
|
|
216
275
|
const prevDefaultTimeoutMs = this.settings.requestTimeoutMs;
|
|
276
|
+
const prefixChanged = settings.toolPrefix !== this.settings.toolPrefix;
|
|
217
277
|
this.settings = settings;
|
|
278
|
+
if (prefixChanged) {
|
|
279
|
+
this.baseNameOwners.clear();
|
|
280
|
+
this.baseNameCandidates.clear();
|
|
281
|
+
this.collidedBaseServers.clear();
|
|
282
|
+
}
|
|
218
283
|
for (const [serverName, timeoutMs] of this.serverTimeouts.entries()) {
|
|
219
284
|
if (timeoutMs === prevDefaultTimeoutMs) {
|
|
220
285
|
this.serverTimeouts.delete(serverName);
|
|
@@ -302,6 +367,63 @@ export class ToolBridge {
|
|
|
302
367
|
return [...direct].filter((name) => !active.has(name));
|
|
303
368
|
}
|
|
304
369
|
|
|
370
|
+
/** Capture active tools immediately before `/tree` restores transcript tools (#333). */
|
|
371
|
+
snapshotPreTreeActiveTools(): void {
|
|
372
|
+
this.preTreeActiveSnapshot = new Set(this.pi.getActiveTools());
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Discard any pending pre-`/tree` snapshot (e.g. after a cancelled `session_before_tree`) (#333). */
|
|
376
|
+
clearPreTreeSnapshot(): void {
|
|
377
|
+
this.preTreeActiveSnapshot = undefined;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/**
|
|
381
|
+
* Record `direct` tools stripped across `/tree` (accumulating across consecutive `/tree` hops
|
|
382
|
+
* and pruning any tools active again on the target branch) (#333).
|
|
383
|
+
*/
|
|
384
|
+
recordTreeDeactivations(): void {
|
|
385
|
+
const before = this.preTreeActiveSnapshot;
|
|
386
|
+
this.preTreeActiveSnapshot = undefined;
|
|
387
|
+
const current = new Set(this.pi.getActiveTools());
|
|
388
|
+
const servers = new Set([
|
|
389
|
+
...this.directToolNames.keys(),
|
|
390
|
+
...this.treeDeactivatedDirectTools.keys(),
|
|
391
|
+
]);
|
|
392
|
+
for (const serverName of servers) {
|
|
393
|
+
const next = updateTreeDeactivatedDirectTools({
|
|
394
|
+
existing: this.treeDeactivatedDirectTools.get(serverName),
|
|
395
|
+
directTools: this.directToolNames.get(serverName),
|
|
396
|
+
rawToolNames: this.rawToolNames.get(serverName),
|
|
397
|
+
droppedToolState: this.droppedToolState.get(serverName),
|
|
398
|
+
rawToolExposures: this.rawToolExposures.get(serverName),
|
|
399
|
+
beforeActive: before,
|
|
400
|
+
currentActive: current,
|
|
401
|
+
});
|
|
402
|
+
this._setOrDeleteMapEntry(this.treeDeactivatedDirectTools, serverName, next);
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
|
|
406
|
+
/**
|
|
407
|
+
* One-shot restoration of `direct` tools previously deactivated by `/tree` for `serverName`,
|
|
408
|
+
* called by `mcp_connect` and `/mcp:start` without overriding extension restrictions (#333).
|
|
409
|
+
*/
|
|
410
|
+
restoreTreeDeactivatedDirectTools(serverName: string): void {
|
|
411
|
+
const pending = this.treeDeactivatedDirectTools.get(serverName);
|
|
412
|
+
this.treeDeactivatedDirectTools.delete(serverName);
|
|
413
|
+
if (!this.activeServers.has(serverName)) return;
|
|
414
|
+
const activeBefore = this.pi.getActiveTools();
|
|
415
|
+
const nextActive = planTreeDirectToolRestore({
|
|
416
|
+
pendingRawNames: pending,
|
|
417
|
+
directTools: this.directToolNames.get(serverName),
|
|
418
|
+
rawToolNames: this.rawToolNames.get(serverName),
|
|
419
|
+
activeBefore,
|
|
420
|
+
isOwned: (name) => this.toolOwners.has(name),
|
|
421
|
+
});
|
|
422
|
+
if (nextActive !== undefined) {
|
|
423
|
+
this.pi.setActiveTools(nextActive);
|
|
424
|
+
}
|
|
425
|
+
}
|
|
426
|
+
|
|
305
427
|
/**
|
|
306
428
|
* Re-apply this bridge's deterministic tool order to Pi's active list when owned tools have
|
|
307
429
|
* been reordered externally, and do nothing when already ordered.
|
|
@@ -314,6 +436,7 @@ export class ToolBridge {
|
|
|
314
436
|
*/
|
|
315
437
|
orderActiveTools(): void {
|
|
316
438
|
const current = this.pi.getActiveTools();
|
|
439
|
+
this._pruneActiveTreeDeactivations(new Set(current));
|
|
317
440
|
const ordered = orderOwnedEntries(
|
|
318
441
|
current,
|
|
319
442
|
(name) => name,
|
|
@@ -349,6 +472,8 @@ export class ToolBridge {
|
|
|
349
472
|
this.activeServers.delete(serverName);
|
|
350
473
|
this.activeServerExposures.delete(serverName);
|
|
351
474
|
this.indirectFilteredServers.delete(serverName);
|
|
475
|
+
this.treeDeactivatedDirectTools.delete(serverName);
|
|
476
|
+
this._deleteServerLiveBindings(serverName);
|
|
352
477
|
// WHY: stopping the server turns every tool off, so what each one "left in" belongs to a
|
|
353
478
|
// connection that no longer exists; a fresh connect rediscovers the state from scratch.
|
|
354
479
|
this.droppedToolState.delete(serverName);
|
|
@@ -385,6 +510,14 @@ export class ToolBridge {
|
|
|
385
510
|
this.activeServers.delete(serverName);
|
|
386
511
|
this.activeServerExposures.delete(serverName);
|
|
387
512
|
this.indirectFilteredServers.delete(serverName);
|
|
513
|
+
this.treeDeactivatedDirectTools.delete(serverName);
|
|
514
|
+
this._deleteServerLiveBindings(serverName);
|
|
515
|
+
forgetServerCollisionState(
|
|
516
|
+
serverName,
|
|
517
|
+
this.baseNameOwners,
|
|
518
|
+
this.collidedBaseServers,
|
|
519
|
+
this.baseNameCandidates,
|
|
520
|
+
);
|
|
388
521
|
this.droppedToolState.delete(serverName);
|
|
389
522
|
this.rawToolNames.delete(serverName);
|
|
390
523
|
this.rawToolExposures.delete(serverName);
|
|
@@ -395,6 +528,31 @@ export class ToolBridge {
|
|
|
395
528
|
deleteServerOwnedTools(serverName, this.serverToolNames, this.toolOwners);
|
|
396
529
|
}
|
|
397
530
|
|
|
531
|
+
/**
|
|
532
|
+
* Clear all session-scoped ownership, activity, exposure, collision, and `/tree` state after
|
|
533
|
+
* a non-reload `session_shutdown` teardown so a subsequent `new_session` starts identically
|
|
534
|
+
* to a fresh process while keeping `bridgeRegisteredNames` intact for retired Pi placeholders.
|
|
535
|
+
*/
|
|
536
|
+
resetSessionState(): void {
|
|
537
|
+
this.preTreeActiveSnapshot = undefined;
|
|
538
|
+
this.treeDeactivatedDirectTools.clear();
|
|
539
|
+
this.baseNameOwners.clear();
|
|
540
|
+
this.baseNameCandidates.clear();
|
|
541
|
+
this.collidedBaseServers.clear();
|
|
542
|
+
this.toolOwners.clear();
|
|
543
|
+
this.serverToolNames.clear();
|
|
544
|
+
this.directToolNames.clear();
|
|
545
|
+
this.registeredDefinitions.clear();
|
|
546
|
+
this.activeServers.clear();
|
|
547
|
+
this.liveToolBindings.clear();
|
|
548
|
+
this.droppedToolState.clear();
|
|
549
|
+
this.rawToolNames.clear();
|
|
550
|
+
this.rawToolExposures.clear();
|
|
551
|
+
this.activeServerExposures.clear();
|
|
552
|
+
this.indirectFilteredServers.clear();
|
|
553
|
+
this.serverTimeouts.clear();
|
|
554
|
+
}
|
|
555
|
+
|
|
398
556
|
/**
|
|
399
557
|
* Re-sync `ToolDefinition.namespace` on active servers when `mcp_servers_change` adds or
|
|
400
558
|
* removes a peer whose sanitized name collides (`my-srv` vs `my_srv`), without network I/O.
|
|
@@ -482,6 +640,16 @@ export class ToolBridge {
|
|
|
482
640
|
peerServerNames,
|
|
483
641
|
});
|
|
484
642
|
|
|
643
|
+
const allToolsBefore = this.pi.getAllTools?.();
|
|
644
|
+
const allToolsBeforeNames = allToolsBefore
|
|
645
|
+
? new Set(allToolsBefore.map((tool) => tool.name))
|
|
646
|
+
: undefined;
|
|
647
|
+
const reservedNames = collectReservedToolNames(
|
|
648
|
+
RESERVED_MANAGEMENT_TOOL_NAMES,
|
|
649
|
+
allToolsBefore,
|
|
650
|
+
this.bridgeRegisteredNames,
|
|
651
|
+
);
|
|
652
|
+
const collidedBaseNames = new Set(this.collidedBaseServers.keys());
|
|
485
653
|
const batch = planServerToolBatch({
|
|
486
654
|
prefix: this.settings.toolPrefix,
|
|
487
655
|
serverName,
|
|
@@ -489,6 +657,18 @@ export class ToolBridge {
|
|
|
489
657
|
toolOwners: this.toolOwners,
|
|
490
658
|
ownedPreviousNames,
|
|
491
659
|
exposureConfig: options,
|
|
660
|
+
peerServerNames,
|
|
661
|
+
collidedBaseNames,
|
|
662
|
+
baseNameOwners: this.baseNameOwners,
|
|
663
|
+
reservedNames,
|
|
664
|
+
});
|
|
665
|
+
const displacement = this._displaceCrossServerCollisions({
|
|
666
|
+
incomingServer: serverName,
|
|
667
|
+
batch,
|
|
668
|
+
collidedBaseNames,
|
|
669
|
+
reservedNames,
|
|
670
|
+
activeBeforeSet: new Set(activeBefore),
|
|
671
|
+
allToolsBeforeNames,
|
|
492
672
|
});
|
|
493
673
|
for (const { piName, tool, exposure } of batch.plannedTools) {
|
|
494
674
|
this.toolOwners.set(piName, serverName);
|
|
@@ -496,11 +676,17 @@ export class ToolBridge {
|
|
|
496
676
|
// Pi's registerTool overwrites by name, so this is idempotent.
|
|
497
677
|
this._registerTool({ piName, serverName, tool, client, exposure, namespace });
|
|
498
678
|
}
|
|
679
|
+
this._recordBaseNameOwners(serverName, batch, collidedBaseNames, reservedNames);
|
|
499
680
|
const activeAfterRegistration = [...this.pi.getActiveTools()];
|
|
500
681
|
this._releaseWithdrawnTools(batch.withdrawnToolNames);
|
|
501
682
|
|
|
502
683
|
const allTools = this.pi.getAllTools?.();
|
|
684
|
+
this._promoteAllowedDisplacedDirect(displacement, allTools);
|
|
503
685
|
const serverExposures = this._assessServerExposures(serverName, batch.piExposures, allTools);
|
|
686
|
+
const incumbentExposures = this._reassessAffectedIncumbents(
|
|
687
|
+
displacement.affectedIncumbents,
|
|
688
|
+
allTools,
|
|
689
|
+
);
|
|
504
690
|
|
|
505
691
|
// WHY: `pi.setActiveTools` is shared with every other extension and the user, so an already
|
|
506
692
|
// connected server's tool set may have been narrowed on purpose. A live `tools/list_changed`
|
|
@@ -516,29 +702,41 @@ export class ToolBridge {
|
|
|
516
702
|
previousStateByRawName,
|
|
517
703
|
)
|
|
518
704
|
: batch.directToolNames;
|
|
705
|
+
const mergedPiExposures = new Map([...batch.piExposures, ...displacement.piExposures]);
|
|
519
706
|
const desiredActive = mergePendingRestoredTools({
|
|
520
|
-
desiredActive: baseDesiredActive,
|
|
521
|
-
piExposures:
|
|
707
|
+
desiredActive: new Set([...baseDesiredActive, ...displacement.desiredActive]),
|
|
708
|
+
piExposures: mergedPiExposures,
|
|
522
709
|
activeBefore,
|
|
523
710
|
activeAfterRegistration,
|
|
524
711
|
allTools,
|
|
525
712
|
});
|
|
526
|
-
|
|
527
|
-
|
|
713
|
+
for (const oldName of displacement.oldNames) {
|
|
714
|
+
ownedPreviousNames.add(oldName);
|
|
715
|
+
}
|
|
716
|
+
const mergedRawExposures = mergeRawToolExposures(
|
|
717
|
+
this.rawToolExposures.get(serverName),
|
|
718
|
+
batch.currentExposures,
|
|
719
|
+
this.droppedToolState.get(serverName),
|
|
720
|
+
);
|
|
721
|
+
this._syncTreeDeactivationsOnReconcile(
|
|
528
722
|
serverName,
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
),
|
|
723
|
+
previousStateByRawName !== undefined,
|
|
724
|
+
batch,
|
|
725
|
+
mergedRawExposures,
|
|
726
|
+
desiredActive,
|
|
534
727
|
);
|
|
728
|
+
|
|
729
|
+
this.rawToolExposures.set(serverName, mergedRawExposures);
|
|
535
730
|
this.serverToolNames.set(serverName, batch.currentToolNames);
|
|
536
731
|
this.rawToolNames.set(serverName, batch.currentRawNames);
|
|
537
732
|
this.directToolNames.set(serverName, batch.directToolNames);
|
|
538
733
|
this.activeServerExposures.set(serverName, serverExposures);
|
|
539
734
|
this.activeServers.add(serverName);
|
|
540
735
|
this._rebindActiveNamespaces(peerServerNames);
|
|
541
|
-
const discoveryToActivate = this._resolveDiscoveryTools(
|
|
736
|
+
const discoveryToActivate = this._resolveDiscoveryTools(
|
|
737
|
+
new Set([...serverExposures, ...incumbentExposures]),
|
|
738
|
+
activeBefore,
|
|
739
|
+
);
|
|
542
740
|
this._reconcileActiveTools(ownedPreviousNames, desiredActive, activeBefore, discoveryToActivate);
|
|
543
741
|
}
|
|
544
742
|
|
|
@@ -577,12 +775,241 @@ export class ToolBridge {
|
|
|
577
775
|
previousExposures: this.rawToolExposures.get(serverName),
|
|
578
776
|
previousDropped: this.droppedToolState.get(serverName),
|
|
579
777
|
});
|
|
580
|
-
|
|
581
|
-
|
|
778
|
+
this._setOrDeleteMapEntry(this.droppedToolState, serverName, dropped);
|
|
779
|
+
return desiredActive;
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
private _setOrDeleteMapEntry<V>(map: Map<string, V>, key: string, value: V | undefined): void {
|
|
783
|
+
if (value !== undefined) {
|
|
784
|
+
map.set(key, value);
|
|
582
785
|
} else {
|
|
583
|
-
|
|
786
|
+
map.delete(key);
|
|
584
787
|
}
|
|
585
|
-
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
private _pruneActiveTreeDeactivations(nowActive: ReadonlySet<string>): void {
|
|
791
|
+
for (const [serverName, pending] of this.treeDeactivatedDirectTools) {
|
|
792
|
+
const next = pruneTreeDeactivatedDirectTools({
|
|
793
|
+
existing: pending,
|
|
794
|
+
directTools: this.directToolNames.get(serverName),
|
|
795
|
+
rawToolNames: this.rawToolNames.get(serverName),
|
|
796
|
+
droppedToolState: this.droppedToolState.get(serverName),
|
|
797
|
+
rawToolExposures: this.rawToolExposures.get(serverName),
|
|
798
|
+
nowActive,
|
|
799
|
+
});
|
|
800
|
+
this._setOrDeleteMapEntry(this.treeDeactivatedDirectTools, serverName, next);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
private _syncTreeDeactivationsOnReconcile(
|
|
805
|
+
serverName: string,
|
|
806
|
+
isLiveRefresh: boolean,
|
|
807
|
+
batch: ServerToolBatchPlan,
|
|
808
|
+
mergedRawExposures: ReadonlyMap<string, McpExposure>,
|
|
809
|
+
desiredActive: ReadonlySet<string>,
|
|
810
|
+
): void {
|
|
811
|
+
if (!isLiveRefresh) {
|
|
812
|
+
this.treeDeactivatedDirectTools.delete(serverName);
|
|
813
|
+
return;
|
|
814
|
+
}
|
|
815
|
+
const remaining = pruneTreeDeactivatedDirectTools({
|
|
816
|
+
existing: this.treeDeactivatedDirectTools.get(serverName),
|
|
817
|
+
directTools: batch.directToolNames,
|
|
818
|
+
rawToolNames: batch.currentRawNames,
|
|
819
|
+
droppedToolState: this.droppedToolState.get(serverName),
|
|
820
|
+
rawToolExposures: mergedRawExposures,
|
|
821
|
+
nowActive: desiredActive,
|
|
822
|
+
});
|
|
823
|
+
this._setOrDeleteMapEntry(this.treeDeactivatedDirectTools, serverName, remaining);
|
|
824
|
+
}
|
|
825
|
+
|
|
826
|
+
private _deleteServerLiveBindings(serverName: string): void {
|
|
827
|
+
for (const [piName, binding] of this.liveToolBindings) {
|
|
828
|
+
if (binding.serverName === serverName) {
|
|
829
|
+
this.liveToolBindings.delete(piName);
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
private _clearStoppedIncumbentClaim(baseName: string, incumbentServer: string): void {
|
|
835
|
+
this._hideTool(baseName, true);
|
|
836
|
+
this.toolOwners.delete(baseName);
|
|
837
|
+
this.liveToolBindings.delete(baseName);
|
|
838
|
+
this.serverToolNames.get(incumbentServer)?.delete(baseName);
|
|
839
|
+
this.directToolNames.get(incumbentServer)?.delete(baseName);
|
|
840
|
+
this.rawToolNames.get(incumbentServer)?.delete(baseName);
|
|
841
|
+
}
|
|
842
|
+
|
|
843
|
+
private _renameIncumbentTracking(
|
|
844
|
+
serverName: string,
|
|
845
|
+
oldPiName: string,
|
|
846
|
+
newPiName: string,
|
|
847
|
+
rawToolName: string,
|
|
848
|
+
): void {
|
|
849
|
+
const serverTools = this.serverToolNames.get(serverName);
|
|
850
|
+
serverTools?.delete(oldPiName);
|
|
851
|
+
serverTools?.add(newPiName);
|
|
852
|
+
const rawNames = this.rawToolNames.get(serverName);
|
|
853
|
+
rawNames?.delete(oldPiName);
|
|
854
|
+
rawNames?.set(newPiName, rawToolName);
|
|
855
|
+
for (const set of [this.directToolNames.get(serverName), this.preTreeActiveSnapshot]) {
|
|
856
|
+
if (set?.has(oldPiName)) {
|
|
857
|
+
set.delete(oldPiName);
|
|
858
|
+
set.add(newPiName);
|
|
859
|
+
}
|
|
860
|
+
}
|
|
861
|
+
}
|
|
862
|
+
|
|
863
|
+
private _displaceLiveIncumbent(ctx: DisplaceIncumbentContext): void {
|
|
864
|
+
const {
|
|
865
|
+
baseName,
|
|
866
|
+
incumbentServer,
|
|
867
|
+
batchToolNames,
|
|
868
|
+
collidedBaseNames,
|
|
869
|
+
reservedNames,
|
|
870
|
+
activeBeforeSet,
|
|
871
|
+
allToolsBeforeNames,
|
|
872
|
+
displacement,
|
|
873
|
+
} = ctx;
|
|
874
|
+
const binding = this.liveToolBindings.get(baseName);
|
|
875
|
+
if (!binding) return;
|
|
876
|
+
const newPiName = resolveUniqueToolName({
|
|
877
|
+
prefix: this.settings.toolPrefix,
|
|
878
|
+
serverName: incumbentServer,
|
|
879
|
+
rawToolName: binding.tool.name,
|
|
880
|
+
seenInBatch: batchToolNames,
|
|
881
|
+
toolOwners: this.toolOwners,
|
|
882
|
+
forceHash: true,
|
|
883
|
+
collidedBaseNames,
|
|
884
|
+
reservedNames,
|
|
885
|
+
});
|
|
886
|
+
const currentNamespace = this.registeredDefinitions.get(baseName)?.namespace ?? binding.namespace;
|
|
887
|
+
this._hideTool(baseName, true);
|
|
888
|
+
this.toolOwners.delete(baseName);
|
|
889
|
+
this.liveToolBindings.delete(baseName);
|
|
890
|
+
this._renameIncumbentTracking(incumbentServer, baseName, newPiName, binding.tool.name);
|
|
891
|
+
this.toolOwners.set(newPiName, incumbentServer);
|
|
892
|
+
this._registerTool({ ...binding, namespace: currentNamespace, piName: newPiName });
|
|
893
|
+
displacement.oldNames.add(baseName);
|
|
894
|
+
if (activeBeforeSet.has(baseName)) {
|
|
895
|
+
displacement.desiredActive.add(newPiName);
|
|
896
|
+
} else if (
|
|
897
|
+
binding.exposure === "direct" &&
|
|
898
|
+
allToolsBeforeNames !== undefined &&
|
|
899
|
+
!allToolsBeforeNames.has(baseName)
|
|
900
|
+
) {
|
|
901
|
+
// WHY: Pi omits CLI-filtered (`--tools` / `--exclude-tools`) tools from `getAllTools()`,
|
|
902
|
+
// whereas extension-deactivated and `/tree`-stripped tools remain registered there. If the
|
|
903
|
+
// unhashed base name was excluded by CLI filters while the deterministic hashed name is
|
|
904
|
+
// allowed, promote it after registration so connect order stays invariant (#331).
|
|
905
|
+
displacement.cliFilteredDirectNames.add(newPiName);
|
|
906
|
+
}
|
|
907
|
+
displacement.piExposures.set(newPiName, binding.exposure);
|
|
908
|
+
displacement.affectedIncumbents.add(incumbentServer);
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
private _promoteAllowedDisplacedDirect(
|
|
912
|
+
displacement: DisplacementResult,
|
|
913
|
+
allTools: readonly RegisteredToolSummary[] | undefined,
|
|
914
|
+
): void {
|
|
915
|
+
if (displacement.cliFilteredDirectNames.size === 0 || !allTools) return;
|
|
916
|
+
const allowedAfter = new Set(allTools.map((tool) => tool.name));
|
|
917
|
+
for (const piName of displacement.cliFilteredDirectNames) {
|
|
918
|
+
if (allowedAfter.has(piName)) {
|
|
919
|
+
displacement.desiredActive.add(piName);
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
|
|
924
|
+
private _displaceCrossServerCollisions(options: DisplaceCollisionsOptions): DisplacementResult {
|
|
925
|
+
const {
|
|
926
|
+
incomingServer,
|
|
927
|
+
batch,
|
|
928
|
+
collidedBaseNames,
|
|
929
|
+
reservedNames,
|
|
930
|
+
activeBeforeSet,
|
|
931
|
+
allToolsBeforeNames,
|
|
932
|
+
} = options;
|
|
933
|
+
const displacement: DisplacementResult = {
|
|
934
|
+
oldNames: new Set(),
|
|
935
|
+
desiredActive: new Set(),
|
|
936
|
+
cliFilteredDirectNames: new Set(),
|
|
937
|
+
piExposures: new Map(),
|
|
938
|
+
affectedIncumbents: new Set(),
|
|
939
|
+
};
|
|
940
|
+
for (const [baseName, incumbentServer] of batch.crossServerCollisions) {
|
|
941
|
+
recordCrossServerCollision(
|
|
942
|
+
baseName,
|
|
943
|
+
incumbentServer,
|
|
944
|
+
incomingServer,
|
|
945
|
+
this.collidedBaseServers,
|
|
946
|
+
this.baseNameCandidates,
|
|
947
|
+
);
|
|
948
|
+
collidedBaseNames.add(baseName);
|
|
949
|
+
this.baseNameOwners.delete(baseName);
|
|
950
|
+
if (this.toolOwners.get(baseName) !== incumbentServer) continue;
|
|
951
|
+
if (this.activeServers.has(incumbentServer)) {
|
|
952
|
+
this._displaceLiveIncumbent({
|
|
953
|
+
baseName,
|
|
954
|
+
incumbentServer,
|
|
955
|
+
batchToolNames: batch.currentToolNames,
|
|
956
|
+
collidedBaseNames,
|
|
957
|
+
reservedNames,
|
|
958
|
+
activeBeforeSet,
|
|
959
|
+
allToolsBeforeNames,
|
|
960
|
+
displacement,
|
|
961
|
+
});
|
|
962
|
+
} else {
|
|
963
|
+
this._clearStoppedIncumbentClaim(baseName, incumbentServer);
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
return displacement;
|
|
967
|
+
}
|
|
968
|
+
|
|
969
|
+
private _recordBaseNameOwners(
|
|
970
|
+
serverName: string,
|
|
971
|
+
batch: ServerToolBatchPlan,
|
|
972
|
+
collidedBaseNames: ReadonlySet<string>,
|
|
973
|
+
reservedNames: ReadonlySet<string>,
|
|
974
|
+
): void {
|
|
975
|
+
const prefix = this.settings.toolPrefix;
|
|
976
|
+
for (const { piName, tool } of batch.plannedTools) {
|
|
977
|
+
const base = buildToolName(prefix, serverName, tool.name, false);
|
|
978
|
+
const hashed = buildToolName(prefix, serverName, tool.name, true);
|
|
979
|
+
if (base === hashed || reservedNames.has(base)) continue;
|
|
980
|
+
recordBaseNameCandidate(this.baseNameCandidates, base, serverName);
|
|
981
|
+
if (collidedBaseNames.has(base)) {
|
|
982
|
+
this.collidedBaseServers.get(base)?.add(serverName);
|
|
983
|
+
} else if (piName === base) {
|
|
984
|
+
this.baseNameOwners.set(base, serverName);
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
private _collectServerPiExposures(serverName: string): Map<string, McpExposure> {
|
|
990
|
+
const exposures = new Map<string, McpExposure>();
|
|
991
|
+
for (const piName of this.serverToolNames.get(serverName) ?? []) {
|
|
992
|
+
const binding = this.liveToolBindings.get(piName);
|
|
993
|
+
if (binding) {
|
|
994
|
+
exposures.set(piName, binding.exposure);
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
return exposures;
|
|
998
|
+
}
|
|
999
|
+
|
|
1000
|
+
private _reassessAffectedIncumbents(
|
|
1001
|
+
affectedIncumbents: ReadonlySet<string>,
|
|
1002
|
+
allTools: readonly RegisteredToolSummary[] | undefined,
|
|
1003
|
+
): Set<McpExposure> {
|
|
1004
|
+
const addedExposures: Set<McpExposure>[] = [];
|
|
1005
|
+
for (const incumbent of affectedIncumbents) {
|
|
1006
|
+
const previous = this.activeServerExposures.get(incumbent);
|
|
1007
|
+
const exposures = this._collectServerPiExposures(incumbent);
|
|
1008
|
+
const assessed = this._assessServerExposures(incumbent, exposures, allTools);
|
|
1009
|
+
this.activeServerExposures.set(incumbent, assessed);
|
|
1010
|
+
addedExposures.push(collectAddedExposures(previous, assessed));
|
|
1011
|
+
}
|
|
1012
|
+
return collectConnectedExposures(addedExposures);
|
|
586
1013
|
}
|
|
587
1014
|
|
|
588
1015
|
private _registerTool(registration: RegisterToolParams): void {
|
|
@@ -600,6 +1027,8 @@ export class ToolBridge {
|
|
|
600
1027
|
// bridge is constructed, and it is the caller for every server, so it takes the name.
|
|
601
1028
|
onAuthError: (srv, err) => this.onAuthError?.(srv, err),
|
|
602
1029
|
});
|
|
1030
|
+
this.bridgeRegisteredNames.add(piName);
|
|
1031
|
+
this.liveToolBindings.set(piName, { serverName, tool, client, exposure, namespace });
|
|
603
1032
|
this.registeredDefinitions.set(piName, definition);
|
|
604
1033
|
this.pi.registerTool(definition);
|
|
605
1034
|
}
|
|
@@ -650,6 +1079,7 @@ export class ToolBridge {
|
|
|
650
1079
|
for (const existingName of withdrawnToolNames) {
|
|
651
1080
|
this._hideTool(existingName, true);
|
|
652
1081
|
this.toolOwners.delete(existingName);
|
|
1082
|
+
this.liveToolBindings.delete(existingName);
|
|
653
1083
|
}
|
|
654
1084
|
}
|
|
655
1085
|
|
package/src/tool-names.ts
CHANGED
|
@@ -9,12 +9,35 @@ import { compareCodePoints } from "./tool-order.js";
|
|
|
9
9
|
|
|
10
10
|
export const MAX_TOOL_NAME_LEN = 64;
|
|
11
11
|
|
|
12
|
+
/** Built-in Pi management tool names registered outside `ToolBridge.toolOwners` (#332). */
|
|
13
|
+
export const MANAGEMENT_TOOL_NAMES = {
|
|
14
|
+
status: "mcp_status",
|
|
15
|
+
connect: "mcp_connect",
|
|
16
|
+
listResources: "mcp_list_resources",
|
|
17
|
+
readResource: "mcp_read_resource",
|
|
18
|
+
} as const;
|
|
19
|
+
|
|
20
|
+
/** Management tool names that bridged MCP server tools must never overwrite or hide (#332). */
|
|
21
|
+
export const RESERVED_MANAGEMENT_TOOL_NAMES: ReadonlySet<string> = new Set(
|
|
22
|
+
Object.values(MANAGEMENT_TOOL_NAMES),
|
|
23
|
+
);
|
|
24
|
+
|
|
12
25
|
export interface ResolveUniqueToolNameOptions {
|
|
13
26
|
prefix: string;
|
|
14
27
|
serverName: string;
|
|
15
28
|
rawToolName: string;
|
|
16
29
|
seenInBatch: ReadonlySet<string>;
|
|
17
30
|
toolOwners: ReadonlyMap<string, string>;
|
|
31
|
+
forceHash?: boolean | undefined;
|
|
32
|
+
collidedBaseNames?: ReadonlySet<string> | undefined;
|
|
33
|
+
reservedNames?: ReadonlySet<string> | undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface CollisionContext {
|
|
37
|
+
serverName: string;
|
|
38
|
+
seenInBatch: ReadonlySet<string>;
|
|
39
|
+
toolOwners: ReadonlyMap<string, string>;
|
|
40
|
+
reservedNames: ReadonlySet<string> | undefined;
|
|
18
41
|
}
|
|
19
42
|
|
|
20
43
|
/** Replace any character outside `[a-zA-Z0-9_]` with `_`. */
|
|
@@ -108,28 +131,41 @@ export function orderToolsForNameAssignment(
|
|
|
108
131
|
return ordered;
|
|
109
132
|
}
|
|
110
133
|
|
|
111
|
-
|
|
112
|
-
|
|
134
|
+
/**
|
|
135
|
+
* True when another configured peer server sanitizes to the same `[a-zA-Z0-9_]` stem
|
|
136
|
+
* as `serverName` and outranks it under {@link compareNamesForAssignment} (lossless
|
|
137
|
+
* `[a-zA-Z0-9_]+` wins, then code-point order) (#331).
|
|
138
|
+
*/
|
|
139
|
+
export function isCollidingServerStemLoser(
|
|
113
140
|
serverName: string,
|
|
114
|
-
|
|
115
|
-
toolOwners: ReadonlyMap<string, string>,
|
|
141
|
+
peerServerNames: Iterable<string> | undefined,
|
|
116
142
|
): boolean {
|
|
117
|
-
if (
|
|
118
|
-
const
|
|
119
|
-
|
|
143
|
+
if (!peerServerNames) return false;
|
|
144
|
+
const stem = sanitizeIdentifierSegment(serverName);
|
|
145
|
+
for (const peer of peerServerNames) {
|
|
146
|
+
if (
|
|
147
|
+
peer !== serverName &&
|
|
148
|
+
sanitizeIdentifierSegment(peer) === stem &&
|
|
149
|
+
compareNamesForAssignment(peer, serverName) < 0
|
|
150
|
+
) {
|
|
151
|
+
return true;
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
return false;
|
|
120
155
|
}
|
|
121
156
|
|
|
122
|
-
function
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
157
|
+
function isToolNameTaken(name: string, ctx: CollisionContext): boolean {
|
|
158
|
+
if (ctx.seenInBatch.has(name) || ctx.reservedNames?.has(name)) return true;
|
|
159
|
+
const owner = ctx.toolOwners.get(name);
|
|
160
|
+
return owner !== undefined && owner !== ctx.serverName;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function findSuffixedToolName(hashedCandidate: string, ctx: CollisionContext): string {
|
|
128
164
|
let suffix = 2;
|
|
129
165
|
while (true) {
|
|
130
166
|
const tag = `_${suffix}`;
|
|
131
167
|
const candidate = `${hashedCandidate.slice(0, MAX_TOOL_NAME_LEN - tag.length)}${tag}`;
|
|
132
|
-
if (!isToolNameTaken(candidate,
|
|
168
|
+
if (!isToolNameTaken(candidate, ctx)) {
|
|
133
169
|
return candidate;
|
|
134
170
|
}
|
|
135
171
|
suffix++;
|
|
@@ -138,21 +174,32 @@ function findSuffixedToolName(
|
|
|
138
174
|
|
|
139
175
|
/**
|
|
140
176
|
* Resolve a collision-free Pi tool name for `rawToolName` on `serverName`.
|
|
141
|
-
* Tries the unhashed `<prefix>_<server>_<tool>` name first
|
|
142
|
-
* 8-character SHA-256 suffix when
|
|
143
|
-
*
|
|
177
|
+
* Tries the unhashed `<prefix>_<server>_<tool>` name first (unless `forceHash` or
|
|
178
|
+
* `collidedBaseNames` forbids it), falls back to the 8-character SHA-256 suffix when
|
|
179
|
+
* taken or reserved, and appends `_2`, `_3`, … if even the hashed identifier is taken.
|
|
144
180
|
*/
|
|
145
181
|
export function resolveUniqueToolName(options: ResolveUniqueToolNameOptions): string {
|
|
146
|
-
const {
|
|
182
|
+
const {
|
|
183
|
+
prefix,
|
|
184
|
+
serverName,
|
|
185
|
+
rawToolName,
|
|
186
|
+
seenInBatch,
|
|
187
|
+
toolOwners,
|
|
188
|
+
forceHash = false,
|
|
189
|
+
collidedBaseNames,
|
|
190
|
+
reservedNames,
|
|
191
|
+
} = options;
|
|
192
|
+
const ctx: CollisionContext = { serverName, seenInBatch, toolOwners, reservedNames };
|
|
147
193
|
const baseCandidate = buildToolName(prefix, serverName, rawToolName, false);
|
|
148
|
-
|
|
194
|
+
const mustHash = forceHash || collidedBaseNames?.has(baseCandidate) === true;
|
|
195
|
+
if (!mustHash && !isToolNameTaken(baseCandidate, ctx)) {
|
|
149
196
|
return baseCandidate;
|
|
150
197
|
}
|
|
151
198
|
|
|
152
199
|
const hashedCandidate = buildToolName(prefix, serverName, rawToolName, true);
|
|
153
|
-
if (!isToolNameTaken(hashedCandidate,
|
|
200
|
+
if (!isToolNameTaken(hashedCandidate, ctx)) {
|
|
154
201
|
return hashedCandidate;
|
|
155
202
|
}
|
|
156
203
|
|
|
157
|
-
return findSuffixedToolName(hashedCandidate,
|
|
204
|
+
return findSuffixedToolName(hashedCandidate, ctx);
|
|
158
205
|
}
|
package/src/tool-reconcile.ts
CHANGED
|
@@ -12,7 +12,12 @@ import {
|
|
|
12
12
|
type RegisteredToolSummary,
|
|
13
13
|
type ToolExposureConfig,
|
|
14
14
|
} from "./tool-exposure.js";
|
|
15
|
-
import {
|
|
15
|
+
import {
|
|
16
|
+
buildToolName,
|
|
17
|
+
isCollidingServerStemLoser,
|
|
18
|
+
orderToolsForNameAssignment,
|
|
19
|
+
resolveUniqueToolName,
|
|
20
|
+
} from "./tool-names.js";
|
|
16
21
|
import { orderOwnedEntries, sameToolList } from "./tool-order.js";
|
|
17
22
|
|
|
18
23
|
/** Structural shape of `refreshTools` options accepted by {@link normalizeRefreshArgs}. */
|
|
@@ -36,6 +41,10 @@ export interface PlanServerToolBatchOptions {
|
|
|
36
41
|
toolOwners: ReadonlyMap<string, string>;
|
|
37
42
|
ownedPreviousNames?: ReadonlySet<string> | undefined;
|
|
38
43
|
exposureConfig?: ToolExposureConfig | undefined;
|
|
44
|
+
peerServerNames?: Iterable<string> | undefined;
|
|
45
|
+
collidedBaseNames?: ReadonlySet<string> | undefined;
|
|
46
|
+
baseNameOwners?: ReadonlyMap<string, string> | undefined;
|
|
47
|
+
reservedNames?: ReadonlySet<string> | undefined;
|
|
39
48
|
}
|
|
40
49
|
|
|
41
50
|
/** Planned registration batch, Pi→raw lookup tables, exposure maps, and withdrawn tool names. */
|
|
@@ -47,6 +56,7 @@ export interface ServerToolBatchPlan {
|
|
|
47
56
|
piExposures: Map<string, McpExposure>;
|
|
48
57
|
directToolNames: Set<string>;
|
|
49
58
|
withdrawnToolNames: Set<string>;
|
|
59
|
+
crossServerCollisions: Map<string, string>;
|
|
50
60
|
}
|
|
51
61
|
|
|
52
62
|
/** Input for preserving active/inactive tool state across a live `tools/list_changed` refresh. */
|
|
@@ -142,6 +152,123 @@ export function deleteServerOwnedTools(
|
|
|
142
152
|
serverToolNames.delete(serverName);
|
|
143
153
|
}
|
|
144
154
|
|
|
155
|
+
function detectCrossServerCollision(
|
|
156
|
+
baseCandidate: string,
|
|
157
|
+
hashedCandidate: string,
|
|
158
|
+
options: PlanServerToolBatchOptions,
|
|
159
|
+
): string | undefined {
|
|
160
|
+
if (baseCandidate === hashedCandidate) return undefined;
|
|
161
|
+
const owner =
|
|
162
|
+
options.toolOwners.get(baseCandidate) ?? options.baseNameOwners?.get(baseCandidate);
|
|
163
|
+
if (owner !== undefined && owner !== options.serverName) {
|
|
164
|
+
return owner;
|
|
165
|
+
}
|
|
166
|
+
return undefined;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Collect Pi tool names that bridged MCP tools must not overwrite: built-in management
|
|
171
|
+
* tools plus any foreign tools in `allTools` not registered by this bridge (#332).
|
|
172
|
+
*/
|
|
173
|
+
export function collectReservedToolNames(
|
|
174
|
+
baseReserved: ReadonlySet<string>,
|
|
175
|
+
allTools: readonly RegisteredToolSummary[] | undefined,
|
|
176
|
+
bridgeRegisteredNames: ReadonlySet<string>,
|
|
177
|
+
): Set<string> {
|
|
178
|
+
const reserved = new Set(baseReserved);
|
|
179
|
+
if (!allTools) return reserved;
|
|
180
|
+
for (const tool of allTools) {
|
|
181
|
+
if (!bridgeRegisteredNames.has(tool.name)) {
|
|
182
|
+
reserved.add(tool.name);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return reserved;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
function getOrCreateSet(map: Map<string, Set<string>>, key: string): Set<string> {
|
|
189
|
+
let set = map.get(key);
|
|
190
|
+
if (!set) {
|
|
191
|
+
set = new Set<string>();
|
|
192
|
+
map.set(key, set);
|
|
193
|
+
}
|
|
194
|
+
return set;
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Record that `serverName` advertises a tool targeting unhashed `baseName`, so if a real
|
|
199
|
+
* cross-server collision later occurs on `baseName` this server is included in
|
|
200
|
+
* `collidedBaseServers` regardless of connect order (#331).
|
|
201
|
+
*/
|
|
202
|
+
export function recordBaseNameCandidate(
|
|
203
|
+
baseNameCandidates: Map<string, Set<string>>,
|
|
204
|
+
baseName: string,
|
|
205
|
+
serverName: string,
|
|
206
|
+
): void {
|
|
207
|
+
getOrCreateSet(baseNameCandidates, baseName).add(serverName);
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Record a cross-server base-name collision and include any previously connected server
|
|
212
|
+
* (such as a stem-loser peer) that also targets `baseName` so dynamic peer removal stays
|
|
213
|
+
* connect-order invariant (#331).
|
|
214
|
+
*/
|
|
215
|
+
export function recordCrossServerCollision(
|
|
216
|
+
baseName: string,
|
|
217
|
+
incumbentServer: string,
|
|
218
|
+
incomingServer: string,
|
|
219
|
+
collidedBaseServers: Map<string, Set<string>>,
|
|
220
|
+
baseNameCandidates?: ReadonlyMap<string, ReadonlySet<string>>,
|
|
221
|
+
): void {
|
|
222
|
+
const servers = getOrCreateSet(collidedBaseServers, baseName);
|
|
223
|
+
servers.add(incumbentServer);
|
|
224
|
+
servers.add(incomingServer);
|
|
225
|
+
for (const candidate of baseNameCandidates?.get(baseName) ?? []) {
|
|
226
|
+
servers.add(candidate);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Remove `serverName` from cross-server base-ownership, collision-set, and candidate-base
|
|
232
|
+
* tracking, deleting any collision entry that drops below 2 competing servers and
|
|
233
|
+
* transferring any sole surviving server back to `baseNameOwners` (#331).
|
|
234
|
+
*/
|
|
235
|
+
export function forgetServerCollisionState(
|
|
236
|
+
serverName: string,
|
|
237
|
+
baseNameOwners: Map<string, string>,
|
|
238
|
+
collidedBaseServers: Map<string, Set<string>>,
|
|
239
|
+
baseNameCandidates?: Map<string, Set<string>>,
|
|
240
|
+
): void {
|
|
241
|
+
for (const [baseName, owner] of baseNameOwners) {
|
|
242
|
+
if (owner === serverName) {
|
|
243
|
+
baseNameOwners.delete(baseName);
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
for (const [baseName, servers] of collidedBaseServers) {
|
|
247
|
+
servers.delete(serverName);
|
|
248
|
+
if (servers.size < 2) {
|
|
249
|
+
collidedBaseServers.delete(baseName);
|
|
250
|
+
const [survivor] = servers;
|
|
251
|
+
if (survivor !== undefined) {
|
|
252
|
+
baseNameOwners.set(baseName, survivor);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
for (const [baseName, candidates] of baseNameCandidates ?? []) {
|
|
257
|
+
candidates.delete(serverName);
|
|
258
|
+
if (candidates.size === 0) {
|
|
259
|
+
baseNameCandidates?.delete(baseName);
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/** Collect resolved MCP exposures present in `next` that were absent from `previous`. */
|
|
265
|
+
export function collectAddedExposures(
|
|
266
|
+
previous: ReadonlySet<McpExposure> | undefined,
|
|
267
|
+
next: ReadonlySet<McpExposure>,
|
|
268
|
+
): Set<McpExposure> {
|
|
269
|
+
return new Set([...next].filter((exposure) => !previous?.has(exposure)));
|
|
270
|
+
}
|
|
271
|
+
|
|
145
272
|
/**
|
|
146
273
|
* Deterministically assign collision-free Pi tool names and resolved MCP exposures for a
|
|
147
274
|
* server's discovered tools, and compute any previously owned Pi names withdrawn by this refresh.
|
|
@@ -154,17 +281,30 @@ export function planServerToolBatch(options: PlanServerToolBatchOptions): Server
|
|
|
154
281
|
const currentExposures = new Map<string, McpExposure>();
|
|
155
282
|
const piExposures = new Map<string, McpExposure>();
|
|
156
283
|
const directToolNames = new Set<string>();
|
|
284
|
+
const crossServerCollisions = new Map<string, string>();
|
|
285
|
+
const stemLoser = isCollidingServerStemLoser(serverName, options.peerServerNames);
|
|
157
286
|
// WHY: `tools/list` order carries no meaning (a server may reorder it freely), so colliding
|
|
158
287
|
// names are assigned over a deterministic order of the tool set — otherwise the exact-match
|
|
159
288
|
// tool could lose the unhashed name to a lossy one and a later refresh would swap which MCP
|
|
160
289
|
// tool that name executes (#213).
|
|
161
290
|
for (const tool of orderToolsForNameAssignment(prefix, serverName, tools)) {
|
|
291
|
+
const baseCandidate = buildToolName(prefix, serverName, tool.name, false);
|
|
292
|
+
const hashedCandidate = buildToolName(prefix, serverName, tool.name, true);
|
|
293
|
+
const incumbent = stemLoser
|
|
294
|
+
? undefined
|
|
295
|
+
: detectCrossServerCollision(baseCandidate, hashedCandidate, options);
|
|
296
|
+
if (incumbent !== undefined) {
|
|
297
|
+
crossServerCollisions.set(baseCandidate, incumbent);
|
|
298
|
+
}
|
|
162
299
|
const piName = resolveUniqueToolName({
|
|
163
300
|
prefix,
|
|
164
301
|
serverName,
|
|
165
302
|
rawToolName: tool.name,
|
|
166
303
|
seenInBatch: currentToolNames,
|
|
167
304
|
toolOwners,
|
|
305
|
+
forceHash: stemLoser || incumbent !== undefined,
|
|
306
|
+
collidedBaseNames: options.collidedBaseNames,
|
|
307
|
+
reservedNames: options.reservedNames,
|
|
168
308
|
});
|
|
169
309
|
const exposure = resolveToolExposure(exposureConfig, tool.name);
|
|
170
310
|
plannedTools.push({ piName, tool, exposure });
|
|
@@ -187,6 +327,7 @@ export function planServerToolBatch(options: PlanServerToolBatchOptions): Server
|
|
|
187
327
|
piExposures,
|
|
188
328
|
directToolNames,
|
|
189
329
|
withdrawnToolNames,
|
|
330
|
+
crossServerCollisions,
|
|
190
331
|
};
|
|
191
332
|
}
|
|
192
333
|
|
|
@@ -373,3 +514,122 @@ export function planActiveToolReconciliation(
|
|
|
373
514
|
// with — so compare against a fresh read and write whenever the set *or* the order differs.
|
|
374
515
|
return sameToolList(currentActive, nextActive) ? undefined : nextActive;
|
|
375
516
|
}
|
|
517
|
+
|
|
518
|
+
/** Input for recording raw MCP tool names of `direct` tools stripped across `/tree` hops (#333). */
|
|
519
|
+
export interface UpdateTreeDeactivatedInput {
|
|
520
|
+
existing: ReadonlySet<string> | undefined;
|
|
521
|
+
directTools: ReadonlySet<string> | undefined;
|
|
522
|
+
rawToolNames?: ReadonlyMap<string, string> | undefined;
|
|
523
|
+
droppedToolState?: ReadonlyMap<string, boolean> | undefined;
|
|
524
|
+
rawToolExposures?: ReadonlyMap<string, McpExposure> | undefined;
|
|
525
|
+
beforeActive: ReadonlySet<string> | undefined;
|
|
526
|
+
currentActive: ReadonlySet<string>;
|
|
527
|
+
}
|
|
528
|
+
|
|
529
|
+
/** Input for pruning tracked raw `/tree`-deactivated `direct` tool names (#333). */
|
|
530
|
+
export interface PruneTreeDeactivatedInput {
|
|
531
|
+
existing: ReadonlySet<string> | undefined;
|
|
532
|
+
directTools: ReadonlySet<string> | undefined;
|
|
533
|
+
rawToolNames?: ReadonlyMap<string, string> | undefined;
|
|
534
|
+
droppedToolState?: ReadonlyMap<string, boolean> | undefined;
|
|
535
|
+
rawToolExposures?: ReadonlyMap<string, McpExposure> | undefined;
|
|
536
|
+
nowActive: ReadonlySet<string>;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/** Input for restoring tracked raw `/tree`-deactivated `direct` tools onto Pi's active set (#333). */
|
|
540
|
+
export interface PlanTreeDirectToolRestoreInput {
|
|
541
|
+
pendingRawNames: ReadonlySet<string> | undefined;
|
|
542
|
+
directTools: ReadonlySet<string> | undefined;
|
|
543
|
+
rawToolNames?: ReadonlyMap<string, string> | undefined;
|
|
544
|
+
activeBefore: readonly string[];
|
|
545
|
+
isOwned: (name: string) => boolean;
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
function collectDroppedDirectTools(
|
|
549
|
+
existing: ReadonlySet<string> | undefined,
|
|
550
|
+
activeRaw: ReadonlySet<string>,
|
|
551
|
+
droppedToolState: ReadonlyMap<string, boolean> | undefined,
|
|
552
|
+
rawToolExposures: ReadonlyMap<string, McpExposure> | undefined,
|
|
553
|
+
target: Set<string>,
|
|
554
|
+
): void {
|
|
555
|
+
if (!existing || !droppedToolState || !rawToolExposures) return;
|
|
556
|
+
for (const rawName of existing) {
|
|
557
|
+
if (
|
|
558
|
+
!activeRaw.has(rawName) &&
|
|
559
|
+
droppedToolState.has(rawName) &&
|
|
560
|
+
rawToolExposures.get(rawName) === "direct"
|
|
561
|
+
) {
|
|
562
|
+
target.add(rawName);
|
|
563
|
+
}
|
|
564
|
+
}
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* Accumulate raw MCP tool names of `direct` tools stripped across one or more `/tree` hops,
|
|
569
|
+
* retaining transiently dropped `direct` tools while pruning any that are active again on
|
|
570
|
+
* `currentActive` or no longer `direct` (#333).
|
|
571
|
+
* When `beforeActive` is `undefined`, no new deactivations are recorded.
|
|
572
|
+
*/
|
|
573
|
+
export function updateTreeDeactivatedDirectTools(
|
|
574
|
+
input: UpdateTreeDeactivatedInput,
|
|
575
|
+
): Set<string> | undefined {
|
|
576
|
+
const next = new Set<string>();
|
|
577
|
+
const activeRaw = new Set<string>();
|
|
578
|
+
if (input.directTools) {
|
|
579
|
+
for (const piName of input.directTools) {
|
|
580
|
+
const rawName = input.rawToolNames?.get(piName) ?? piName;
|
|
581
|
+
if (input.currentActive.has(piName)) {
|
|
582
|
+
activeRaw.add(rawName);
|
|
583
|
+
} else if (input.beforeActive?.has(piName) || input.existing?.has(rawName)) {
|
|
584
|
+
next.add(rawName);
|
|
585
|
+
}
|
|
586
|
+
}
|
|
587
|
+
}
|
|
588
|
+
collectDroppedDirectTools(
|
|
589
|
+
input.existing,
|
|
590
|
+
activeRaw,
|
|
591
|
+
input.droppedToolState,
|
|
592
|
+
input.rawToolExposures,
|
|
593
|
+
next,
|
|
594
|
+
);
|
|
595
|
+
return next.size > 0 ? next : undefined;
|
|
596
|
+
}
|
|
597
|
+
|
|
598
|
+
/**
|
|
599
|
+
* Prune tracked raw `/tree`-deactivated `direct` tool names against current `direct` tools,
|
|
600
|
+
* dropped-direct memory, and `nowActive` Pi tool names (#333).
|
|
601
|
+
*/
|
|
602
|
+
export function pruneTreeDeactivatedDirectTools(
|
|
603
|
+
input: PruneTreeDeactivatedInput,
|
|
604
|
+
): Set<string> | undefined {
|
|
605
|
+
return updateTreeDeactivatedDirectTools({
|
|
606
|
+
...input,
|
|
607
|
+
beforeActive: undefined,
|
|
608
|
+
currentActive: input.nowActive,
|
|
609
|
+
});
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
/**
|
|
613
|
+
* Plan an additive, deterministically ordered active-tool list restoring `/tree`-deactivated
|
|
614
|
+
* `direct` tools (resolved from raw MCP tool names to their current Pi names) without altering
|
|
615
|
+
* any other extension's restrictions (#333).
|
|
616
|
+
*/
|
|
617
|
+
export function planTreeDirectToolRestore(
|
|
618
|
+
input: PlanTreeDirectToolRestoreInput,
|
|
619
|
+
): string[] | undefined {
|
|
620
|
+
const { pendingRawNames, directTools, rawToolNames, activeBefore, isOwned } = input;
|
|
621
|
+
if (!pendingRawNames?.size || !directTools?.size) {
|
|
622
|
+
return undefined;
|
|
623
|
+
}
|
|
624
|
+
const activeSet = new Set(activeBefore);
|
|
625
|
+
const toRestore: string[] = [];
|
|
626
|
+
for (const piName of directTools) {
|
|
627
|
+
const rawName = rawToolNames?.get(piName) ?? piName;
|
|
628
|
+
if (pendingRawNames.has(rawName) && !activeSet.has(piName)) {
|
|
629
|
+
toRestore.push(piName);
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
if (toRestore.length === 0) return undefined;
|
|
633
|
+
const nextActive = orderOwnedActiveTools(new Set([...activeBefore, ...toRestore]), isOwned);
|
|
634
|
+
return sameToolList(activeBefore, nextActive) ? undefined : nextActive;
|
|
635
|
+
}
|