@blackbelt-technology/pi-dashboard-apple-tools 0.7.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/.pi/skills/apple-tools/SKILL.md +8 -7
- package/README.md +16 -11
- package/package.json +9 -7
- package/src/bin/install.ts +4 -4
- package/src/client/index.tsx +60 -50
- package/src/env.ts +26 -76
- package/src/install.ts +38 -33
- package/src/server/index.ts +68 -109
- package/src/mcp-config.ts +0 -285
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: apple-tools
|
|
3
|
-
description: Reach Apple PIM data (Calendar, Contacts, Reminders, Messages, Location, Maps, Weather) from a pi session via iMCP + pi-
|
|
3
|
+
description: Reach Apple PIM data (Calendar, Contacts, Reminders, Messages, Location, Maps, Weather) from a pi session via iMCP + pi's built-in MCP on macOS. Use when the user asks to read/search their Apple Calendar, Contacts, Reminders, iMessages, current Location, Maps, or Weather. Does NOT cover Apple Mail — iMCP exposes no Mail service; use apple-mail-fast-export for email.
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# apple-tools (iMCP)
|
|
7
7
|
|
|
8
8
|
Access Apple personal-information-management data on **macOS** through
|
|
9
9
|
[iMCP](https://github.com/mattt/iMCP), a menu-bar app that brokers the OS
|
|
10
|
-
permission grants, reached over MCP by
|
|
10
|
+
permission grants, reached over MCP by pi's built-in MCP (pi ≥ 1.0.0).
|
|
11
11
|
|
|
12
12
|
## Reachable services (seven)
|
|
13
13
|
|
|
@@ -27,11 +27,12 @@ If the user asks to read, search, or summarize **Apple Mail / email**:
|
|
|
27
27
|
"Messages" satisfying an email request is a category error: Messages is
|
|
28
28
|
iMessage/SMS only.
|
|
29
29
|
|
|
30
|
-
## Access pattern — search then invoke via
|
|
30
|
+
## Access pattern — search then invoke via built-in MCP
|
|
31
31
|
|
|
32
|
-
The agent reaches iMCP tools through
|
|
33
|
-
server. Do **not** run `imcp-server` directly.
|
|
34
|
-
|
|
32
|
+
The agent reaches iMCP tools through pi's **built-in MCP**, not by spawning the
|
|
33
|
+
server. Do **not** run `imcp-server` directly. Tools appear as `mcp__iMCP__*`
|
|
34
|
+
(through `codemode`, or `tool_search` when the entry's `exposure` is
|
|
35
|
+
`deferred`). Search the available tools, then invoke.
|
|
35
36
|
|
|
36
37
|
## Provisioning check (run at load)
|
|
37
38
|
|
|
@@ -49,7 +50,7 @@ Terminal states mirror the CLI and the dashboard panel:
|
|
|
49
50
|
`READY_PENDING_GRANTS`.
|
|
50
51
|
|
|
51
52
|
`READY` is NOT one of them. It is a live-access result — reachable only by a
|
|
52
|
-
successful tool round-trip through
|
|
53
|
+
successful tool round-trip through pi's built-in MCP, never by the provisioning
|
|
53
54
|
traversal, which cannot know whether the TCC grants were given.
|
|
54
55
|
|
|
55
56
|
If the state is anything other than `READY_PENDING_GRANTS`, do NOT attempt
|
package/README.md
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
Provision and surface **iMCP** — Apple PIM (Calendar, Contacts, Reminders,
|
|
4
4
|
Messages, Location, Maps, Weather) — for a pi session on **macOS**, reached
|
|
5
|
-
through
|
|
5
|
+
through pi's **built-in MCP** (pi ≥ 1.0.0). No `pi-mcp-adapter`.
|
|
6
6
|
|
|
7
7
|
> **macOS only. No Apple Mail.** iMCP exposes no Mail service; "Messages" is
|
|
8
8
|
> iMessage/SMS, not email. For email use the `apple-mail-fast-export` skill.
|
|
@@ -12,12 +12,11 @@ through [`pi-mcp-adapter`](https://www.npmjs.com/package/pi-mcp-adapter).
|
|
|
12
12
|
Three moving parts must line up before a single Apple tool call works:
|
|
13
13
|
|
|
14
14
|
1. **iMCP.app installed** — `brew install --cask mattt/tap/iMCP`
|
|
15
|
-
2. **`
|
|
16
|
-
3.
|
|
17
|
-
4. **TCC grants** — **manual**, in the iMCP menu-bar app (Apple's security model
|
|
15
|
+
2. **`mcp.json` entry present** — `mcpServers.iMCP.command` in `~/.pi/agent/mcp.json`
|
|
16
|
+
3. **TCC grants** — **manual**, in the iMCP menu-bar app (Apple's security model
|
|
18
17
|
has no API; this step cannot be automated)
|
|
19
18
|
|
|
20
|
-
Steps 1–
|
|
19
|
+
Steps 1–2 are automated by this package. Step 3 is a documented manual click.
|
|
21
20
|
|
|
22
21
|
## Install
|
|
23
22
|
|
|
@@ -29,7 +28,7 @@ Installing the package does nothing on its own (no `postinstall`). Provisioning
|
|
|
29
28
|
is **opt-in**:
|
|
30
29
|
|
|
31
30
|
```bash
|
|
32
|
-
pi-apple-tools-install # provision (writes mcp.json
|
|
31
|
+
pi-apple-tools-install # provision (writes mcp.json only)
|
|
33
32
|
pi-apple-tools-install --check # report the state without changing anything
|
|
34
33
|
```
|
|
35
34
|
|
|
@@ -43,7 +42,8 @@ the `doctor` probe:
|
|
|
43
42
|
`CONFIG_WRITE_FAILED` · `READY_PENDING_GRANTS` · `READY`
|
|
44
43
|
|
|
45
44
|
`READY_PENDING_GRANTS` means everything is wired but you still need to grant
|
|
46
|
-
permissions in the iMCP menu-bar app.
|
|
45
|
+
permissions in the iMCP menu-bar app. `READY` is a live round trip through pi's
|
|
46
|
+
built-in MCP, never the provisioning traversal. Minimum macOS: **15.3**.
|
|
47
47
|
|
|
48
48
|
## Manual grant step
|
|
49
49
|
|
|
@@ -55,7 +55,12 @@ remediation**, not re-running the installer.
|
|
|
55
55
|
## Dashboard panel
|
|
56
56
|
|
|
57
57
|
The plugin contributes a settings section under its own row in the Plugins tab:
|
|
58
|
-
status readout, **Run installer**,
|
|
59
|
-
|
|
60
|
-
the
|
|
61
|
-
menu-bar only.
|
|
58
|
+
status readout (`exposure`, `enabled`), **Run installer**, and the
|
|
59
|
+
`imcp-server` path override. Server enable/disable and exposure live in the
|
|
60
|
+
**mcp-client** plugin (Settings → MCP); the panel links there. It has **no
|
|
61
|
+
per-service toggles** — those are menu-bar only.
|
|
62
|
+
|
|
63
|
+
iMCP tools are reached as `mcp__iMCP__*` per the entry's `exposure` (`codemode`
|
|
64
|
+
by default; `deferred` via `tool_search`). Operator-set `enabled` / `exposure` /
|
|
65
|
+
`toolExposure` and unknown keys are preserved on refresh; only `command` is
|
|
66
|
+
rewritten.
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@blackbelt-technology/pi-dashboard-apple-tools",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Provision and surface iMCP (Apple PIM: Calendar, Contacts, Reminders, Messages, Location, Maps, Weather) for pi. One-command installer, a dashboard provisioning panel, and an agent skill. macOS-only; no Apple Mail.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"publishConfig": {
|
|
@@ -44,6 +44,8 @@
|
|
|
44
44
|
"src/",
|
|
45
45
|
"config.schema.json",
|
|
46
46
|
".pi/",
|
|
47
|
+
"!**/AGENTS.md",
|
|
48
|
+
"!**/*.AGENTS.md",
|
|
47
49
|
"!**/__tests__",
|
|
48
50
|
"!**/*.test.ts",
|
|
49
51
|
"!**/*.test.tsx"
|
|
@@ -60,10 +62,10 @@
|
|
|
60
62
|
"client": "./src/client/index.tsx",
|
|
61
63
|
"server": "./src/server/index.ts",
|
|
62
64
|
"configSchema": "./config.schema.json",
|
|
65
|
+
"dependsOn": [
|
|
66
|
+
"mcp-client"
|
|
67
|
+
],
|
|
63
68
|
"requires": {
|
|
64
|
-
"piExtensions": [
|
|
65
|
-
"pi-mcp-adapter"
|
|
66
|
-
],
|
|
67
69
|
"paths": [
|
|
68
70
|
"${imcpServerPath}"
|
|
69
71
|
]
|
|
@@ -80,9 +82,9 @@
|
|
|
80
82
|
"react-dom": ">=18.0.0"
|
|
81
83
|
},
|
|
82
84
|
"dependencies": {
|
|
83
|
-
"@blackbelt-technology/dashboard-plugin-runtime": "^0.
|
|
84
|
-
"@blackbelt-technology/pi-dashboard-
|
|
85
|
-
"pi-
|
|
85
|
+
"@blackbelt-technology/dashboard-plugin-runtime": "^0.9.0",
|
|
86
|
+
"@blackbelt-technology/pi-dashboard-mcp-client-plugin": "^0.9.0",
|
|
87
|
+
"@blackbelt-technology/pi-dashboard-shared": "^0.9.0"
|
|
86
88
|
},
|
|
87
89
|
"devDependencies": {
|
|
88
90
|
"@types/react": "^19.0.0",
|
package/src/bin/install.ts
CHANGED
|
@@ -2,12 +2,12 @@
|
|
|
2
2
|
/**
|
|
3
3
|
* `pi-apple-tools-install [--check]` — opt-in CLI entry for iMCP provisioning.
|
|
4
4
|
*
|
|
5
|
-
* Never runs implicitly (no postinstall). Writes exactly
|
|
6
|
-
* mode (`~/.pi/agent/mcp.json
|
|
7
|
-
* the server-owned plugin config store. `--check` reports the terminal state
|
|
5
|
+
* Never runs implicitly (no postinstall). Writes exactly one file in write
|
|
6
|
+
* mode (`~/.pi/agent/mcp.json` — pi's built-in MCP config; never
|
|
7
|
+
* `settings.json`) and NEVER touches the server-owned plugin config store. `--check` reports the terminal state
|
|
8
8
|
* without mutating anything.
|
|
9
9
|
*
|
|
10
|
-
* See
|
|
10
|
+
* See changes: add-apple-tools-imcp-plugin, migrate-mcp-to-pi-builtin.
|
|
11
11
|
*/
|
|
12
12
|
import { createInstallerEnv } from "../env.js";
|
|
13
13
|
import { runInstaller } from "../install.js";
|
package/src/client/index.tsx
CHANGED
|
@@ -5,17 +5,24 @@
|
|
|
5
5
|
* Plugins tab (no `tab` field — per dashboard-plugin-loader spec it renders
|
|
6
6
|
* only under the owning plugin's row). A provisioning surface, NOT a service
|
|
7
7
|
* switchboard: it shows the shared checker's terminal state, offers
|
|
8
|
-
* [Run installer]
|
|
9
|
-
* enable/disable
|
|
10
|
-
* only, no API).
|
|
8
|
+
* [Run installer] and a path override, and links to the mcp-client plugin for
|
|
9
|
+
* server enable/disable + exposure (which live there). No per-Apple-service
|
|
10
|
+
* toggles (TCC is menu-bar only, no API).
|
|
11
11
|
*
|
|
12
|
-
*
|
|
12
|
+
* A missing `dependsOn: ["mcp-client"]` requirement renders a banner that hides
|
|
13
|
+
* [Run installer] — provisioning would refuse without the service.
|
|
14
|
+
*
|
|
15
|
+
* See changes: add-apple-tools-imcp-plugin (Decision 5), extract-mcp-client-plugin.
|
|
13
16
|
*/
|
|
14
17
|
import { usePluginConfig, usePluginSend } from "@blackbelt-technology/dashboard-plugin-runtime/context";
|
|
15
18
|
import { useEffect, useState } from "react";
|
|
16
19
|
|
|
17
20
|
const PLUGIN_ID = "apple-tools";
|
|
18
21
|
const DEFAULT_PATH = "/Applications/iMCP.app/Contents/MacOS/imcp-server";
|
|
22
|
+
/** The generic MCP server manager — where enable/disable + exposure live. */
|
|
23
|
+
const MANAGE_MCP_PATH = "/settings/plugins/mcp-client";
|
|
24
|
+
/** Plugins index — the missing-dependency banner's Enable affordance. */
|
|
25
|
+
const PLUGINS_INDEX_PATH = "/settings/plugins";
|
|
19
26
|
|
|
20
27
|
interface AppleToolsConfig {
|
|
21
28
|
imcpServerPath?: string;
|
|
@@ -27,34 +34,52 @@ interface StatusReadout {
|
|
|
27
34
|
message: string;
|
|
28
35
|
resolvedPath?: string;
|
|
29
36
|
imcpServerPath: string;
|
|
30
|
-
/** Adapter-owned, read server-side from ~/.pi/agent/mcp.json. */
|
|
31
|
-
directTools: string[];
|
|
32
|
-
disabled: boolean;
|
|
33
37
|
/** False when iMCP.app is absent — provisioning must go through the CLI. */
|
|
34
38
|
appPresent: boolean;
|
|
35
39
|
}
|
|
36
40
|
|
|
41
|
+
/**
|
|
42
|
+
* This plugin's own loader row `missingDeps` (a `dependsOn` gap). Fetched from
|
|
43
|
+
* `GET /api/plugins` because the server's row is the single source of truth for
|
|
44
|
+
* the dependency graph. A fetch failure leaves the list empty rather than
|
|
45
|
+
* blocking the panel.
|
|
46
|
+
*/
|
|
47
|
+
function useMissingDeps(): string[] {
|
|
48
|
+
const [missing, setMissing] = useState<string[]>([]);
|
|
49
|
+
useEffect(() => {
|
|
50
|
+
let alive = true;
|
|
51
|
+
void (async () => {
|
|
52
|
+
try {
|
|
53
|
+
const res = await fetch("/api/plugins");
|
|
54
|
+
if (!res.ok) return;
|
|
55
|
+
const body = (await res.json()) as {
|
|
56
|
+
plugins?: Array<{ id?: string; status?: { missingDeps?: string[] } | null }>;
|
|
57
|
+
};
|
|
58
|
+
const row = (body.plugins ?? []).find((p) => p.id === PLUGIN_ID);
|
|
59
|
+
if (alive) setMissing(row?.status?.missingDeps ?? []);
|
|
60
|
+
} catch {
|
|
61
|
+
/* leave empty */
|
|
62
|
+
}
|
|
63
|
+
})();
|
|
64
|
+
return () => {
|
|
65
|
+
alive = false;
|
|
66
|
+
};
|
|
67
|
+
}, []);
|
|
68
|
+
return missing;
|
|
69
|
+
}
|
|
70
|
+
|
|
37
71
|
export function AppleToolsSettings() {
|
|
38
72
|
const config = usePluginConfig<AppleToolsConfig>();
|
|
39
73
|
const send = usePluginSend();
|
|
40
74
|
const [status, setStatus] = useState<StatusReadout | null>(null);
|
|
41
75
|
const [fetchError, setFetchError] = useState<string | null>(null);
|
|
42
76
|
const [pathDraft, setPathDraft] = useState(config?.imcpServerPath ?? DEFAULT_PATH);
|
|
43
|
-
const
|
|
77
|
+
const missingDeps = useMissingDeps();
|
|
44
78
|
|
|
45
79
|
useEffect(() => {
|
|
46
80
|
setPathDraft(config?.imcpServerPath ?? DEFAULT_PATH);
|
|
47
81
|
}, [config?.imcpServerPath]);
|
|
48
82
|
|
|
49
|
-
// directTools + disabled live in ~/.pi/agent/mcp.json (adapter-owned), so the
|
|
50
|
-
// server status readout — not our plugin config — is their source of truth.
|
|
51
|
-
// Key on the VALUE, not the status object identity: re-seeding on every poll
|
|
52
|
-
// would wipe an edit the operator is still typing.
|
|
53
|
-
const serverDirectTools = status?.directTools.join(", ") ?? null;
|
|
54
|
-
useEffect(() => {
|
|
55
|
-
if (serverDirectTools !== null) setDirectToolsDraft(serverDirectTools);
|
|
56
|
-
}, [serverDirectTools]);
|
|
57
|
-
|
|
58
83
|
async function refresh(): Promise<void> {
|
|
59
84
|
try {
|
|
60
85
|
const res = await fetch(`/api/${PLUGIN_ID}/status`);
|
|
@@ -76,9 +101,6 @@ export function AppleToolsSettings() {
|
|
|
76
101
|
}, []);
|
|
77
102
|
|
|
78
103
|
const isMac = status ? status.platform === "darwin" : true;
|
|
79
|
-
const disabled = status?.disabled === true;
|
|
80
|
-
// #F11: disabled folds into the readout — never READY_PENDING_GRANTS + disabled simultaneously.
|
|
81
|
-
const displayState = disabled ? "DISABLED" : (status?.state ?? "…");
|
|
82
104
|
|
|
83
105
|
function saveConfig(partial: AppleToolsConfig): void {
|
|
84
106
|
void send({ type: "plugin_config_write", id: PLUGIN_ID, config: { ...config, ...partial } });
|
|
@@ -105,11 +127,21 @@ export function AppleToolsSettings() {
|
|
|
105
127
|
<span style={{ fontSize: "10px", color: "#71717a" }}>apple-tools</span>
|
|
106
128
|
</div>
|
|
107
129
|
|
|
130
|
+
{missingDeps.length > 0 && (
|
|
131
|
+
<p
|
|
132
|
+
data-testid="apple-tools-missing-deps"
|
|
133
|
+
style={{ fontSize: "11px", color: "#fbbf24", margin: "0 0 10px 0" }}
|
|
134
|
+
>
|
|
135
|
+
Missing dependency: <code>{missingDeps.join(", ")}</code>. Provisioning needs it.{" "}
|
|
136
|
+
<a href={PLUGINS_INDEX_PATH}>Enable it in Plugins</a> first.
|
|
137
|
+
</p>
|
|
138
|
+
)}
|
|
139
|
+
|
|
108
140
|
<div
|
|
109
141
|
data-testid="apple-tools-status"
|
|
110
142
|
style={{ fontSize: "12px", marginBottom: "8px", fontFamily: "monospace" }}
|
|
111
143
|
>
|
|
112
|
-
{
|
|
144
|
+
{status?.state ?? "…"}
|
|
113
145
|
</div>
|
|
114
146
|
{status?.message && (
|
|
115
147
|
<p style={{ fontSize: "11px", color: "#a1a1aa", margin: "0 0 10px 0" }}>{status.message}</p>
|
|
@@ -129,7 +161,7 @@ export function AppleToolsSettings() {
|
|
|
129
161
|
</p>
|
|
130
162
|
) : (
|
|
131
163
|
<>
|
|
132
|
-
{status && !status.appPresent ? (
|
|
164
|
+
{missingDeps.length > 0 ? null : status && !status.appPresent ? (
|
|
133
165
|
// The dashboard performs only the fast config-write half of
|
|
134
166
|
// provisioning; the long `brew install --cask` runs from the CLI so
|
|
135
167
|
// a click can never block the server. Tell the operator that here
|
|
@@ -162,34 +194,12 @@ export function AppleToolsSettings() {
|
|
|
162
194
|
/>
|
|
163
195
|
</label>
|
|
164
196
|
|
|
165
|
-
<
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
onBlur={() =>
|
|
172
|
-
act("set-direct-tools", {
|
|
173
|
-
tools: directToolsDraft
|
|
174
|
-
.split(",")
|
|
175
|
-
.map((s) => s.trim())
|
|
176
|
-
.filter(Boolean),
|
|
177
|
-
})
|
|
178
|
-
}
|
|
179
|
-
style={{ display: "block", width: "100%", fontSize: "11px" }}
|
|
180
|
-
/>
|
|
181
|
-
</label>
|
|
182
|
-
|
|
183
|
-
<label style={{ display: "flex", gap: "6px", alignItems: "center", fontSize: "11px" }}>
|
|
184
|
-
<input
|
|
185
|
-
data-testid="apple-tools-disabled"
|
|
186
|
-
type="checkbox"
|
|
187
|
-
checked={disabled}
|
|
188
|
-
onChange={(e) => act("set-disabled", { scope: "global", disabled: e.target.checked })}
|
|
189
|
-
/>
|
|
190
|
-
Disable the iMCP server globally (writes `disabled` to ~/.pi/agent/mcp.json; a project
|
|
191
|
-
can override this in its own .pi/mcp.json. Menu-bar grants are unaffected.)
|
|
192
|
-
</label>
|
|
197
|
+
<p style={{ fontSize: "11px", margin: "2px 0 10px 0" }}>
|
|
198
|
+
<a data-testid="apple-tools-manage-mcp" href={MANAGE_MCP_PATH}>
|
|
199
|
+
Manage MCP servers
|
|
200
|
+
</a>{" "}
|
|
201
|
+
— enable/disable iMCP and pick its direct tools there.
|
|
202
|
+
</p>
|
|
193
203
|
|
|
194
204
|
<p style={{ fontSize: "10px", color: "#71717a", marginTop: "10px" }}>
|
|
195
205
|
Apple service permissions (Calendar, Contacts, …) are granted only in the iMCP menu-bar
|
package/src/env.ts
CHANGED
|
@@ -3,30 +3,28 @@
|
|
|
3
3
|
* that touches the real OS — every probe and side effect is concentrated here
|
|
4
4
|
* so the state machine (`install.ts`) stays pure and Linux-testable.
|
|
5
5
|
*
|
|
6
|
+
* Config paths and the hardened atomic write live in the `mcp-client`
|
|
7
|
+
* plugin's `./core`: this factory only builds the `mcp-client.config` service
|
|
8
|
+
* with the real filesystem IO, so the target path is pi's built-in MCP file
|
|
9
|
+
* and honours `PI_CODING_AGENT_DIR` (a hard-coded `~/.pi/agent` would not).
|
|
10
|
+
* See change: migrate-mcp-to-pi-builtin (D4).
|
|
11
|
+
*
|
|
6
12
|
* Security discipline (see change: add-apple-tools-imcp-plugin, Decision 4):
|
|
7
13
|
* - `brew` is invoked with an argv array via execFileSync — never a shell,
|
|
8
14
|
* so no probed value (path, sw_vers output) can reach a shell string.
|
|
9
|
-
* - config writes are temp-file + atomic rename.
|
|
10
15
|
*/
|
|
11
16
|
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
closeSync,
|
|
15
|
-
existsSync,
|
|
16
|
-
fsyncSync,
|
|
17
|
-
mkdirSync,
|
|
18
|
-
openSync,
|
|
19
|
-
readFileSync,
|
|
20
|
-
renameSync,
|
|
21
|
-
unlinkSync,
|
|
22
|
-
writeSync,
|
|
23
|
-
} from "node:fs";
|
|
17
|
+
import { existsSync } from "node:fs";
|
|
24
18
|
import { homedir } from "node:os";
|
|
25
|
-
import {
|
|
19
|
+
import {
|
|
20
|
+
type ConfigIO,
|
|
21
|
+
createMcpClientConfigService,
|
|
22
|
+
createRealConfigIO,
|
|
23
|
+
type LayerPaths,
|
|
24
|
+
} from "@blackbelt-technology/pi-dashboard-mcp-client-plugin/core";
|
|
26
25
|
import { execFileSync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
27
26
|
import { IMCP_BREW_CASK } from "./detect.js";
|
|
28
27
|
import type { BrewResult, InstallerEnv } from "./install.js";
|
|
29
|
-
import type { ConfigIO } from "./mcp-config.js";
|
|
30
28
|
|
|
31
29
|
/** 10-minute cap on the brew cask install (design X4). */
|
|
32
30
|
export const BREW_TIMEOUT_MS = 10 * 60 * 1000;
|
|
@@ -68,79 +66,31 @@ function runBrewCask(brew: string): BrewResult {
|
|
|
68
66
|
}
|
|
69
67
|
}
|
|
70
68
|
|
|
71
|
-
/**
|
|
72
|
-
* Atomic write: temp file in the target dir, fsync, then rename over the
|
|
73
|
-
* destination. Hardened per the security pass:
|
|
74
|
-
* - `wx` + a random name: never follow or clobber a pre-planted symlink.
|
|
75
|
-
* - mode 0600: a rename carries the temp file's mode onto the destination, so
|
|
76
|
-
* a default-umask temp would silently widen a 0600 user config that may hold
|
|
77
|
-
* another server's credential `env` block.
|
|
78
|
-
* - fsync before rename: a rename over unflushed data can surface as a
|
|
79
|
-
* zero-length config after a crash — the truncation this exists to prevent.
|
|
80
|
-
* - unlink the temp on failure: no leftovers on ENOSPC/EACCES.
|
|
81
|
-
*/
|
|
82
|
-
function writeFileAtomic(path: string, content: string): void {
|
|
83
|
-
const dir = dirname(path);
|
|
84
|
-
mkdirSync(dir, { recursive: true });
|
|
85
|
-
const tmp = join(dir, `.${randomBytes(8).toString("hex")}.tmp`);
|
|
86
|
-
const fd = openSync(tmp, "wx", 0o600);
|
|
87
|
-
try {
|
|
88
|
-
// writeSync may perform a partial write; loop until the buffer is drained
|
|
89
|
-
// rather than assuming one call consumes it all.
|
|
90
|
-
const buf = Buffer.from(content, "utf8");
|
|
91
|
-
let off = 0;
|
|
92
|
-
while (off < buf.length) {
|
|
93
|
-
off += writeSync(fd, buf, off, buf.length - off);
|
|
94
|
-
}
|
|
95
|
-
fsyncSync(fd);
|
|
96
|
-
} catch (e) {
|
|
97
|
-
closeSync(fd);
|
|
98
|
-
try {
|
|
99
|
-
unlinkSync(tmp);
|
|
100
|
-
} catch {
|
|
101
|
-
/* best effort */
|
|
102
|
-
}
|
|
103
|
-
throw e;
|
|
104
|
-
}
|
|
105
|
-
closeSync(fd);
|
|
106
|
-
try {
|
|
107
|
-
renameSync(tmp, path);
|
|
108
|
-
} catch (e) {
|
|
109
|
-
try {
|
|
110
|
-
unlinkSync(tmp);
|
|
111
|
-
} catch {
|
|
112
|
-
/* best effort */
|
|
113
|
-
}
|
|
114
|
-
throw e;
|
|
115
|
-
}
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
const realConfigIO: ConfigIO = {
|
|
119
|
-
readFile: (p) => (existsSync(p) ? readFileSync(p, "utf8") : null),
|
|
120
|
-
writeFileAtomic,
|
|
121
|
-
};
|
|
122
|
-
|
|
123
69
|
export interface CreateEnvOptions {
|
|
124
70
|
/** Operator override for the imcp-server path. */
|
|
125
71
|
overridePath?: string;
|
|
126
|
-
/**
|
|
127
|
-
|
|
72
|
+
/** Test seam: inject config IO (defaults to the real filesystem). */
|
|
73
|
+
configIO?: ConfigIO;
|
|
74
|
+
/** Test seam: inject the layer paths (defaults to pi's built-in MCP paths). */
|
|
75
|
+
paths?: LayerPaths;
|
|
128
76
|
}
|
|
129
77
|
|
|
130
78
|
/** Build a real InstallerEnv wired to the current host. */
|
|
131
79
|
export function createInstallerEnv(opts: CreateEnvOptions = {}): InstallerEnv {
|
|
132
|
-
const home = homedir();
|
|
133
|
-
const agentHome = opts.piAgentHome ?? join(home, ".pi", "agent");
|
|
134
80
|
return {
|
|
135
81
|
platform: process.platform,
|
|
136
|
-
homedir:
|
|
82
|
+
homedir: homedir(),
|
|
137
83
|
probeOsVersion,
|
|
138
84
|
pathExists: existsSync,
|
|
139
85
|
brewPath,
|
|
140
86
|
runBrewCask,
|
|
141
87
|
...(opts.overridePath ? { overridePath: opts.overridePath } : {}),
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
88
|
+
// Global scope only — the CLI never writes a project layer, so the
|
|
89
|
+
// known-cwd admission set is empty.
|
|
90
|
+
mcps: createMcpClientConfigService({
|
|
91
|
+
configIO: opts.configIO ?? createRealConfigIO(),
|
|
92
|
+
knownCwds: () => [],
|
|
93
|
+
...(opts.paths ? { paths: opts.paths } : {}),
|
|
94
|
+
}),
|
|
145
95
|
};
|
|
146
|
-
}
|
|
96
|
+
}
|
package/src/install.ts
CHANGED
|
@@ -6,6 +6,10 @@
|
|
|
6
6
|
*
|
|
7
7
|
* See change: add-apple-tools-imcp-plugin (Decision 2).
|
|
8
8
|
*/
|
|
9
|
+
import type {
|
|
10
|
+
ConfigRefusal,
|
|
11
|
+
McpClientConfigService,
|
|
12
|
+
} from "@blackbelt-technology/pi-dashboard-mcp-client-plugin/core";
|
|
9
13
|
import {
|
|
10
14
|
discoverServer,
|
|
11
15
|
IMCP_BREW_CASK,
|
|
@@ -14,13 +18,6 @@ import {
|
|
|
14
18
|
MIN_MACOS,
|
|
15
19
|
meetsMinimum,
|
|
16
20
|
} from "./detect.js";
|
|
17
|
-
import {
|
|
18
|
-
type ConfigIO,
|
|
19
|
-
type ConfigWriteResult,
|
|
20
|
-
ensureAdapterPackage,
|
|
21
|
-
ensureMcpEntry,
|
|
22
|
-
validateConfigShape,
|
|
23
|
-
} from "./mcp-config.js";
|
|
24
21
|
|
|
25
22
|
/** Closed, nine-member terminal-state enum. All three surfaces render these. */
|
|
26
23
|
export type TerminalState =
|
|
@@ -67,12 +64,12 @@ export interface InstallerEnv {
|
|
|
67
64
|
runBrewCask: (brew: string) => BrewResult;
|
|
68
65
|
/** Operator override for the imcp-server path (`imcpServerPath` config key). */
|
|
69
66
|
overridePath?: string;
|
|
70
|
-
/**
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
67
|
+
/**
|
|
68
|
+
* The `mcp-client.config` service. Owns every target path (honouring
|
|
69
|
+
* `PI_CODING_AGENT_DIR`) and the hardened atomic write, so this module needs
|
|
70
|
+
* no `ConfigIO` / hard-coded `~/.pi/agent` paths of its own.
|
|
71
|
+
*/
|
|
72
|
+
mcps: McpClientConfigService;
|
|
76
73
|
}
|
|
77
74
|
|
|
78
75
|
export interface InstallResult {
|
|
@@ -186,18 +183,21 @@ export function runInstaller(env: InstallerEnv, opts: RunOptions = {}): InstallR
|
|
|
186
183
|
|
|
187
184
|
// 5. Config writes (suppressed in check mode).
|
|
188
185
|
if (!check) {
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
186
|
+
// Merge-only: `command` is refreshed; operator-set `enabled` / `exposure`
|
|
187
|
+
// / `toolExposure` survive. pi's built-in MCP needs no package entry, so
|
|
188
|
+
// `settings.json` is never touched (a `pi-mcp-adapter` package entry would
|
|
189
|
+
// DISABLE the built-in). See change: migrate-mcp-to-pi-builtin (D4).
|
|
190
|
+
const mcp = env.mcps.ensureServerEntry("iMCP", { command: resolved }, { kind: "global" });
|
|
191
|
+
if (!mcp.ok) return relayConfigFailure(mcp.refusal);
|
|
193
192
|
} else {
|
|
194
|
-
// Predict a config failure the write would hit (unparseable existing file
|
|
195
|
-
|
|
193
|
+
// Predict a config failure the write would hit (unparseable existing file
|
|
194
|
+
// or a malformed post-patch entry).
|
|
195
|
+
const predicted = predictConfigWritability(env, resolved);
|
|
196
196
|
if (predicted) return predicted;
|
|
197
197
|
}
|
|
198
198
|
|
|
199
|
-
// 6. Terminal success. The installer never claims READY — only a live
|
|
200
|
-
// round-trip (a granted tool call) can distinguish READY from pending.
|
|
199
|
+
// 6. Terminal success. The installer never claims READY — only a live
|
|
200
|
+
// round-trip through pi's built-in MCP (a granted tool call) can distinguish READY from pending.
|
|
201
201
|
//
|
|
202
202
|
// In check mode with the app absent, `state` is a PREDICTION of what a
|
|
203
203
|
// write run would reach. Reporting it as "provisioned", or naming the
|
|
@@ -224,21 +224,26 @@ export function runInstaller(env: InstallerEnv, opts: RunOptions = {}): InstallR
|
|
|
224
224
|
};
|
|
225
225
|
}
|
|
226
226
|
|
|
227
|
-
function relayConfigFailure(r:
|
|
228
|
-
|
|
227
|
+
function relayConfigFailure(r: ConfigRefusal): InstallResult {
|
|
228
|
+
// The 9-member TerminalState enum is unchanged: a write IO fault is
|
|
229
|
+
// CONFIG_WRITE_FAILED, every structural refusal (unparseable, entry-not-object,
|
|
230
|
+
// invalid-name, transport-conflict) is CONFIG_UNPARSEABLE.
|
|
231
|
+
return fail(r.code === "write-failed" ? "CONFIG_WRITE_FAILED" : "CONFIG_UNPARSEABLE", r.message);
|
|
229
232
|
}
|
|
230
233
|
|
|
231
234
|
/**
|
|
232
|
-
* Check-mode dry predicate. Delegates to the
|
|
233
|
-
*
|
|
234
|
-
*
|
|
235
|
-
*
|
|
236
|
-
* (EACCES/ENOSPC) remain unpredictable without attempting a write.
|
|
235
|
+
* Check-mode dry predicate. Delegates to the service's own check path so check
|
|
236
|
+
* and write agree: a config the write would refuse must never be reported as
|
|
237
|
+
* healthy by `--check`. Write-permission failures (EACCES/ENOSPC) remain
|
|
238
|
+
* unpredictable without attempting a write.
|
|
237
239
|
*/
|
|
238
|
-
function predictConfigWritability(env: InstallerEnv): InstallResult | null {
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
240
|
+
function predictConfigWritability(env: InstallerEnv, resolvedPath: string): InstallResult | null {
|
|
241
|
+
const status = env.mcps.checkConfigFiles({
|
|
242
|
+
serverName: "iMCP",
|
|
243
|
+
fields: { command: resolvedPath },
|
|
244
|
+
});
|
|
245
|
+
if (!status.mcpJson.ok) {
|
|
246
|
+
return fail("CONFIG_UNPARSEABLE", status.mcpJson.message ?? "mcp.json would be refused");
|
|
247
|
+
}
|
|
243
248
|
return null;
|
|
244
249
|
}
|
package/src/server/index.ts
CHANGED
|
@@ -2,22 +2,29 @@
|
|
|
2
2
|
* apple-tools · SERVER entry.
|
|
3
3
|
*
|
|
4
4
|
* Exposes the iMCP provisioning state (shared write-suppressed checker) and the
|
|
5
|
-
* run-installer action to the dashboard.
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
5
|
+
* run-installer action to the dashboard. Consumes the `mcp-client.config`
|
|
6
|
+
* service provided by the `mcp-client` plugin (declared via `dependsOn`) for
|
|
7
|
+
* the mcp.json readout; owns reconciliation of a discovered non-default path
|
|
8
|
+
* into the server-owned plugin config store (Decision 1).
|
|
9
9
|
*
|
|
10
|
-
*
|
|
10
|
+
* The MCP server enable/disable + exposure controls live in the mcp-client
|
|
11
|
+
* plugin's own generic surface; this plugin no longer writes mcp.json.
|
|
12
|
+
*
|
|
13
|
+
* See changes: add-apple-tools-imcp-plugin, extract-mcp-client-plugin,
|
|
14
|
+
* migrate-mcp-to-pi-builtin.
|
|
11
15
|
*/
|
|
12
|
-
import { join } from "node:path";
|
|
13
16
|
import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
|
|
17
|
+
import {
|
|
18
|
+
displayExposure,
|
|
19
|
+
type McpClientConfigService,
|
|
20
|
+
} from "@blackbelt-technology/pi-dashboard-mcp-client-plugin/core";
|
|
14
21
|
import { createInstallerEnv } from "../env.js";
|
|
15
22
|
import { runInstaller, type TerminalState } from "../install.js";
|
|
16
|
-
import { readImcpEntry, setDirectTools, setServerDisabled } from "../mcp-config.js";
|
|
17
23
|
import { DEFAULT_IMCP_PATH, shouldReconcilePath } from "../reconcile.js";
|
|
18
24
|
|
|
19
25
|
const PLUGIN_ID = "apple-tools";
|
|
20
|
-
|
|
26
|
+
/** The service key the `mcp-client` plugin provides. */
|
|
27
|
+
const SERVICE_KEY = "mcp-client.config";
|
|
21
28
|
/** Status readout TTL — the traversal shells out to `sw_vers`/`which`, so a
|
|
22
29
|
* polling panel must not re-run it per request. Mirrors the 30s requirement-
|
|
23
30
|
* probe cache. */
|
|
@@ -34,12 +41,12 @@ interface StatusReadout {
|
|
|
34
41
|
resolvedPath?: string;
|
|
35
42
|
imcpServerPath: string;
|
|
36
43
|
/**
|
|
37
|
-
*
|
|
38
|
-
*
|
|
39
|
-
*
|
|
44
|
+
* pi built-in MCP fields of the iMCP entry, read from the Pi-global
|
|
45
|
+
* `mcp.json` through the mcp-client service (the source of truth) rather
|
|
46
|
+
* than our plugin config. `exposure` is the display value (default codemode).
|
|
40
47
|
*/
|
|
41
|
-
|
|
42
|
-
|
|
48
|
+
exposure: string;
|
|
49
|
+
enabled: boolean;
|
|
43
50
|
/**
|
|
44
51
|
* True when iMCP.app is actually on disk. The dashboard can only perform the
|
|
45
52
|
* fast config-write half of provisioning; when this is false the operator
|
|
@@ -52,18 +59,14 @@ interface StatusReadout {
|
|
|
52
59
|
export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
53
60
|
ctx.logger.info("apple-tools server entry activated");
|
|
54
61
|
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
.filter((c): c is string => typeof c === "string" && c.length > 0);
|
|
64
|
-
};
|
|
65
|
-
const isAllowedCwd = (cwd: string | undefined): cwd is string =>
|
|
66
|
-
typeof cwd === "string" && cwd.length > 0 && knownCwds().includes(cwd);
|
|
62
|
+
const consumed = ctx.consume<McpClientConfigService>(SERVICE_KEY);
|
|
63
|
+
if (!consumed) {
|
|
64
|
+
throw new Error(
|
|
65
|
+
"apple-tools requires the `mcp-client.config` service (plugin id `mcp-client`); " +
|
|
66
|
+
"ensure it is enabled and loaded before apple-tools (`dependsOn: [\"mcp-client\"]`).",
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
const mcpClient: McpClientConfigService = consumed;
|
|
67
70
|
|
|
68
71
|
let statusCache: { at: number; value: StatusReadout } | null = null;
|
|
69
72
|
|
|
@@ -74,15 +77,16 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
|
74
77
|
...(configured ? { overridePath: configured } : {}),
|
|
75
78
|
});
|
|
76
79
|
const result = runInstaller(env, { check: true });
|
|
77
|
-
const entry =
|
|
80
|
+
const entry = mcpClient.readServerEntry("iMCP", { kind: "global" });
|
|
78
81
|
return {
|
|
79
82
|
platform: env.platform,
|
|
80
83
|
state: result.state,
|
|
81
84
|
message: result.message,
|
|
82
85
|
...(result.resolvedPath ? { resolvedPath: result.resolvedPath } : {}),
|
|
83
86
|
imcpServerPath: configured ?? DEFAULT_IMCP_PATH,
|
|
84
|
-
|
|
85
|
-
|
|
87
|
+
exposure: displayExposure(entry?.exposure),
|
|
88
|
+
// pi: only a literal `enabled: false` disables.
|
|
89
|
+
enabled: entry?.enabled !== false,
|
|
86
90
|
// Reported by the traversal itself: false when the state is a prediction.
|
|
87
91
|
appPresent: result.appPresent,
|
|
88
92
|
};
|
|
@@ -109,91 +113,46 @@ export async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
|
|
|
109
113
|
// run-installer action instead.
|
|
110
114
|
ctx.fastify.get(`/api/${PLUGIN_ID}/status`, async () => cachedStatus());
|
|
111
115
|
|
|
112
|
-
// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: flat action switch.
|
|
113
116
|
ctx.registerBrowserHandler("plugin_action", (msg) => {
|
|
114
117
|
const m = msg as { pluginId?: string; action?: string; payload?: Record<string, unknown> };
|
|
115
118
|
if (m.pluginId !== PLUGIN_ID) return;
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
}
|
|
143
|
-
const result = runInstaller(env, { check: false });
|
|
144
|
-
ctx.logger.info(`apple-tools run-installer → ${result.state}`);
|
|
145
|
-
statusCache = null; // invalidate on mutation (#F7)
|
|
146
|
-
// Pass only what reconcile reads. Calling cachedStatus() here would
|
|
147
|
-
// miss the just-cleared cache, run a THIRD sync traversal (sw_vers +
|
|
148
|
-
// which) on the event loop, discard the result, and re-seed the cache
|
|
149
|
-
// with a pre-reconcile readout served for the next 10s.
|
|
150
|
-
reconcile(result.resolvedPath).catch((e) =>
|
|
151
|
-
ctx.logger.warn(`apple-tools reconcile failed: ${(e as Error).message}`),
|
|
152
|
-
);
|
|
153
|
-
break;
|
|
154
|
-
}
|
|
155
|
-
case "set-disabled": {
|
|
156
|
-
// Enable/disable the iMCP server. BOTH levels are supported:
|
|
157
|
-
// scope "global" → ~/.pi/agent/mcp.json (default; the global panel)
|
|
158
|
-
// scope "project" → <cwd>/.pi/mcp.json (highest-precedence override)
|
|
159
|
-
const payload = m.payload ?? {};
|
|
160
|
-
const disabled = payload.disabled === true;
|
|
161
|
-
const scope = payload.scope === "project" ? "project" : "global";
|
|
162
|
-
const env = createInstallerEnv();
|
|
163
|
-
let target: string;
|
|
164
|
-
if (scope === "project") {
|
|
165
|
-
const cwd = typeof payload.cwd === "string" ? payload.cwd : undefined;
|
|
166
|
-
// Browser-supplied write path — it MUST be a known folder cwd, else
|
|
167
|
-
// this is an arbitrary mkdir -p + file write as the server user.
|
|
168
|
-
if (!isAllowedCwd(cwd)) {
|
|
169
|
-
ctx.logger.warn(`apple-tools set-disabled: cwd not allowed (${cwd ?? "missing"})`);
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
target = join(cwd, ".pi", "mcp.json");
|
|
173
|
-
} else {
|
|
174
|
-
target = env.mcpJsonPath;
|
|
175
|
-
}
|
|
176
|
-
const r = setServerDisabled(env.configIO, target, disabled);
|
|
177
|
-
if (!r.ok) ctx.logger.warn(`apple-tools set-disabled failed: ${r.message}`);
|
|
178
|
-
else ctx.logger.info(`apple-tools set-disabled scope=${scope} disabled=${disabled}`);
|
|
179
|
-
statusCache = null;
|
|
180
|
-
break;
|
|
181
|
-
}
|
|
182
|
-
case "set-direct-tools": {
|
|
183
|
-
// Adapter-owned per-server `directTools` filter on the global entry.
|
|
184
|
-
const payload = m.payload ?? {};
|
|
185
|
-
const tools = Array.isArray(payload.tools)
|
|
186
|
-
? (payload.tools as unknown[]).filter((t): t is string => typeof t === "string")
|
|
187
|
-
: [];
|
|
188
|
-
const env = createInstallerEnv();
|
|
189
|
-
const r = setDirectTools(env.configIO, env.mcpJsonPath, tools);
|
|
190
|
-
if (!r.ok) ctx.logger.warn(`apple-tools set-direct-tools failed: ${r.message}`);
|
|
191
|
-
statusCache = null;
|
|
192
|
-
break;
|
|
193
|
-
}
|
|
194
|
-
default:
|
|
195
|
-
break;
|
|
119
|
+
if (m.action !== "run-installer") return;
|
|
120
|
+
|
|
121
|
+
const cfg = ctx.getPluginConfig<AppleToolsConfig>() ?? {};
|
|
122
|
+
const env = createInstallerEnv({
|
|
123
|
+
...(cfg.imcpServerPath ? { overridePath: cfg.imcpServerPath } : {}),
|
|
124
|
+
});
|
|
125
|
+
// The state machine is synchronous by design (pure + unit-testable).
|
|
126
|
+
// Running its INSTALL branch here would `execFileSync(brew, …)` with a
|
|
127
|
+
// 10-minute timeout on the Fastify event loop, freezing every session's
|
|
128
|
+
// WebSocket and every other plugin's HTTP for the duration.
|
|
129
|
+
//
|
|
130
|
+
// So the server only ever performs the FAST half of provisioning (the
|
|
131
|
+
// two config writes, which run when iMCP is already on disk). When the
|
|
132
|
+
// app is absent — the only branch that shells out to brew — it refuses
|
|
133
|
+
// and directs the operator to the CLI, which owns the long, network-
|
|
134
|
+
// bound install. See the security/perf review of this change.
|
|
135
|
+
const probe = runInstaller(env, { check: true });
|
|
136
|
+
if (!probe.appPresent) {
|
|
137
|
+
// The panel reads `appPresent` from the status readout and renders the
|
|
138
|
+
// CLI instruction instead of the button, so this is defence in depth.
|
|
139
|
+
ctx.logger.warn(
|
|
140
|
+
"apple-tools run-installer: iMCP is not installed. Run `pi-apple-tools-install` " +
|
|
141
|
+
"in a terminal — the dashboard does not run `brew` in-process.",
|
|
142
|
+
);
|
|
143
|
+
statusCache = null;
|
|
144
|
+
return;
|
|
196
145
|
}
|
|
146
|
+
const result = runInstaller(env, { check: false });
|
|
147
|
+
ctx.logger.info(`apple-tools run-installer → ${result.state}`);
|
|
148
|
+
statusCache = null; // invalidate on mutation (#F7)
|
|
149
|
+
// Pass only what reconcile reads. Calling cachedStatus() here would
|
|
150
|
+
// miss the just-cleared cache, run a THIRD sync traversal (sw_vers +
|
|
151
|
+
// which) on the event loop, discard the result, and re-seed the cache
|
|
152
|
+
// with a pre-reconcile readout served for the next 10s.
|
|
153
|
+
reconcile(result.resolvedPath).catch((e) =>
|
|
154
|
+
ctx.logger.warn(`apple-tools reconcile failed: ${(e as Error).message}`),
|
|
155
|
+
);
|
|
197
156
|
});
|
|
198
157
|
}
|
|
199
158
|
|
package/src/mcp-config.ts
DELETED
|
@@ -1,285 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Merge-only, atomic config writers for the two user-owned files the installer
|
|
3
|
-
* touches: `~/.pi/agent/mcp.json` (the `mcpServers.iMCP` entry) and
|
|
4
|
-
* `~/.pi/agent/settings.json` (the `packages[]` adapter entry).
|
|
5
|
-
*
|
|
6
|
-
* Discipline (see change: add-apple-tools-imcp-plugin, Decision 4):
|
|
7
|
-
* - read → deep-merge exactly one key → write. Never clobber siblings.
|
|
8
|
-
* - refuse to write a present-but-unparseable file (surface, don't "fix").
|
|
9
|
-
* - write via temp-file + atomic rename; never leave a truncated config.
|
|
10
|
-
* - never interpolate any probed value into a shell string.
|
|
11
|
-
*
|
|
12
|
-
* All filesystem access is injected (`ConfigIO`) so the suite runs on Linux CI
|
|
13
|
-
* without touching real user config.
|
|
14
|
-
*/
|
|
15
|
-
import { sourcesMatch } from "@blackbelt-technology/pi-dashboard-shared/source-matching.js";
|
|
16
|
-
|
|
17
|
-
/** Injected filesystem surface. `readFile` returns null when the file is absent. */
|
|
18
|
-
export interface ConfigIO {
|
|
19
|
-
readFile: (path: string) => string | null;
|
|
20
|
-
/** Atomic write (temp-file + rename). Throws an Error whose `.code` may be EACCES/ENOSPC. */
|
|
21
|
-
writeFileAtomic: (path: string, content: string) => void;
|
|
22
|
-
}
|
|
23
|
-
|
|
24
|
-
/** Outcome of a config write; `state` is set only on a terminal failure. */
|
|
25
|
-
export type ConfigWriteResult =
|
|
26
|
-
| { ok: true }
|
|
27
|
-
| { ok: false; state: "CONFIG_UNPARSEABLE" | "CONFIG_WRITE_FAILED"; message: string };
|
|
28
|
-
|
|
29
|
-
/** The npm source string appended to settings.json packages[] for the adapter. */
|
|
30
|
-
export const ADAPTER_PACKAGE_SOURCE = "npm:pi-mcp-adapter";
|
|
31
|
-
|
|
32
|
-
function parseOrError(
|
|
33
|
-
io: ConfigIO,
|
|
34
|
-
path: string,
|
|
35
|
-
): { parsed: Record<string, unknown> } | { error: ConfigWriteResult } {
|
|
36
|
-
const raw = io.readFile(path);
|
|
37
|
-
if (raw === null || raw.trim() === "") return { parsed: {} };
|
|
38
|
-
try {
|
|
39
|
-
const val = JSON.parse(raw);
|
|
40
|
-
if (val === null || typeof val !== "object" || Array.isArray(val)) {
|
|
41
|
-
return {
|
|
42
|
-
error: {
|
|
43
|
-
ok: false,
|
|
44
|
-
state: "CONFIG_UNPARSEABLE",
|
|
45
|
-
message: `${path} is not a JSON object`,
|
|
46
|
-
},
|
|
47
|
-
};
|
|
48
|
-
}
|
|
49
|
-
return { parsed: val as Record<string, unknown> };
|
|
50
|
-
} catch (e) {
|
|
51
|
-
return {
|
|
52
|
-
error: {
|
|
53
|
-
ok: false,
|
|
54
|
-
state: "CONFIG_UNPARSEABLE",
|
|
55
|
-
message: `${path} contains invalid JSON: ${(e as Error).message}`,
|
|
56
|
-
},
|
|
57
|
-
};
|
|
58
|
-
}
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Read `mcpServers` as an object. A present-but-wrong-typed value (array,
|
|
63
|
-
* string) is refused rather than coerced to `{}` — coercing would silently
|
|
64
|
-
* drop the user's data on the next write.
|
|
65
|
-
*/
|
|
66
|
-
function readServers(
|
|
67
|
-
config: Record<string, unknown>,
|
|
68
|
-
path: string,
|
|
69
|
-
): { servers: Record<string, unknown> } | { error: ConfigWriteResult } {
|
|
70
|
-
const raw = config.mcpServers;
|
|
71
|
-
if (raw === undefined) return { servers: {} };
|
|
72
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
73
|
-
return {
|
|
74
|
-
error: {
|
|
75
|
-
ok: false,
|
|
76
|
-
state: "CONFIG_UNPARSEABLE",
|
|
77
|
-
message: `${path}: "mcpServers" must be an object`,
|
|
78
|
-
},
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
|
-
return { servers: raw as Record<string, unknown> };
|
|
82
|
-
}
|
|
83
|
-
|
|
84
|
-
/**
|
|
85
|
-
* Read the existing `mcpServers.iMCP` entry. A present-but-wrong-typed value
|
|
86
|
-
* (scalar, null, array) is REFUSED rather than coerced to `{}` — coercing would
|
|
87
|
-
* destroy the operator's parseable value on the next write.
|
|
88
|
-
*/
|
|
89
|
-
function readExistingImcp(
|
|
90
|
-
servers: Record<string, unknown>,
|
|
91
|
-
path: string,
|
|
92
|
-
): { existing: Record<string, unknown> } | { error: ConfigWriteResult } {
|
|
93
|
-
const raw = servers.iMCP;
|
|
94
|
-
if (raw === undefined) return { existing: {} };
|
|
95
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
|
|
96
|
-
return {
|
|
97
|
-
error: {
|
|
98
|
-
ok: false,
|
|
99
|
-
state: "CONFIG_UNPARSEABLE",
|
|
100
|
-
message: `${path}: "mcpServers.iMCP" must be an object`,
|
|
101
|
-
},
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
return { existing: raw as Record<string, unknown> };
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
function writeOrError(io: ConfigIO, path: string, obj: unknown): ConfigWriteResult {
|
|
108
|
-
try {
|
|
109
|
-
io.writeFileAtomic(path, `${JSON.stringify(obj, null, 2)}\n`);
|
|
110
|
-
return { ok: true };
|
|
111
|
-
} catch (e) {
|
|
112
|
-
return {
|
|
113
|
-
ok: false,
|
|
114
|
-
state: "CONFIG_WRITE_FAILED",
|
|
115
|
-
message: `failed to write ${path}: ${(e as Error).message}`,
|
|
116
|
-
};
|
|
117
|
-
}
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
/**
|
|
121
|
-
* Ensure `mcpServers.iMCP = { command: <imcpServerPath> }` in mcp.json,
|
|
122
|
-
* preserving every other server and unknown top-level key. imcp-server is a
|
|
123
|
-
* stdio server that takes no args — `command` alone is the full contract
|
|
124
|
-
* (verified against pi-mcp-adapter's documented mcpServers shape).
|
|
125
|
-
*/
|
|
126
|
-
export function ensureMcpEntry(
|
|
127
|
-
io: ConfigIO,
|
|
128
|
-
mcpJsonPath: string,
|
|
129
|
-
imcpServerPath: string,
|
|
130
|
-
): ConfigWriteResult {
|
|
131
|
-
const r = parseOrError(io, mcpJsonPath);
|
|
132
|
-
if ("error" in r) return r.error;
|
|
133
|
-
const config = r.parsed;
|
|
134
|
-
const sr = readServers(config, mcpJsonPath);
|
|
135
|
-
if ("error" in sr) return sr.error;
|
|
136
|
-
const { servers } = sr;
|
|
137
|
-
const er = readExistingImcp(servers, mcpJsonPath);
|
|
138
|
-
if ("error" in er) return er.error;
|
|
139
|
-
const { existing } = er;
|
|
140
|
-
// Merge-only: preserve any operator-added fields on the iMCP entry (e.g. a
|
|
141
|
-
// `disabled` flag), overriding just `command` with the re-discovered path.
|
|
142
|
-
const merged = { ...existing, command: imcpServerPath };
|
|
143
|
-
const next = { ...config, mcpServers: { ...servers, iMCP: merged } };
|
|
144
|
-
return writeOrError(io, mcpJsonPath, next);
|
|
145
|
-
}
|
|
146
|
-
|
|
147
|
-
/**
|
|
148
|
-
* Append the adapter to settings.json `packages[]` if absent. Presence is
|
|
149
|
-
* detected with the cross-kind `sourcesMatch()` (npm ↔ git ↔ raw), so a
|
|
150
|
-
* user who installed pi-mcp-adapter from git receives no duplicate npm entry.
|
|
151
|
-
* Never reorders or removes existing entries.
|
|
152
|
-
*/
|
|
153
|
-
export function ensureAdapterPackage(io: ConfigIO, settingsJsonPath: string): ConfigWriteResult {
|
|
154
|
-
const r = parseOrError(io, settingsJsonPath);
|
|
155
|
-
if ("error" in r) return r.error;
|
|
156
|
-
const config = r.parsed;
|
|
157
|
-
if (config.packages !== undefined && !Array.isArray(config.packages)) {
|
|
158
|
-
return {
|
|
159
|
-
ok: false,
|
|
160
|
-
state: "CONFIG_UNPARSEABLE",
|
|
161
|
-
message: `${settingsJsonPath}: "packages" must be an array`,
|
|
162
|
-
};
|
|
163
|
-
}
|
|
164
|
-
const packages = Array.isArray(config.packages) ? (config.packages as unknown[]) : [];
|
|
165
|
-
const already = packages.some(
|
|
166
|
-
(p) => typeof p === "string" && sourcesMatch(p, ADAPTER_PACKAGE_SOURCE),
|
|
167
|
-
);
|
|
168
|
-
if (already) return { ok: true };
|
|
169
|
-
const next = { ...config, packages: [...packages, ADAPTER_PACKAGE_SOURCE] };
|
|
170
|
-
return writeOrError(io, settingsJsonPath, next);
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
/**
|
|
174
|
-
* Read-only structural validation of a config file, using the SAME rules the
|
|
175
|
-
* writers enforce. Check mode calls this so `--check` can never report a
|
|
176
|
-
* healthy state that write mode would fail on (parity: invalid JSON, non-object
|
|
177
|
-
* root, malformed `mcpServers` / `mcpServers.iMCP` / `packages`).
|
|
178
|
-
* Returns null when the file would be writable.
|
|
179
|
-
*/
|
|
180
|
-
export function validateConfigShape(
|
|
181
|
-
io: ConfigIO,
|
|
182
|
-
path: string,
|
|
183
|
-
kind: "mcp" | "settings",
|
|
184
|
-
): Extract<ConfigWriteResult, { ok: false }> | null {
|
|
185
|
-
const r = parseOrError(io, path);
|
|
186
|
-
if ("error" in r) return r.error as Extract<ConfigWriteResult, { ok: false }>;
|
|
187
|
-
if (kind === "mcp") {
|
|
188
|
-
const sr = readServers(r.parsed, path);
|
|
189
|
-
if ("error" in sr) return sr.error as Extract<ConfigWriteResult, { ok: false }>;
|
|
190
|
-
const er = readExistingImcp(sr.servers, path);
|
|
191
|
-
if ("error" in er) return er.error as Extract<ConfigWriteResult, { ok: false }>;
|
|
192
|
-
} else if (r.parsed.packages !== undefined && !Array.isArray(r.parsed.packages)) {
|
|
193
|
-
return {
|
|
194
|
-
ok: false,
|
|
195
|
-
state: "CONFIG_UNPARSEABLE",
|
|
196
|
-
message: `${path}: "packages" must be an array`,
|
|
197
|
-
};
|
|
198
|
-
}
|
|
199
|
-
return null;
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
/** Read the iMCP entry's operator-facing fields from a given mcp.json layer. */
|
|
203
|
-
export function readImcpEntry(
|
|
204
|
-
io: ConfigIO,
|
|
205
|
-
mcpJsonPath: string,
|
|
206
|
-
): { disabled: boolean; directTools: string[] } {
|
|
207
|
-
const r = parseOrError(io, mcpJsonPath);
|
|
208
|
-
if ("error" in r) return { disabled: false, directTools: [] };
|
|
209
|
-
const servers = r.parsed.mcpServers;
|
|
210
|
-
if (!servers || typeof servers !== "object" || Array.isArray(servers)) {
|
|
211
|
-
return { disabled: false, directTools: [] };
|
|
212
|
-
}
|
|
213
|
-
const entry = (servers as Record<string, unknown>).iMCP;
|
|
214
|
-
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
|
|
215
|
-
return { disabled: false, directTools: [] };
|
|
216
|
-
}
|
|
217
|
-
const e = entry as Record<string, unknown>;
|
|
218
|
-
return {
|
|
219
|
-
// pi-mcp-adapter's isServerDisabled: only a literal `true` disables.
|
|
220
|
-
disabled: e.disabled === true,
|
|
221
|
-
directTools: Array.isArray(e.directTools)
|
|
222
|
-
? (e.directTools as unknown[]).filter((t): t is string => typeof t === "string")
|
|
223
|
-
: [],
|
|
224
|
-
};
|
|
225
|
-
}
|
|
226
|
-
|
|
227
|
-
/** Merge a patch into `mcpServers.iMCP`; an `undefined` value removes the key. */
|
|
228
|
-
function patchImcpEntry(
|
|
229
|
-
io: ConfigIO,
|
|
230
|
-
mcpJsonPath: string,
|
|
231
|
-
patch: Record<string, unknown>,
|
|
232
|
-
): ConfigWriteResult {
|
|
233
|
-
const r = parseOrError(io, mcpJsonPath);
|
|
234
|
-
if ("error" in r) return r.error;
|
|
235
|
-
const config = r.parsed;
|
|
236
|
-
const sr = readServers(config, mcpJsonPath);
|
|
237
|
-
if ("error" in sr) return sr.error;
|
|
238
|
-
const { servers } = sr;
|
|
239
|
-
const er = readExistingImcp(servers, mcpJsonPath);
|
|
240
|
-
if ("error" in er) return er.error;
|
|
241
|
-
const merged: Record<string, unknown> = { ...er.existing };
|
|
242
|
-
for (const [k, v] of Object.entries(patch)) {
|
|
243
|
-
if (v === undefined) delete merged[k];
|
|
244
|
-
else merged[k] = v;
|
|
245
|
-
}
|
|
246
|
-
const next = { ...config, mcpServers: { ...servers, iMCP: merged } };
|
|
247
|
-
return writeOrError(io, mcpJsonPath, next);
|
|
248
|
-
}
|
|
249
|
-
|
|
250
|
-
/**
|
|
251
|
-
* Write the iMCP `disabled` override into a given mcp.json layer. BOTH levels
|
|
252
|
-
* are supported and use the identical merge discipline:
|
|
253
|
-
* - global → `~/.pi/agent/mcp.json` (the layer the installer writes `command`
|
|
254
|
-
* to; the target for the dashboard's global settings panel)
|
|
255
|
-
* - project → `<cwd>/.pi/mcp.json` (the adapter's highest-precedence layer,
|
|
256
|
-
* so a project override folds over the global value without mutating it)
|
|
257
|
-
*
|
|
258
|
-
* Mirrors `writeProjectServerDisabledOverride` in the installed pi-mcp-adapter
|
|
259
|
-
* (`config.ts`): disabling writes `disabled: true`; ENABLING removes the key
|
|
260
|
-
* rather than writing `false`. `isServerDisabled` treats only a literal `true`
|
|
261
|
-
* as disabled (`types.ts:395`). Verified against adapter v2.19.0 (task 7.8).
|
|
262
|
-
*/
|
|
263
|
-
export function setServerDisabled(
|
|
264
|
-
io: ConfigIO,
|
|
265
|
-
mcpJsonPath: string,
|
|
266
|
-
disabled: boolean,
|
|
267
|
-
): ConfigWriteResult {
|
|
268
|
-
return patchImcpEntry(io, mcpJsonPath, { disabled: disabled ? true : undefined });
|
|
269
|
-
}
|
|
270
|
-
|
|
271
|
-
/**
|
|
272
|
-
* Write the adapter's per-server `directTools` filter onto the iMCP entry
|
|
273
|
-
* (`ServerEntry.directTools?: boolean | string[]`, consumed by the adapter's
|
|
274
|
-
* `direct-tools.ts`). An empty selection removes the key rather than writing
|
|
275
|
-
* `[]`, which the adapter would read as "promote nothing".
|
|
276
|
-
*/
|
|
277
|
-
export function setDirectTools(
|
|
278
|
-
io: ConfigIO,
|
|
279
|
-
mcpJsonPath: string,
|
|
280
|
-
tools: string[],
|
|
281
|
-
): ConfigWriteResult {
|
|
282
|
-
return patchImcpEntry(io, mcpJsonPath, {
|
|
283
|
-
directTools: tools.length > 0 ? tools : undefined,
|
|
284
|
-
});
|
|
285
|
-
}
|