@xzzpig/pi-subagents 0.8.0 → 0.9.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 +443 -0
- package/README.md +2 -2
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +151 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +5 -4
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +370 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +12 -2
- package/src/agents/agents.ts +919 -372
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +48 -18
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +57 -21
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +366 -128
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +45 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +189 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +39 -16
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +84 -17
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +676 -1161
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +468 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1172 -400
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +138 -36
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +32 -6
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +139 -9
- package/src/runs/shared/model-fallback.ts +142 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +15 -7
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +8 -1
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +524 -70
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +217 -82
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1429 -163
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +988 -59
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -935
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -2,11 +2,21 @@ import { createHash } from "node:crypto";
|
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as path from "node:path";
|
|
5
|
+
import { findConfiguredProjectRoot } from "../../agents/agents.ts";
|
|
5
6
|
import { getAgentDir, getProjectConfigDir } from "../../shared/utils.ts";
|
|
7
|
+
import { isMcpServerDefinition, loadAgentPluginMcpServers, loadPackageMcpServers, type McpServerDefinition } from "./mcp-config-sources.ts";
|
|
8
|
+
import {
|
|
9
|
+
normalizeMcpDirectToolSelectors,
|
|
10
|
+
parseMcpDirectToolSelectors,
|
|
11
|
+
planMcpDirectToolGrant,
|
|
12
|
+
} from "./mcp-direct-tool-grant.ts";
|
|
13
|
+
import type { McpToolPrefix, ResolvedMcpDirectToolSelection } from "./mcp-direct-tool-grant.ts";
|
|
14
|
+
|
|
15
|
+
export { formatUnresolvedMcpDirectToolSelectors } from "./mcp-direct-tool-grant.ts";
|
|
16
|
+
export type { ResolvedMcpDirectToolSelection } from "./mcp-direct-tool-grant.ts";
|
|
6
17
|
|
|
7
18
|
const CACHE_VERSION = 1;
|
|
8
19
|
const CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000;
|
|
9
|
-
const BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
|
|
10
20
|
const GENERIC_GLOBAL_CONFIG_PATH = path.join(os.homedir(), ".config", "mcp", "mcp.json");
|
|
11
21
|
const IMPORT_PATHS = {
|
|
12
22
|
cursor: [path.join(os.homedir(), ".cursor", "mcp.json")],
|
|
@@ -21,39 +31,41 @@ const IMPORT_PATHS = {
|
|
|
21
31
|
vscode: [".vscode/mcp.json"],
|
|
22
32
|
} as const;
|
|
23
33
|
|
|
24
|
-
type ToolPrefix = "server" | "none" | "short";
|
|
25
34
|
type ImportKind = keyof typeof IMPORT_PATHS;
|
|
26
35
|
|
|
27
|
-
|
|
28
|
-
command?: string;
|
|
29
|
-
args?: string[];
|
|
30
|
-
socket?: string;
|
|
31
|
-
env?: Record<string, string>;
|
|
32
|
-
cwd?: string;
|
|
33
|
-
url?: string;
|
|
34
|
-
headers?: Record<string, string>;
|
|
35
|
-
requestHeadersCommand?: {
|
|
36
|
-
command: string;
|
|
37
|
-
args?: string[];
|
|
38
|
-
env?: Record<string, string>;
|
|
39
|
-
timeoutMs?: number;
|
|
40
|
-
};
|
|
41
|
-
auth?: "oauth" | "bearer" | false;
|
|
42
|
-
bearerToken?: string;
|
|
43
|
-
bearerTokenEnv?: string;
|
|
44
|
-
exposeResources?: boolean;
|
|
45
|
-
includeTools?: string[];
|
|
46
|
-
excludeTools?: string[];
|
|
47
|
-
protocolVersion?: string;
|
|
48
|
-
directTools?: boolean | string[];
|
|
49
|
-
}
|
|
36
|
+
type ServerEntry = McpServerDefinition;
|
|
50
37
|
|
|
51
|
-
interface McpConfig {
|
|
38
|
+
export interface McpConfig {
|
|
52
39
|
mcpServers: Record<string, ServerEntry>;
|
|
53
40
|
imports?: ImportKind[];
|
|
54
41
|
settings?: {
|
|
55
|
-
toolPrefix?:
|
|
42
|
+
toolPrefix?: McpToolPrefix;
|
|
56
43
|
directTools?: boolean;
|
|
44
|
+
agentPluginPaths?: unknown;
|
|
45
|
+
};
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export const MCP_RUNTIME_SNAPSHOT_EVENT = "pi-mcp-adapter:runtime-snapshot:v1" as const;
|
|
49
|
+
export const MCP_RUNTIME_SNAPSHOT_VERSION = 1 as const;
|
|
50
|
+
|
|
51
|
+
export interface McpRuntimeServerSnapshot {
|
|
52
|
+
readonly name: string;
|
|
53
|
+
readonly definition: ServerEntry;
|
|
54
|
+
readonly runtime: true;
|
|
55
|
+
readonly persisted: false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface McpRuntimeSnapshotRequest {
|
|
59
|
+
version: typeof MCP_RUNTIME_SNAPSHOT_VERSION;
|
|
60
|
+
name: string;
|
|
61
|
+
result?:
|
|
62
|
+
| { ok: true; snapshot: McpRuntimeServerSnapshot }
|
|
63
|
+
| { ok: false; error: Error };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export interface McpRuntimeSnapshotHost {
|
|
67
|
+
events: {
|
|
68
|
+
emit(event: string, request: McpRuntimeSnapshotRequest): void;
|
|
57
69
|
};
|
|
58
70
|
}
|
|
59
71
|
|
|
@@ -78,19 +90,60 @@ interface MetadataCache {
|
|
|
78
90
|
servers: Record<string, ServerCacheEntry>;
|
|
79
91
|
}
|
|
80
92
|
|
|
81
|
-
export interface
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
+
export interface McpDirectToolResolution {
|
|
94
|
+
selections: ResolvedMcpDirectToolSelection[];
|
|
95
|
+
unresolvedSelectors: string[];
|
|
96
|
+
/** Normal loaded config plus the selected runtime server definitions. */
|
|
97
|
+
mcpConfig?: McpConfig;
|
|
98
|
+
runtimeServerNames?: string[];
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function resolveMcpDirectToolResolution(
|
|
102
|
+
mcpDirectTools: string[] | undefined,
|
|
103
|
+
cwd = process.cwd(),
|
|
104
|
+
runtimeSnapshotHost?: McpRuntimeSnapshotHost,
|
|
105
|
+
configOverride?: McpConfig,
|
|
106
|
+
): McpDirectToolResolution {
|
|
107
|
+
const selectors = normalizeMcpDirectToolSelectors(mcpDirectTools);
|
|
108
|
+
if (selectors.length === 0) return { selections: [], unresolvedSelectors: [] };
|
|
109
|
+
|
|
110
|
+
const config = configOverride ?? loadMcpConfig(cwd);
|
|
111
|
+
const { servers: selectedServers, tools: selectedTools } = parseMcpDirectToolSelectors(selectors);
|
|
112
|
+
const runtimeSelectionServers = new Set([...selectedServers, ...selectedTools.keys()]);
|
|
113
|
+
const runtimeServers = resolveRuntimeMcpServers(config, runtimeSelectionServers, runtimeSnapshotHost);
|
|
114
|
+
const resolvedConfig = Object.keys(runtimeServers).length > 0
|
|
115
|
+
? mergeConfigs(config, { mcpServers: runtimeServers })
|
|
116
|
+
: config;
|
|
117
|
+
validateSelectedServerDefinitions(resolvedConfig, selectors);
|
|
118
|
+
const runtime = Object.keys(runtimeServers).length > 0
|
|
119
|
+
? { mcpConfig: resolvedConfig, runtimeServerNames: Object.keys(runtimeServers) }
|
|
120
|
+
: {};
|
|
121
|
+
const cache = loadMetadataCache();
|
|
122
|
+
if (!cache) return { selections: [], unresolvedSelectors: selectors, ...runtime };
|
|
123
|
+
const validMetadata: Record<string, ServerCacheEntry> = {};
|
|
124
|
+
for (const [serverName, definition] of Object.entries(resolvedConfig.mcpServers)) {
|
|
125
|
+
const serverCache = cache.servers[serverName];
|
|
126
|
+
if (isServerCacheValid(serverCache, definition)) validMetadata[serverName] = serverCache;
|
|
93
127
|
}
|
|
128
|
+
const grant = planMcpDirectToolGrant({
|
|
129
|
+
selectors,
|
|
130
|
+
servers: resolvedConfig.mcpServers,
|
|
131
|
+
metadata: validMetadata,
|
|
132
|
+
toolPrefix: resolvedConfig.settings?.toolPrefix,
|
|
133
|
+
});
|
|
134
|
+
return {
|
|
135
|
+
selections: grant.selections,
|
|
136
|
+
unresolvedSelectors: grant.unresolvedSelectors,
|
|
137
|
+
...runtime,
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
export function resolveMcpDirectToolSelections(
|
|
142
|
+
mcpDirectTools: string[] | undefined,
|
|
143
|
+
cwd = process.cwd(),
|
|
144
|
+
runtimeSnapshotHost?: McpRuntimeSnapshotHost,
|
|
145
|
+
): ResolvedMcpDirectToolSelection[] {
|
|
146
|
+
return resolveMcpDirectToolResolution(mcpDirectTools, cwd, runtimeSnapshotHost).selections;
|
|
94
147
|
}
|
|
95
148
|
|
|
96
149
|
function loadMetadataCache(): MetadataCache | null {
|
|
@@ -102,28 +155,116 @@ function loadMetadataCache(): MetadataCache | null {
|
|
|
102
155
|
return null;
|
|
103
156
|
}
|
|
104
157
|
|
|
105
|
-
if (!parsed ||
|
|
106
|
-
const
|
|
107
|
-
|
|
108
|
-
|
|
158
|
+
if (!isRecord(parsed) || parsed.version !== CACHE_VERSION || !isRecord(parsed.servers)) return null;
|
|
159
|
+
const servers: Record<string, ServerCacheEntry> = {};
|
|
160
|
+
for (const [name, value] of Object.entries(parsed.servers)) {
|
|
161
|
+
const entry = parseServerCacheEntry(value);
|
|
162
|
+
if (entry) servers[name] = entry;
|
|
163
|
+
}
|
|
164
|
+
return { version: CACHE_VERSION, servers };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function parseServerCacheEntry(value: unknown): ServerCacheEntry | undefined {
|
|
168
|
+
if (!isRecord(value)) return undefined;
|
|
169
|
+
if (value.configHash !== undefined && typeof value.configHash !== "string") return undefined;
|
|
170
|
+
if (value.cachedAt !== undefined && (typeof value.cachedAt !== "number" || !Number.isFinite(value.cachedAt))) return undefined;
|
|
171
|
+
if (value.tools !== undefined && !Array.isArray(value.tools)) return undefined;
|
|
172
|
+
if (value.resources !== undefined && !Array.isArray(value.resources)) return undefined;
|
|
173
|
+
const tools = value.tools?.map(parseCachedTool);
|
|
174
|
+
const resources = value.resources?.map(parseCachedResource);
|
|
175
|
+
if (tools && !tools.every((entry): entry is CachedTool => entry !== undefined)) return undefined;
|
|
176
|
+
if (resources && !resources.every((entry): entry is CachedResource => entry !== undefined)) return undefined;
|
|
177
|
+
return {
|
|
178
|
+
...(value.configHash !== undefined ? { configHash: value.configHash } : {}),
|
|
179
|
+
...(value.cachedAt !== undefined ? { cachedAt: value.cachedAt } : {}),
|
|
180
|
+
...(tools ? { tools } : {}),
|
|
181
|
+
...(resources ? { resources } : {}),
|
|
182
|
+
};
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function parseCachedTool(value: unknown): CachedTool | undefined {
|
|
186
|
+
if (!isRecord(value) || (value.name !== undefined && typeof value.name !== "string")) return undefined;
|
|
187
|
+
return value.name === undefined ? {} : { name: value.name };
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
function parseCachedResource(value: unknown): CachedResource | undefined {
|
|
191
|
+
if (!isRecord(value)) return undefined;
|
|
192
|
+
if (value.uri !== undefined && typeof value.uri !== "string") return undefined;
|
|
193
|
+
if (value.name !== undefined && typeof value.name !== "string") return undefined;
|
|
194
|
+
return {
|
|
195
|
+
...(value.uri !== undefined ? { uri: value.uri } : {}),
|
|
196
|
+
...(value.name !== undefined ? { name: value.name } : {}),
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function resolveRuntimeMcpServers(
|
|
201
|
+
config: McpConfig,
|
|
202
|
+
selectedServers: ReadonlySet<string>,
|
|
203
|
+
runtimeSnapshotHost: McpRuntimeSnapshotHost | undefined,
|
|
204
|
+
): Record<string, ServerEntry> {
|
|
205
|
+
if (!runtimeSnapshotHost) return {};
|
|
206
|
+
const runtimeServers: Record<string, ServerEntry> = {};
|
|
207
|
+
for (const serverName of selectedServers) {
|
|
208
|
+
if (Object.hasOwn(config.mcpServers, serverName)) continue;
|
|
209
|
+
try {
|
|
210
|
+
const snapshot = getRuntimeMcpServerSnapshot(runtimeSnapshotHost, serverName);
|
|
211
|
+
runtimeServers[serverName] = snapshot.definition;
|
|
212
|
+
} catch {
|
|
213
|
+
// Missing, disposed, or shadowed runtime servers remain unresolved below.
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
return runtimeServers;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function getRuntimeMcpServerSnapshot(
|
|
220
|
+
host: McpRuntimeSnapshotHost,
|
|
221
|
+
name: string,
|
|
222
|
+
): McpRuntimeServerSnapshot {
|
|
223
|
+
const request: McpRuntimeSnapshotRequest = {
|
|
224
|
+
version: MCP_RUNTIME_SNAPSHOT_VERSION,
|
|
225
|
+
name,
|
|
226
|
+
};
|
|
227
|
+
host.events.emit(MCP_RUNTIME_SNAPSHOT_EVENT, request);
|
|
228
|
+
if (!request.result) throw new Error("pi-mcp-adapter is not installed for this Pi instance");
|
|
229
|
+
if (!request.result.ok) throw request.result.error;
|
|
230
|
+
const snapshot = request.result.snapshot;
|
|
231
|
+
if (
|
|
232
|
+
!snapshot ||
|
|
233
|
+
snapshot.name !== name ||
|
|
234
|
+
snapshot.runtime !== true ||
|
|
235
|
+
snapshot.persisted !== false ||
|
|
236
|
+
!isMcpServerDefinition(snapshot.definition)
|
|
237
|
+
) {
|
|
238
|
+
throw new Error(`Invalid MCP runtime snapshot for server "${name}"`);
|
|
109
239
|
}
|
|
110
|
-
return
|
|
240
|
+
return snapshot;
|
|
111
241
|
}
|
|
112
242
|
|
|
113
243
|
function loadMcpConfig(cwd: string): McpConfig {
|
|
244
|
+
const resolvedCwd = path.resolve(cwd);
|
|
245
|
+
const projectRoot = findConfiguredProjectRoot(resolvedCwd) ?? resolvedCwd;
|
|
114
246
|
let config: McpConfig = { mcpServers: {} };
|
|
115
|
-
for (const sourcePath of getConfigPaths(
|
|
247
|
+
for (const sourcePath of getConfigPaths(projectRoot)) {
|
|
116
248
|
const loaded = readConfig(sourcePath);
|
|
117
249
|
if (!loaded) continue;
|
|
118
|
-
config = mergeConfigs(config, expandImports(loaded,
|
|
250
|
+
config = mergeConfigs(config, expandImports(loaded, projectRoot));
|
|
119
251
|
}
|
|
120
|
-
|
|
252
|
+
|
|
253
|
+
const packageServers = loadPackageMcpServers(projectRoot);
|
|
254
|
+
const pluginServers = loadAgentPluginMcpServers(config.settings?.agentPluginPaths, projectRoot);
|
|
255
|
+
const packageOnlyServers = Object.fromEntries(
|
|
256
|
+
Object.entries(packageServers).filter(([name]) => !Object.hasOwn(pluginServers, name)),
|
|
257
|
+
);
|
|
258
|
+
return mergeConfigs(
|
|
259
|
+
{ mcpServers: packageOnlyServers },
|
|
260
|
+
mergeConfigs({ mcpServers: pluginServers }, config),
|
|
261
|
+
);
|
|
121
262
|
}
|
|
122
263
|
|
|
123
|
-
function getConfigPaths(
|
|
264
|
+
function getConfigPaths(projectRoot: string): string[] {
|
|
124
265
|
const piGlobalPath = path.join(getAgentDir(), "mcp.json");
|
|
125
|
-
const projectPath = path.resolve(
|
|
126
|
-
const projectPiPath = path.resolve(getProjectConfigDir(
|
|
266
|
+
const projectPath = path.resolve(projectRoot, ".mcp.json");
|
|
267
|
+
const projectPiPath = path.resolve(getProjectConfigDir(projectRoot), "mcp.json");
|
|
127
268
|
const sources: string[] = [];
|
|
128
269
|
if (GENERIC_GLOBAL_CONFIG_PATH !== piGlobalPath) sources.push(GENERIC_GLOBAL_CONFIG_PATH);
|
|
129
270
|
sources.push(piGlobalPath);
|
|
@@ -143,18 +284,33 @@ function readConfig(configPath: string): McpConfig | null {
|
|
|
143
284
|
}
|
|
144
285
|
|
|
145
286
|
function validateConfig(raw: unknown): McpConfig {
|
|
146
|
-
if (!
|
|
147
|
-
const obj = raw
|
|
287
|
+
if (!isRecord(raw)) return { mcpServers: {} };
|
|
288
|
+
const obj = raw;
|
|
148
289
|
const servers = obj.mcpServers ?? obj["mcp-servers"] ?? {};
|
|
149
290
|
return {
|
|
150
|
-
mcpServers:
|
|
291
|
+
mcpServers: parseServerEntries(servers),
|
|
151
292
|
imports: Array.isArray(obj.imports) ? obj.imports.filter((value): value is ImportKind => isImportKind(value)) : undefined,
|
|
152
|
-
settings:
|
|
153
|
-
? obj.settings as McpConfig["settings"]
|
|
154
|
-
: undefined,
|
|
293
|
+
settings: parseSettings(obj.settings),
|
|
155
294
|
};
|
|
156
295
|
}
|
|
157
296
|
|
|
297
|
+
function parseServerEntries(value: unknown): Record<string, ServerEntry> {
|
|
298
|
+
if (!isRecord(value)) return {};
|
|
299
|
+
return Object.fromEntries(Object.entries(value).filter((entry): entry is [string, ServerEntry] => isMcpServerDefinition(entry[1])));
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function parseSettings(value: unknown): McpConfig["settings"] | undefined {
|
|
303
|
+
if (!isRecord(value)) return undefined;
|
|
304
|
+
const toolPrefix = value.toolPrefix === "server" || value.toolPrefix === "short" || value.toolPrefix === "none" ? value.toolPrefix : undefined;
|
|
305
|
+
const directTools = typeof value.directTools === "boolean" ? value.directTools : undefined;
|
|
306
|
+
const settings: NonNullable<McpConfig["settings"]> = {
|
|
307
|
+
...(toolPrefix ? { toolPrefix } : {}),
|
|
308
|
+
...(directTools !== undefined ? { directTools } : {}),
|
|
309
|
+
...(value.agentPluginPaths !== undefined ? { agentPluginPaths: value.agentPluginPaths } : {}),
|
|
310
|
+
};
|
|
311
|
+
return Object.keys(settings).length ? settings : undefined;
|
|
312
|
+
}
|
|
313
|
+
|
|
158
314
|
function mergeConfigs(base: McpConfig, next: McpConfig): McpConfig {
|
|
159
315
|
const imports = [...(base.imports ?? []), ...(next.imports ?? [])];
|
|
160
316
|
return {
|
|
@@ -198,76 +354,24 @@ function resolveImportPath(importKind: ImportKind, cwd: string): string | null {
|
|
|
198
354
|
}
|
|
199
355
|
|
|
200
356
|
function extractServers(config: unknown, kind: ImportKind): Record<string, ServerEntry> {
|
|
201
|
-
if (!
|
|
202
|
-
const obj = config
|
|
357
|
+
if (!isRecord(config)) return {};
|
|
358
|
+
const obj = config;
|
|
203
359
|
const servers = kind === "cursor" || kind === "windsurf" || kind === "vscode"
|
|
204
360
|
? obj.mcpServers ?? obj["mcp-servers"]
|
|
205
361
|
: obj.mcpServers;
|
|
206
|
-
return
|
|
207
|
-
}
|
|
208
|
-
|
|
209
|
-
function resolveDirectToolSelections(config: McpConfig, cache: MetadataCache, prefix: ToolPrefix, envOverride: string[]): ResolvedMcpDirectToolSelection[] {
|
|
210
|
-
const names: ResolvedMcpDirectToolSelection[] = [];
|
|
211
|
-
const seenNames = new Set<string>();
|
|
212
|
-
const { servers: selectedServers, tools: selectedTools } = parseSelections(envOverride);
|
|
213
|
-
|
|
214
|
-
for (const [serverName, definition] of Object.entries(config.mcpServers)) {
|
|
215
|
-
const serverCache = cache.servers[serverName];
|
|
216
|
-
if (!isServerCacheValid(serverCache, definition)) continue;
|
|
217
|
-
|
|
218
|
-
const toolFilter = selectedServers.has(serverName)
|
|
219
|
-
? true
|
|
220
|
-
: selectedTools.get(serverName);
|
|
221
|
-
if (!toolFilter) continue;
|
|
222
|
-
|
|
223
|
-
for (const tool of Array.isArray(serverCache.tools) ? serverCache.tools : []) {
|
|
224
|
-
if (typeof tool?.name !== "string" || !tool.name) continue;
|
|
225
|
-
if (toolFilter !== true && !toolFilter.has(tool.name)) continue;
|
|
226
|
-
if (isToolExcluded(tool.name, serverName, prefix, definition.excludeTools)) continue;
|
|
227
|
-
const prefixedName = formatToolName(tool.name, serverName, prefix);
|
|
228
|
-
if (BUILTIN_TOOL_NAMES.has(prefixedName) || seenNames.has(prefixedName)) continue;
|
|
229
|
-
seenNames.add(prefixedName);
|
|
230
|
-
names.push({ name: prefixedName, selector: `${serverName}/${tool.name}` });
|
|
231
|
-
}
|
|
232
|
-
|
|
233
|
-
if (definition.exposeResources === false) continue;
|
|
234
|
-
for (const resource of Array.isArray(serverCache.resources) ? serverCache.resources : []) {
|
|
235
|
-
if (typeof resource?.name !== "string" || !resource.name || typeof resource.uri !== "string" || !resource.uri) continue;
|
|
236
|
-
const baseName = `get_${resourceNameToToolName(resource.name)}`;
|
|
237
|
-
if (toolFilter !== true && !toolFilter.has(baseName)) continue;
|
|
238
|
-
if (isToolExcluded(baseName, serverName, prefix, definition.excludeTools)) continue;
|
|
239
|
-
const prefixedName = formatToolName(baseName, serverName, prefix);
|
|
240
|
-
if (BUILTIN_TOOL_NAMES.has(prefixedName) || seenNames.has(prefixedName)) continue;
|
|
241
|
-
seenNames.add(prefixedName);
|
|
242
|
-
names.push({ name: prefixedName, selector: `${serverName}/${baseName}` });
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
|
|
246
|
-
return names;
|
|
362
|
+
return parseServerEntries(servers);
|
|
247
363
|
}
|
|
248
364
|
|
|
249
365
|
export function resolveMcpDirectToolNames(mcpDirectTools: string[] | undefined, cwd = process.cwd()): string[] {
|
|
250
366
|
return resolveMcpDirectToolSelections(mcpDirectTools, cwd).map((selection) => selection.name);
|
|
251
367
|
}
|
|
252
368
|
|
|
253
|
-
function
|
|
254
|
-
const servers =
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
if (item.includes("/")) {
|
|
259
|
-
const [server, tool] = item.split("/", 2);
|
|
260
|
-
if (server && tool) {
|
|
261
|
-
if (!tools.has(server)) tools.set(server, new Set());
|
|
262
|
-
tools.get(server)!.add(tool);
|
|
263
|
-
} else if (server) {
|
|
264
|
-
servers.add(server);
|
|
265
|
-
}
|
|
266
|
-
} else if (item) {
|
|
267
|
-
servers.add(item);
|
|
268
|
-
}
|
|
369
|
+
function validateSelectedServerDefinitions(config: McpConfig, selectors: string[]): void {
|
|
370
|
+
const { servers, tools } = parseMcpDirectToolSelectors(selectors);
|
|
371
|
+
for (const serverName of new Set([...servers, ...tools.keys()])) {
|
|
372
|
+
const definition = config.mcpServers[serverName];
|
|
373
|
+
if (definition) computeMcpServerHash(definition);
|
|
269
374
|
}
|
|
270
|
-
return { servers, tools };
|
|
271
375
|
}
|
|
272
376
|
|
|
273
377
|
function isServerCacheValid(entry: ServerCacheEntry | undefined, definition: ServerEntry): entry is ServerCacheEntry {
|
|
@@ -304,52 +408,12 @@ export function computeMcpServerHash(definition: ServerEntry): string {
|
|
|
304
408
|
return createHash("sha256").update(stableStringify(identity)).digest("hex");
|
|
305
409
|
}
|
|
306
410
|
|
|
307
|
-
function getToolPrefix(value: unknown): ToolPrefix {
|
|
308
|
-
return value === "none" || value === "short" || value === "server" ? value : "server";
|
|
309
|
-
}
|
|
310
|
-
|
|
311
411
|
function isImportKind(value: unknown): value is ImportKind {
|
|
312
412
|
return typeof value === "string" && Object.hasOwn(IMPORT_PATHS, value);
|
|
313
413
|
}
|
|
314
414
|
|
|
315
|
-
function
|
|
316
|
-
|
|
317
|
-
if (mode === "short") {
|
|
318
|
-
const short = serverName.replace(/-?mcp$/i, "").replace(/-/g, "_");
|
|
319
|
-
return short || "mcp";
|
|
320
|
-
}
|
|
321
|
-
return serverName.replace(/-/g, "_");
|
|
322
|
-
}
|
|
323
|
-
|
|
324
|
-
function formatToolName(toolName: string, serverName: string, prefix: ToolPrefix): string {
|
|
325
|
-
const serverPrefix = getServerPrefix(serverName, prefix);
|
|
326
|
-
return serverPrefix ? `${serverPrefix}_${toolName}` : toolName;
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
function isToolExcluded(toolName: string, serverName: string, prefix: ToolPrefix, excludeTools: unknown): boolean {
|
|
330
|
-
if (!Array.isArray(excludeTools) || excludeTools.length === 0) return false;
|
|
331
|
-
const candidates = new Set([
|
|
332
|
-
normalizeToolName(toolName),
|
|
333
|
-
normalizeToolName(formatToolName(toolName, serverName, prefix)),
|
|
334
|
-
normalizeToolName(formatToolName(toolName, serverName, "server")),
|
|
335
|
-
normalizeToolName(formatToolName(toolName, serverName, "short")),
|
|
336
|
-
]);
|
|
337
|
-
return excludeTools.some((excluded) => typeof excluded === "string" && candidates.has(normalizeToolName(excluded)));
|
|
338
|
-
}
|
|
339
|
-
|
|
340
|
-
function normalizeToolName(value: string): string {
|
|
341
|
-
return value.replace(/-/g, "_");
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
function resourceNameToToolName(name: string): string {
|
|
345
|
-
let result = name
|
|
346
|
-
.replace(/[^a-zA-Z0-9]/g, "_")
|
|
347
|
-
.replace(/_+/g, "_")
|
|
348
|
-
.replace(/^_+/, "")
|
|
349
|
-
.replace(/_+$/, "")
|
|
350
|
-
.toLowerCase();
|
|
351
|
-
if (!result || /^\d/.test(result)) result = `resource${result ? `_${result}` : ""}`;
|
|
352
|
-
return result;
|
|
415
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
416
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
353
417
|
}
|
|
354
418
|
|
|
355
419
|
function interpolateEnvRecord(values: Record<string, string> | undefined): Record<string, string> | undefined {
|
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
const BUILTIN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls", "mcp"]);
|
|
2
|
+
|
|
3
|
+
export type McpToolPrefix = "server" | "none" | "short";
|
|
4
|
+
|
|
5
|
+
export interface McpGrantServerFacts {
|
|
6
|
+
readonly exposeResources?: boolean;
|
|
7
|
+
readonly includeTools?: readonly unknown[];
|
|
8
|
+
readonly excludeTools?: readonly unknown[];
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
export interface McpGrantToolMetadata {
|
|
12
|
+
readonly name?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface McpGrantResourceMetadata {
|
|
16
|
+
readonly name?: string;
|
|
17
|
+
readonly uri?: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface McpGrantServerMetadata {
|
|
21
|
+
readonly tools?: readonly McpGrantToolMetadata[];
|
|
22
|
+
readonly resources?: readonly McpGrantResourceMetadata[];
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export interface McpDirectToolGrantInput {
|
|
26
|
+
readonly selectors?: readonly string[];
|
|
27
|
+
readonly servers: Readonly<Record<string, McpGrantServerFacts>>;
|
|
28
|
+
/** Cache entries already validated by the source-loading adapter. */
|
|
29
|
+
readonly metadata: Readonly<Record<string, McpGrantServerMetadata>>;
|
|
30
|
+
readonly toolPrefix?: unknown;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export interface ResolvedMcpDirectToolSelection {
|
|
34
|
+
name: string;
|
|
35
|
+
selector: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface McpDirectToolGrant {
|
|
39
|
+
selections: ResolvedMcpDirectToolSelection[];
|
|
40
|
+
unresolvedSelectors: string[];
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function normalizeMcpDirectToolSelectors(selectors: readonly string[] | undefined): string[] {
|
|
44
|
+
return [...new Set((selectors ?? []).map((selector) => selector.replace(/\/+$/, "")).filter(Boolean))];
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function parseMcpDirectToolSelectors(selectors: readonly string[]): {
|
|
48
|
+
servers: Set<string>;
|
|
49
|
+
tools: Map<string, Set<string>>;
|
|
50
|
+
} {
|
|
51
|
+
const servers = new Set<string>();
|
|
52
|
+
const tools = new Map<string, Set<string>>();
|
|
53
|
+
for (const item of selectors) {
|
|
54
|
+
if (item.includes("/")) {
|
|
55
|
+
const [server, tool] = item.split("/", 2);
|
|
56
|
+
if (server && tool) {
|
|
57
|
+
if (!tools.has(server)) tools.set(server, new Set());
|
|
58
|
+
tools.get(server)!.add(tool);
|
|
59
|
+
} else if (server) {
|
|
60
|
+
servers.add(server);
|
|
61
|
+
}
|
|
62
|
+
} else if (item) {
|
|
63
|
+
servers.add(item);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
return { servers, tools };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function planMcpDirectToolGrant(input: McpDirectToolGrantInput): McpDirectToolGrant {
|
|
70
|
+
const selectors = normalizeMcpDirectToolSelectors(input.selectors);
|
|
71
|
+
if (selectors.length === 0) return { selections: [], unresolvedSelectors: [] };
|
|
72
|
+
|
|
73
|
+
const { servers: selectedServers, tools: selectedTools } = parseMcpDirectToolSelectors(selectors);
|
|
74
|
+
const selections: ResolvedMcpDirectToolSelection[] = [];
|
|
75
|
+
const seenNames = new Set<string>();
|
|
76
|
+
const prefix = normalizeMcpToolPrefix(input.toolPrefix);
|
|
77
|
+
|
|
78
|
+
for (const [serverName, server] of Object.entries(input.servers)) {
|
|
79
|
+
const metadata = input.metadata[serverName];
|
|
80
|
+
if (!metadata) continue;
|
|
81
|
+
|
|
82
|
+
const toolFilter: true | ReadonlySet<string> | undefined = selectedServers.has(serverName)
|
|
83
|
+
? true
|
|
84
|
+
: selectedTools.get(serverName);
|
|
85
|
+
if (!toolFilter) continue;
|
|
86
|
+
|
|
87
|
+
for (const tool of Array.isArray(metadata.tools) ? metadata.tools : []) {
|
|
88
|
+
if (typeof tool?.name !== "string" || !tool.name) continue;
|
|
89
|
+
if (toolFilter !== true && !toolFilter.has(tool.name)) continue;
|
|
90
|
+
if (!isToolAllowed(tool.name, serverName, prefix, server.includeTools, server.excludeTools)) continue;
|
|
91
|
+
const name = formatToolName(tool.name, serverName, prefix);
|
|
92
|
+
if (BUILTIN_TOOL_NAMES.has(name) || seenNames.has(name)) continue;
|
|
93
|
+
seenNames.add(name);
|
|
94
|
+
selections.push({ name, selector: `${serverName}/${tool.name}` });
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (server.exposeResources === false) continue;
|
|
98
|
+
for (const resource of Array.isArray(metadata.resources) ? metadata.resources : []) {
|
|
99
|
+
if (typeof resource?.name !== "string" || !resource.name || typeof resource.uri !== "string" || !resource.uri) continue;
|
|
100
|
+
const baseName = `get_${resourceNameToToolName(resource.name)}`;
|
|
101
|
+
if (toolFilter !== true && !toolFilter.has(baseName)) continue;
|
|
102
|
+
if (!isToolAllowed(baseName, serverName, prefix, server.includeTools, server.excludeTools)) continue;
|
|
103
|
+
const name = formatToolName(baseName, serverName, prefix);
|
|
104
|
+
if (BUILTIN_TOOL_NAMES.has(name) || seenNames.has(name)) continue;
|
|
105
|
+
seenNames.add(name);
|
|
106
|
+
selections.push({ name, selector: `${serverName}/${baseName}` });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const unresolvedSelectors = selectors.filter((selector) =>
|
|
111
|
+
selector.includes("/")
|
|
112
|
+
? !selections.some((selection) => selection.selector === selector)
|
|
113
|
+
: !selections.some((selection) => selection.selector.startsWith(`${selector}/`)),
|
|
114
|
+
);
|
|
115
|
+
return { selections, unresolvedSelectors };
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
export function normalizeMcpToolPrefix(value: unknown): McpToolPrefix {
|
|
119
|
+
return value === "none" || value === "short" || value === "server" ? value : "server";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function formatUnresolvedMcpDirectToolSelectors(selectors: readonly string[]): string {
|
|
123
|
+
return `Unresolved MCP direct-tool selectors: ${selectors.join(", ")}. Direct MCP tools require a matching configured server and fresh metadata cache; runtime-registered servers require a host/pi-mcp-adapter handoff before child launch.`;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function getServerPrefix(serverName: string, mode: McpToolPrefix): string {
|
|
127
|
+
if (mode === "none") return "";
|
|
128
|
+
if (mode === "short") return serverName.replace(/-?mcp$/i, "") || "mcp";
|
|
129
|
+
return serverName;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
function formatToolName(toolName: string, serverName: string, prefix: McpToolPrefix): string {
|
|
133
|
+
const serverPrefix = getServerPrefix(serverName, prefix);
|
|
134
|
+
return serverPrefix ? `${serverPrefix}_${toolName}` : toolName;
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function isToolAllowed(
|
|
138
|
+
toolName: string,
|
|
139
|
+
serverName: string,
|
|
140
|
+
prefix: McpToolPrefix,
|
|
141
|
+
includeTools: readonly unknown[] | undefined,
|
|
142
|
+
excludeTools: readonly unknown[] | undefined,
|
|
143
|
+
): boolean {
|
|
144
|
+
const candidates = toolNameCandidates(toolName, serverName, prefix);
|
|
145
|
+
return (!Array.isArray(includeTools) || includeTools.length === 0 || matchesToolPatterns(candidates, includeTools))
|
|
146
|
+
&& !matchesToolPatterns(candidates, excludeTools);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function toolNameCandidates(toolName: string, serverName: string, prefix: McpToolPrefix): Set<string> {
|
|
150
|
+
return new Set([
|
|
151
|
+
toolName,
|
|
152
|
+
`mcp_${toolName}`,
|
|
153
|
+
formatToolName(toolName, serverName, prefix),
|
|
154
|
+
formatToolName(toolName, serverName, "server"),
|
|
155
|
+
formatToolName(toolName, serverName, "short"),
|
|
156
|
+
formatToolName(toolName, serverName, "none"),
|
|
157
|
+
]);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function matchesToolPatterns(candidates: ReadonlySet<string>, patterns: readonly unknown[] | undefined): boolean {
|
|
161
|
+
if (!Array.isArray(patterns) || patterns.length === 0) return false;
|
|
162
|
+
for (const pattern of patterns) {
|
|
163
|
+
if (typeof pattern !== "string") continue;
|
|
164
|
+
const normalizedPattern = normalizeToolName(pattern);
|
|
165
|
+
const matcher = normalizedPattern.includes("*") || normalizedPattern.includes("?")
|
|
166
|
+
? globToRegExp(normalizedPattern)
|
|
167
|
+
: undefined;
|
|
168
|
+
for (const candidate of candidates) {
|
|
169
|
+
const normalizedCandidate = normalizeToolName(candidate);
|
|
170
|
+
if (matcher ? matcher.test(normalizedCandidate) : normalizedCandidate === normalizedPattern) return true;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return false;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function globToRegExp(pattern: string): RegExp {
|
|
177
|
+
const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*").replace(/\?/g, ".");
|
|
178
|
+
return new RegExp(`^${escaped}$`);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function normalizeToolName(value: string): string {
|
|
182
|
+
return value.replace(/-/g, "_");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function resourceNameToToolName(name: string): string {
|
|
186
|
+
let result = name
|
|
187
|
+
.replace(/[^a-zA-Z0-9]/g, "_")
|
|
188
|
+
.replace(/_+/g, "_")
|
|
189
|
+
.replace(/^_+/, "")
|
|
190
|
+
.replace(/_+$/, "")
|
|
191
|
+
.toLowerCase();
|
|
192
|
+
if (!result || /^\d/.test(result)) result = `resource${result ? `_${result}` : ""}`;
|
|
193
|
+
return result;
|
|
194
|
+
}
|