@jini-ai/mcp 0.7.3-next.2 → 0.7.3-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +15 -0
- package/dist/agent-install/owned-json-install.d.ts +1 -1
- package/dist/client/client.js +1 -1
- package/dist/client/css-url-refs.d.ts +3 -1
- package/dist/client/css-url-refs.js +1 -1
- package/dist/external/access-review.d.ts +46 -0
- package/dist/external/access-review.js +175 -0
- package/dist/external/agent-tools.d.ts +72 -0
- package/dist/external/agent-tools.js +218 -0
- package/dist/external/built-in-connections.d.ts +17 -0
- package/dist/external/built-in-connections.js +15 -0
- package/dist/external/external-mcp-host-copy.d.ts +14 -0
- package/dist/external/external-mcp-host-copy.js +8 -0
- package/dist/external/operations-tools.d.ts +69 -0
- package/dist/external/operations-tools.js +96 -0
- package/dist/external/save-form.d.ts +105 -0
- package/dist/external/save-form.js +260 -0
- package/dist/external/save-input.d.ts +41 -0
- package/dist/external/save-input.js +149 -0
- package/dist/external/tool-registrations.d.ts +130 -0
- package/dist/external/tool-registrations.js +299 -0
- package/dist/federation/bootstrap.d.ts +18 -0
- package/dist/federation/bootstrap.js +2 -2
- package/dist/federation/external-mcp-admissions.d.ts +19 -0
- package/dist/federation/external-mcp-admissions.js +30 -0
- package/dist/federation/external-mcp-probe.d.ts +86 -0
- package/dist/federation/external-mcp-probe.js +75 -0
- package/dist/federation/hosted/external-mcp-repo.d.ts +108 -0
- package/dist/federation/hosted/external-mcp-repo.js +210 -0
- package/dist/federation/hosted/external-mcp-repo.writes.d.ts +75 -0
- package/dist/federation/hosted/external-mcp-repo.writes.js +131 -0
- package/dist/federation/hosted/store-credentials.d.ts +6 -1
- package/dist/federation/hosted/store-credentials.js +2 -2
- package/dist/federation/hosted/store-input.d.ts +11 -3
- package/dist/federation/hosted/store-input.js +5 -5
- package/dist/federation/hosted/store-oauth-fields.d.ts +10 -2
- package/dist/federation/hosted/store-oauth-fields.js +7 -7
- package/dist/federation/hosted/store-view.d.ts +6 -1
- package/dist/federation/hosted/store-view.js +2 -2
- package/dist/federation/hosted/store.js +7 -7
- package/dist/federation/hosted/store.memory.d.ts +2 -0
- package/dist/federation/hosted/store.memory.js +6 -2
- package/dist/federation/index.d.ts +2 -0
- package/dist/federation/index.js +2 -0
- package/dist/federation/registrations.js +73 -56
- package/dist/federation/roster-change.d.ts +63 -0
- package/dist/federation/roster-change.js +68 -0
- package/dist/federation/runtime.d.ts +140 -0
- package/dist/federation/runtime.js +118 -0
- package/dist/react/external-mcp/ExternalMcpAdmissionsBanner.d.ts +42 -0
- package/dist/react/external-mcp/ExternalMcpAdmissionsBanner.js +80 -0
- package/dist/react/external-mcp/ExternalMcpPanelSections.d.ts +50 -0
- package/dist/react/external-mcp/ExternalMcpPanelSections.js +35 -0
- package/dist/react/external-mcp/ExternalMcpSettingsPanel.d.ts +446 -0
- package/dist/react/external-mcp/ExternalMcpSettingsPanel.hooks.d.ts +135 -0
- package/dist/react/external-mcp/ExternalMcpSettingsPanel.hooks.js +122 -0
- package/dist/react/external-mcp/ExternalMcpSettingsPanel.js +63 -0
- package/dist/react/external-mcp/ExternalMcpSourceRow.d.ts +40 -0
- package/dist/react/external-mcp/ExternalMcpSourceRow.js +100 -0
- package/dist/react/external-mcp/hooks/external-mcp-form.rules.d.ts +58 -0
- package/dist/react/external-mcp/hooks/external-mcp-form.rules.js +209 -0
- package/dist/react/external-mcp/hooks/external-mcp-source-actions.d.ts +115 -0
- package/dist/react/external-mcp/hooks/external-mcp-source-actions.js +152 -0
- package/dist/react/external-mcp/hooks/use-external-mcp-admissions.hooks.d.ts +166 -0
- package/dist/react/external-mcp/hooks/use-external-mcp-admissions.hooks.js +209 -0
- package/dist/react/external-mcp/hooks/use-external-mcp.hooks.d.ts +132 -0
- package/dist/react/external-mcp/hooks/use-external-mcp.hooks.js +37 -0
- package/dist/server/tool-arguments.d.ts +5 -1
- package/dist/server/tool-arguments.js +13 -9
- package/dist/server/tool-protocol.js +7 -5
- package/dist/server/tools/tool-catalog-tools.js +6 -3
- package/dist/tools/ask-choice/custom-answer.d.ts +77 -0
- package/dist/tools/ask-choice/custom-answer.js +113 -0
- package/dist/tools/ask-choice/index.d.ts +2 -0
- package/dist/tools/ask-choice/index.js +1 -0
- package/package.json +122 -7
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import type { useExternalMcp, ExternalMcpPort, ExternalMcpController } from "./use-external-mcp.hooks.js";
|
|
2
|
+
import type { AdminExternalMcpServer } from "@jini-ai/core/contracts/site/cms-external-mcp";
|
|
3
|
+
type SourceConfigItem = Awaited<ReturnType<ExternalMcpController["dependencies"]["port"]["fetchSources"]>>[number];
|
|
4
|
+
export declare function checkSavedServer({ item, server, locale, port, deps }: {
|
|
5
|
+
item: SourceConfigItem;
|
|
6
|
+
server: AdminExternalMcpServer;
|
|
7
|
+
locale: string;
|
|
8
|
+
port: ExternalMcpPort;
|
|
9
|
+
deps: Parameters<typeof useExternalMcp>[0]["deps"];
|
|
10
|
+
}): Promise<SourceConfigItem>;
|
|
11
|
+
export declare function fetchSources({ deps, port, locale, lastKnown }: {
|
|
12
|
+
deps: Parameters<typeof useExternalMcp>[0]["deps"];
|
|
13
|
+
port: ExternalMcpPort;
|
|
14
|
+
locale: string;
|
|
15
|
+
lastKnown: {
|
|
16
|
+
current: Map<string, SourceConfigItem>;
|
|
17
|
+
};
|
|
18
|
+
}, _optional?: {}): Promise<SourceConfigItem[]>;
|
|
19
|
+
export declare function addSource({ input, deps, port, locale, lastKnown, setRestartRequired, t }: {
|
|
20
|
+
input: {
|
|
21
|
+
fields: Record<string, string>;
|
|
22
|
+
trust?: string;
|
|
23
|
+
};
|
|
24
|
+
deps: Parameters<typeof useExternalMcp>[0]["deps"];
|
|
25
|
+
port: ExternalMcpPort;
|
|
26
|
+
locale: string;
|
|
27
|
+
lastKnown: {
|
|
28
|
+
current: Map<string, SourceConfigItem>;
|
|
29
|
+
};
|
|
30
|
+
setRestartRequired: (value: boolean) => void;
|
|
31
|
+
t: (key: string) => string;
|
|
32
|
+
}, _optional?: {}): Promise<{
|
|
33
|
+
ok: boolean;
|
|
34
|
+
source?: SourceConfigItem;
|
|
35
|
+
message?: string;
|
|
36
|
+
}>;
|
|
37
|
+
export declare function removeSource({ id, port, lastKnown, setRestartRequired }: {
|
|
38
|
+
id: string;
|
|
39
|
+
port: ExternalMcpPort;
|
|
40
|
+
lastKnown: {
|
|
41
|
+
current: Map<string, SourceConfigItem>;
|
|
42
|
+
};
|
|
43
|
+
setRestartRequired: (value: boolean) => void;
|
|
44
|
+
}, _optional?: {}): Promise<boolean>;
|
|
45
|
+
/**
|
|
46
|
+
* Runs the write behind whatever `updateSource` write for THIS SAME id is already in
|
|
47
|
+
* flight (`writes.run(..., { key: id })`), so a second concurrent edit never reads
|
|
48
|
+
* `lastKnown` until the first one has actually committed its own result there.
|
|
49
|
+
*
|
|
50
|
+
* The merge below is a read-then-write over `lastKnown` (see that ref's own doc), and
|
|
51
|
+
* nothing else serializes two calls for the same id: `SourceConfigList` can fire a toggle
|
|
52
|
+
* and a field-save close together (e.g. flipping "enabled" while a command edit is still
|
|
53
|
+
* saving), and without this both reads see the SAME pre-write snapshot. Whichever write
|
|
54
|
+
* then lands second wins outright — not merges — because it built its own full-row body
|
|
55
|
+
* from a `previous` that never saw the first write's change, so the field the first write
|
|
56
|
+
* touched (and the second's own patch never named) silently reverts the moment the second
|
|
57
|
+
* write's response arrives. Keying the lane on `id` closes that: the second call's
|
|
58
|
+
* `previous` read is delayed until the first call's `lastKnown.set` has actually run, so it
|
|
59
|
+
* merges against the true current state instead of a stale one. Different ids are NOT
|
|
60
|
+
* serialized against each other — they are independent rows with no shared merge base, and
|
|
61
|
+
* each gets its own lane.
|
|
62
|
+
*/
|
|
63
|
+
export declare function updateSource({ id, patch, deps, port, locale, lastKnown, setRestartRequired, writes, t }: {
|
|
64
|
+
id: string;
|
|
65
|
+
patch: {
|
|
66
|
+
label?: string;
|
|
67
|
+
enabled?: boolean;
|
|
68
|
+
fields?: Record<string, string>;
|
|
69
|
+
};
|
|
70
|
+
deps: Parameters<typeof useExternalMcp>[0]["deps"];
|
|
71
|
+
port: ExternalMcpPort;
|
|
72
|
+
locale: string;
|
|
73
|
+
lastKnown: {
|
|
74
|
+
current: Map<string, SourceConfigItem>;
|
|
75
|
+
};
|
|
76
|
+
setRestartRequired: (value: boolean) => void;
|
|
77
|
+
writes: ReturnType<Parameters<typeof useExternalMcp>[0]["hooks"]["useSerialWrites"]>;
|
|
78
|
+
t: (key: string) => string;
|
|
79
|
+
}, _optional?: {}): Promise<SourceConfigItem | null>;
|
|
80
|
+
/**
|
|
81
|
+
* Wired to `probeExternalMcpServer` (C-007, outline §3.1 Source A / §3.5's D-5). Its only
|
|
82
|
+
* effect is lighting up Jini's existing "Test" button — `useSourceConfigList.ts` derives
|
|
83
|
+
* `capabilities.canTest` from `Boolean(port.testSource)`, so implementing this method is
|
|
84
|
+
* what makes the button appear at all.
|
|
85
|
+
*
|
|
86
|
+
* `id` is `undefined` for the add-form's still-unsaved draft (Jini's generic "test before
|
|
87
|
+
* save" case). The probe route addresses an already-persisted server by id, so there is
|
|
88
|
+
* nothing to probe yet — this returns a failure rather than guessing at a URL/command the
|
|
89
|
+
* operator has not saved.
|
|
90
|
+
*
|
|
91
|
+
* `SourceTestResult` cannot carry a tool list (`{ ok, message?, latencyMs? }`), so this is
|
|
92
|
+
* a reachability check ONLY — it complements, and does not replace, the dedicated
|
|
93
|
+
* `ExternalMcpToolPicker` (Phase 4), which reads `probeExternalMcpServer`'s full
|
|
94
|
+
* `AdminRemoteToolSurfaceEntry[]` directly.
|
|
95
|
+
*
|
|
96
|
+
* The port's `draft` second parameter (unsaved field edits to test against, for an
|
|
97
|
+
* already-persisted item) is deliberately not accepted: `probeExternalMcpServer` (C-007)
|
|
98
|
+
* takes only a `serverId` path param and always connects using the server's LAST SAVED
|
|
99
|
+
* `url`/`command`, so there is nothing here that could honor an edited-but-unsaved value —
|
|
100
|
+
* testing an in-progress edit would require the probe route to accept a draft connection
|
|
101
|
+
* target, which is out of this slice's scope.
|
|
102
|
+
*/
|
|
103
|
+
export declare function testSource({ id, deps, port, locale, t }: {
|
|
104
|
+
id: string | undefined;
|
|
105
|
+
deps: Parameters<typeof useExternalMcp>[0]["deps"];
|
|
106
|
+
port: ExternalMcpPort;
|
|
107
|
+
locale: string;
|
|
108
|
+
t: (key: string) => string;
|
|
109
|
+
}, _optional?: {}): Promise<{
|
|
110
|
+
ok: boolean;
|
|
111
|
+
message?: string;
|
|
112
|
+
latencyMs?: number;
|
|
113
|
+
}>;
|
|
114
|
+
export {};
|
|
115
|
+
//# sourceMappingURL=external-mcp-source-actions.d.ts.map
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
import { toItem, toWriteBody, fieldOrEmpty, expectedVersionOf } from "./external-mcp-form.rules.js";
|
|
2
|
+
export async function checkSavedServer({ item, server, locale, port, deps }) {
|
|
3
|
+
let message = deps.credentialText({ id: 'saved', locale });
|
|
4
|
+
if (server.transport !== 'stdio' && server.enabled) {
|
|
5
|
+
try {
|
|
6
|
+
await port.probeExternalMcpServer({ serverId: server.serverId });
|
|
7
|
+
message = deps.credentialText({ id: 'connected', locale });
|
|
8
|
+
}
|
|
9
|
+
catch (err) {
|
|
10
|
+
message = deps.translateCredentialMessage({ message: deps.describeApiError({ e: err, fallback: deps.credentialText({ id: 'unreachable', locale }) }), locale });
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
return { ...item, statusMessage: [item.statusMessage, message].filter(Boolean).join(' · ') };
|
|
14
|
+
}
|
|
15
|
+
/** The plain-words reason a save failed: the stale-version copy for a lost compare-and-set, else the server's own. @complexity O(1). */
|
|
16
|
+
function describeSaveFailure({ err, t, deps }, _options = {}) {
|
|
17
|
+
return deps.isVersionConflict({ error: err }) ? t(deps.VERSION_CONFLICT_MESSAGE) : deps.describeApiError({ e: err, fallback: t('That server could not be saved.') });
|
|
18
|
+
}
|
|
19
|
+
export async function fetchSources({ deps, port, locale, lastKnown }, _optional = {}) {
|
|
20
|
+
const { servers } = await port.listExternalMcpServers();
|
|
21
|
+
const items = servers.map(server => toItem({ server, deps }, { locale }));
|
|
22
|
+
lastKnown.current = new Map(items.map((item) => [item.id, item]));
|
|
23
|
+
return items;
|
|
24
|
+
}
|
|
25
|
+
/** An untouched transport saves as STDIO; require a header token only for hosted rows. */
|
|
26
|
+
function hostedTokenDraftIssue({ input, deps, locale }) {
|
|
27
|
+
if (deps.resolveExternalMcpEffectiveAuthMode(input.fields) !== 'static_env')
|
|
28
|
+
return null;
|
|
29
|
+
if (deps.resolveExternalMcpEffectiveTransport(input.fields) === 'stdio')
|
|
30
|
+
return null;
|
|
31
|
+
return deps.credentialDraftError({ value: fieldOrEmpty({ fields: input.fields, key: 'accessToken' }) }, { locale, required: true });
|
|
32
|
+
}
|
|
33
|
+
export async function addSource({ input, deps, port, locale, lastKnown, setRestartRequired, t }, _optional = {}) {
|
|
34
|
+
const serverId = (input.fields.id ?? "").trim();
|
|
35
|
+
if (serverId === "")
|
|
36
|
+
return { ok: false, message: t("An ID is required.") };
|
|
37
|
+
// The write is a create-OR-replace PUT, so an id already on the list would silently
|
|
38
|
+
// replace that server's command, tool allowlists and auth instead of adding a new one.
|
|
39
|
+
if (lastKnown.current.has(serverId)) {
|
|
40
|
+
return { ok: false, message: t("A server with this ID already exists. Edit that server instead.") };
|
|
41
|
+
}
|
|
42
|
+
const tokenIssue = hostedTokenDraftIssue({ input, deps, locale });
|
|
43
|
+
if (tokenIssue)
|
|
44
|
+
return { ok: false, message: tokenIssue };
|
|
45
|
+
const oauthIdentityIssue = deps.validateExternalMcpOAuthIdentity(input.fields, { t });
|
|
46
|
+
if (oauthIdentityIssue)
|
|
47
|
+
return { ok: false, message: oauthIdentityIssue };
|
|
48
|
+
try {
|
|
49
|
+
const { server } = await port.saveExternalMcpServer({
|
|
50
|
+
serverId,
|
|
51
|
+
body: toWriteBody({ fields: input.fields, enabled: true, deps }, { ...(input.fields.label !== undefined && { label: input.fields.label }) }),
|
|
52
|
+
});
|
|
53
|
+
setRestartRequired(true);
|
|
54
|
+
const item = toItem({ server, deps }, { locale });
|
|
55
|
+
const checked = await checkSavedServer({ item, server, locale, port, deps });
|
|
56
|
+
lastKnown.current.set(item.id, checked);
|
|
57
|
+
return { ok: true, source: checked };
|
|
58
|
+
}
|
|
59
|
+
catch (e) {
|
|
60
|
+
return { ok: false, message: deps.translateCredentialMessage({ message: deps.describeApiError({ e, fallback: t("That server could not be saved.") }), locale }) };
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
export async function removeSource({ id, port, lastKnown, setRestartRequired }, _optional = {}) {
|
|
64
|
+
try {
|
|
65
|
+
await port.deleteExternalMcpServer({ serverId: id });
|
|
66
|
+
setRestartRequired(true);
|
|
67
|
+
lastKnown.current.delete(id);
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return false;
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Runs the write behind whatever `updateSource` write for THIS SAME id is already in
|
|
76
|
+
* flight (`writes.run(..., { key: id })`), so a second concurrent edit never reads
|
|
77
|
+
* `lastKnown` until the first one has actually committed its own result there.
|
|
78
|
+
*
|
|
79
|
+
* The merge below is a read-then-write over `lastKnown` (see that ref's own doc), and
|
|
80
|
+
* nothing else serializes two calls for the same id: `SourceConfigList` can fire a toggle
|
|
81
|
+
* and a field-save close together (e.g. flipping "enabled" while a command edit is still
|
|
82
|
+
* saving), and without this both reads see the SAME pre-write snapshot. Whichever write
|
|
83
|
+
* then lands second wins outright — not merges — because it built its own full-row body
|
|
84
|
+
* from a `previous` that never saw the first write's change, so the field the first write
|
|
85
|
+
* touched (and the second's own patch never named) silently reverts the moment the second
|
|
86
|
+
* write's response arrives. Keying the lane on `id` closes that: the second call's
|
|
87
|
+
* `previous` read is delayed until the first call's `lastKnown.set` has actually run, so it
|
|
88
|
+
* merges against the true current state instead of a stale one. Different ids are NOT
|
|
89
|
+
* serialized against each other — they are independent rows with no shared merge base, and
|
|
90
|
+
* each gets its own lane.
|
|
91
|
+
*/
|
|
92
|
+
export async function updateSource({ id, patch, deps, port, locale, lastKnown, setRestartRequired, writes, t }, _optional = {}) {
|
|
93
|
+
return writes.run({ task: async () => {
|
|
94
|
+
const previous = lastKnown.current.get(id);
|
|
95
|
+
const merged = deps.mergeSourceUpdate({ previous, patch });
|
|
96
|
+
try {
|
|
97
|
+
const { server } = await port.saveExternalMcpServer({ serverId: id, body: { ...toWriteBody({ fields: merged.fields, enabled: merged.enabled, deps }, { ...(merged.label !== undefined && { label: merged.label }) }), ...expectedVersionOf({ item: previous }) } });
|
|
98
|
+
setRestartRequired(true);
|
|
99
|
+
const item = toItem({ server, deps }, { locale });
|
|
100
|
+
const changedToken = (merged.fields.accessToken ?? '') !== '';
|
|
101
|
+
const checked = changedToken ? await checkSavedServer({ item, server, locale, port, deps }) : item;
|
|
102
|
+
lastKnown.current.set(item.id, checked);
|
|
103
|
+
return checked;
|
|
104
|
+
}
|
|
105
|
+
catch (err) {
|
|
106
|
+
if (!previous)
|
|
107
|
+
return null;
|
|
108
|
+
return { ...previous, statusMessage: deps.translateCredentialMessage({ message: describeSaveFailure({ err, t, deps }), locale }) };
|
|
109
|
+
}
|
|
110
|
+
} }, { key: id });
|
|
111
|
+
}
|
|
112
|
+
/**
|
|
113
|
+
* Wired to `probeExternalMcpServer` (C-007, outline §3.1 Source A / §3.5's D-5). Its only
|
|
114
|
+
* effect is lighting up Jini's existing "Test" button — `useSourceConfigList.ts` derives
|
|
115
|
+
* `capabilities.canTest` from `Boolean(port.testSource)`, so implementing this method is
|
|
116
|
+
* what makes the button appear at all.
|
|
117
|
+
*
|
|
118
|
+
* `id` is `undefined` for the add-form's still-unsaved draft (Jini's generic "test before
|
|
119
|
+
* save" case). The probe route addresses an already-persisted server by id, so there is
|
|
120
|
+
* nothing to probe yet — this returns a failure rather than guessing at a URL/command the
|
|
121
|
+
* operator has not saved.
|
|
122
|
+
*
|
|
123
|
+
* `SourceTestResult` cannot carry a tool list (`{ ok, message?, latencyMs? }`), so this is
|
|
124
|
+
* a reachability check ONLY — it complements, and does not replace, the dedicated
|
|
125
|
+
* `ExternalMcpToolPicker` (Phase 4), which reads `probeExternalMcpServer`'s full
|
|
126
|
+
* `AdminRemoteToolSurfaceEntry[]` directly.
|
|
127
|
+
*
|
|
128
|
+
* The port's `draft` second parameter (unsaved field edits to test against, for an
|
|
129
|
+
* already-persisted item) is deliberately not accepted: `probeExternalMcpServer` (C-007)
|
|
130
|
+
* takes only a `serverId` path param and always connects using the server's LAST SAVED
|
|
131
|
+
* `url`/`command`, so there is nothing here that could honor an edited-but-unsaved value —
|
|
132
|
+
* testing an in-progress edit would require the probe route to accept a draft connection
|
|
133
|
+
* target, which is out of this slice's scope.
|
|
134
|
+
*/
|
|
135
|
+
export async function testSource({ id, deps, port, locale, t }, _optional = {}) {
|
|
136
|
+
if (id === undefined) {
|
|
137
|
+
return { ok: false, message: t("Save this server before you can test it.") };
|
|
138
|
+
}
|
|
139
|
+
const startedAt = deps.now();
|
|
140
|
+
try {
|
|
141
|
+
const { tools } = await port.probeExternalMcpServer({ serverId: id });
|
|
142
|
+
return {
|
|
143
|
+
ok: true,
|
|
144
|
+
message: `${tools.length} tool${tools.length === 1 ? "" : "s"} advertised.`,
|
|
145
|
+
latencyMs: deps.now() - startedAt,
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
catch (e) {
|
|
149
|
+
return { ok: false, message: deps.translateCredentialMessage({ message: deps.describeApiError({ e, fallback: deps.credentialText({ id: "unreachable", locale }) }), locale }) };
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
//# sourceMappingURL=external-mcp-source-actions.js.map
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import type { AdminHttpError } from "@jini-ai/core/admin-runtime";
|
|
2
|
+
import type { AdminExternalMcpAdmissionsSnapshot } from "@jini-ai/core/contracts/hosted-mcp";
|
|
3
|
+
import type { FetchMutationOptions, FetchQueryOptions, MutationResult, QueryResult } from "@jini-ai/core/fetch";
|
|
4
|
+
import { type Translate } from '@jini-ai/core/text';
|
|
5
|
+
/** One saved-vs-live disagreement row, as the host's injected drift describer reports it. */
|
|
6
|
+
export interface AdmissionDriftEntry {
|
|
7
|
+
readonly connectionId: string;
|
|
8
|
+
readonly remoteName: string | null;
|
|
9
|
+
readonly kind: string;
|
|
10
|
+
readonly messageKey: string;
|
|
11
|
+
readonly messageVars: Readonly<Record<string, string>>;
|
|
12
|
+
}
|
|
13
|
+
/** A connection with something to say about saved-vs-live tool admission. */
|
|
14
|
+
export interface AdmissionDriftConnection {
|
|
15
|
+
readonly connectionId: string;
|
|
16
|
+
readonly liveToolCount: number;
|
|
17
|
+
readonly notLoaded: readonly string[];
|
|
18
|
+
readonly savedToolCount: number;
|
|
19
|
+
readonly entries: readonly AdmissionDriftEntry[];
|
|
20
|
+
}
|
|
21
|
+
/** A roster card's saved intent (its `allowedToolNames` field value and on/off toggle). */
|
|
22
|
+
export interface SavedConnectionIntent {
|
|
23
|
+
readonly allowedToolNames: string;
|
|
24
|
+
readonly enabled: boolean;
|
|
25
|
+
readonly transport?: string;
|
|
26
|
+
readonly command?: string;
|
|
27
|
+
readonly needsSignIn?: boolean;
|
|
28
|
+
}
|
|
29
|
+
/** The injected fetch-query hooks (the host's `useFetchQuery`/`useFetchMutation`). */
|
|
30
|
+
export type UseFetchQueryHook = <T>(required: Pick<FetchQueryOptions<T>, "key" | "fetch">, optional?: Omit<FetchQueryOptions<T>, "key" | "fetch">) => QueryResult<T>;
|
|
31
|
+
export type UseFetchMutationHook = <TInput, TOutput>(required: Pick<FetchMutationOptions<TInput, TOutput>, "run">, optional?: Omit<FetchMutationOptions<TInput, TOutput>, "run">) => MutationResult<TInput, TOutput>;
|
|
32
|
+
/**
|
|
33
|
+
* @file The transport behind Settings → External MCP's "what is the assistant actually running"
|
|
34
|
+
* banner: three reads the app already had clients for, and never called together.
|
|
35
|
+
*
|
|
36
|
+
* ## The 503 is data, not an error to swallow
|
|
37
|
+
*
|
|
38
|
+
* `GET .../mcp-servers/admissions` answers a down or unreachable daemon with a distinguishable 503
|
|
39
|
+
* (`code: "AGENT_DAEMON_UNAVAILABLE"`) rather than `{ connections: [] }`, precisely so "the
|
|
40
|
+
* assistant is not running" and "it is running with nothing admitted" stay distinguishable — see
|
|
41
|
+
* that route's own header. This hook preserves that: {@link ExternalMcpAdmissionsController.unavailable}
|
|
42
|
+
* is a sentence to render, never a silently empty list.
|
|
43
|
+
*
|
|
44
|
+
* ## Why the restart button needs a permission read of its own
|
|
45
|
+
*
|
|
46
|
+
* `POST .../system/assistant-daemon/restart` is `system.write`-gated, while this whole tab is
|
|
47
|
+
* `admin.integrations.manage`-gated — so an operator with integration rights and no system rights
|
|
48
|
+
* would get a 403 from a button that looked available. The outline calls that out as decision D-4
|
|
49
|
+
* and answers it: hide the button, and say who can do it instead. `hasPermission` (not a bare
|
|
50
|
+
* `.includes`) is what makes that correct for a workspace owner, whose grant is the literal `"*"`.
|
|
51
|
+
*
|
|
52
|
+
* This is affordance-hiding, not authorization: the route re-checks server-side on every call.
|
|
53
|
+
*/
|
|
54
|
+
/** The three calls this hook makes, injectable so a test composes it with plain fakes. */
|
|
55
|
+
export interface ExternalMcpAdmissionsPort {
|
|
56
|
+
getAdmissions(): Promise<AdminExternalMcpAdmissionsSnapshot>;
|
|
57
|
+
me(): Promise<{
|
|
58
|
+
effectivePermissions?: string[];
|
|
59
|
+
}>;
|
|
60
|
+
restartAssistantDaemon(): Promise<{
|
|
61
|
+
ok: boolean;
|
|
62
|
+
reason?: string;
|
|
63
|
+
}>;
|
|
64
|
+
}
|
|
65
|
+
export interface ExternalMcpAdmissionsController<Connection extends AdmissionDriftConnection = AdmissionDriftConnection> {
|
|
66
|
+
readonly loading: boolean;
|
|
67
|
+
/** A sentence to render when the daemon could not be asked AND the automatic wait for it is over.
|
|
68
|
+
* `null` when it answered, and `null` while {@link waitingForAssistant} is still true. */
|
|
69
|
+
readonly unavailable: string | null;
|
|
70
|
+
/** `true` while the daemon cannot be asked for a reason that normally clears on its own (it is
|
|
71
|
+
* booting or respawning) and this hook is still re-asking — see {@link useUnavailableRetry}. */
|
|
72
|
+
readonly waitingForAssistant: boolean;
|
|
73
|
+
/** Only connections with something to say — an agreeing roster renders nothing. */
|
|
74
|
+
readonly connections: readonly Connection[];
|
|
75
|
+
/** Whether any listed disagreement would change on a restart. Independent of permissions. */
|
|
76
|
+
readonly restartHelps: boolean;
|
|
77
|
+
/** D-4: whether this principal may actually restart the assistant. */
|
|
78
|
+
readonly canRestart: boolean;
|
|
79
|
+
readonly restarting: boolean;
|
|
80
|
+
/** The restart route's own refusal reason (it answers 409 while shutting down), or `null`. */
|
|
81
|
+
readonly restartError: string | null;
|
|
82
|
+
/** `true` while a restart this hook triggered was ACCEPTED and the bounded re-read that follows it
|
|
83
|
+
* is still running — never "the assistant is back up", which no signal in this codebase can
|
|
84
|
+
* currently claim (see the restart route's own header). It goes false when the watch window
|
|
85
|
+
* closes, so the "Restarting…" line stops after {@link RESTART_WATCH_ATTEMPTS} attempts rather
|
|
86
|
+
* than standing for the rest of the mounted session (2026-09-07, ADM-002). */
|
|
87
|
+
readonly restartAccepted: boolean;
|
|
88
|
+
restart(): void;
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Whether a failed admissions read is one that normally clears on its own: the daemon is booting or
|
|
92
|
+
* respawning (the route's 503), or the API in front of it is (unreachable, timed out, or a 5xx from
|
|
93
|
+
* the dev proxy). A 401/403/404 is not — waiting changes nothing about those.
|
|
94
|
+
*
|
|
95
|
+
* Why waiting is the right default (2026-09-29): the daemon only binds its port AFTER it has
|
|
96
|
+
* connected every saved external MCP server, one after another (`agent-daemon-server.ts` `start()`),
|
|
97
|
+
* and the dev API respawns it on every source save. A boot was measured at ~80s after the API's own
|
|
98
|
+
* ~40s. Reading once on mount and showing "not reachable" for that whole window put a red error in
|
|
99
|
+
* front of an assistant that was simply starting — and nothing re-read it afterwards.
|
|
100
|
+
*
|
|
101
|
+
* @complexity O(1).
|
|
102
|
+
*/
|
|
103
|
+
export declare function isAssistantStartingError({ error, isApiError, apiUnreachableCode, requestTimeoutCode }: {
|
|
104
|
+
error: unknown;
|
|
105
|
+
} & Pick<Parameters<typeof useExternalMcpAdmissions>[0], "isApiError" | "apiUnreachableCode" | "requestTimeoutCode">, _options?: {}): boolean;
|
|
106
|
+
/** Gap between automatic re-reads while the assistant is starting. */
|
|
107
|
+
export declare const UNAVAILABLE_RETRY_INTERVAL_MS = 3000;
|
|
108
|
+
/** How long the automatic wait lasts before the real error is shown: 60 × 3s = three minutes, which
|
|
109
|
+
* holds a dev API reload plus a slow daemon boot with room to spare. A daemon that is genuinely
|
|
110
|
+
* down still gets reported — just not during the window where "down" is the wrong reading. */
|
|
111
|
+
export declare const UNAVAILABLE_RETRY_ATTEMPTS = 60;
|
|
112
|
+
/**
|
|
113
|
+
* @param deps.port - See {@link ExternalMcpAdmissionsPort}.
|
|
114
|
+
* @param deps.savedAllowedToolNamesById - Each roster card's own `allowedToolNames` field value,
|
|
115
|
+
* keyed by server id, plus its on/off toggle, so the banner can state saved-vs-live rather than
|
|
116
|
+
* only live — including for a saved connection the daemon never reported (ADM-001).
|
|
117
|
+
* @complexity O(c · t) in connections and their refused tools.
|
|
118
|
+
* @overallScore 100
|
|
119
|
+
*/
|
|
120
|
+
export declare function useExternalMcpAdmissions<Copy, Connection extends AdmissionDriftConnection>(deps: {
|
|
121
|
+
port: ExternalMcpAdmissionsPort;
|
|
122
|
+
savedAllowedToolNamesById: Readonly<Record<string, SavedConnectionIntent>>;
|
|
123
|
+
t: Translate;
|
|
124
|
+
useFetchQuery: UseFetchQueryHook;
|
|
125
|
+
useFetchMutation: UseFetchMutationHook;
|
|
126
|
+
hasPermission: (required: {
|
|
127
|
+
permissions: readonly string[];
|
|
128
|
+
permission: string;
|
|
129
|
+
}) => boolean;
|
|
130
|
+
describeAdmissionDrift: (required: {
|
|
131
|
+
snapshot: AdminExternalMcpAdmissionsSnapshot | undefined;
|
|
132
|
+
savedById: Readonly<Record<string, SavedConnectionIntent>>;
|
|
133
|
+
copy: Copy;
|
|
134
|
+
}) => readonly Connection[];
|
|
135
|
+
admissionRestartHelps: (required: {
|
|
136
|
+
connections: readonly Connection[];
|
|
137
|
+
}) => boolean;
|
|
138
|
+
driftCopy: Copy;
|
|
139
|
+
describeApiError: (required: {
|
|
140
|
+
e: unknown;
|
|
141
|
+
fallback: string;
|
|
142
|
+
}) => string;
|
|
143
|
+
isApiError: (error: unknown) => error is AdminHttpError;
|
|
144
|
+
apiUnreachableCode: string;
|
|
145
|
+
requestTimeoutCode: string;
|
|
146
|
+
setTimeout: typeof globalThis.setTimeout;
|
|
147
|
+
clearTimeout: typeof globalThis.clearTimeout;
|
|
148
|
+
reportRestartFailure: (error: unknown) => void;
|
|
149
|
+
}, _optional?: Record<string, never>): ExternalMcpAdmissionsController<Connection>;
|
|
150
|
+
export declare function bindExternalMcpAdmissions<Copy, Connection extends AdmissionDriftConnection>({ hooks, deps }: {
|
|
151
|
+
hooks: Pick<Parameters<typeof useExternalMcpAdmissions<Copy, Connection>>[0], "useFetchQuery" | "useFetchMutation"> & {
|
|
152
|
+
useCopyHook: () => Translate;
|
|
153
|
+
};
|
|
154
|
+
deps: Omit<Parameters<typeof useExternalMcpAdmissions<Copy, Connection>>[0], "savedAllowedToolNamesById" | "t" | "useFetchQuery" | "useFetchMutation">;
|
|
155
|
+
}, _optional?: {}): {
|
|
156
|
+
isAssistantStartingError: ({ error }: {
|
|
157
|
+
error: unknown;
|
|
158
|
+
}, _optional?: {}) => boolean;
|
|
159
|
+
useExternalMcpAdmissions: ({ port, savedAllowedToolNamesById, t }: {
|
|
160
|
+
port: ExternalMcpAdmissionsPort;
|
|
161
|
+
savedAllowedToolNamesById: Readonly<Record<string, SavedConnectionIntent>>;
|
|
162
|
+
t?: Translate;
|
|
163
|
+
}, _optional?: {}) => ExternalMcpAdmissionsController<Connection>;
|
|
164
|
+
useWiredExternalMcpAdmissions: (savedAllowedToolNamesById: Readonly<Record<string, SavedConnectionIntent>>, _optional?: {}) => ExternalMcpAdmissionsController<Connection>;
|
|
165
|
+
};
|
|
166
|
+
//# sourceMappingURL=use-external-mcp-admissions.hooks.d.ts.map
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
|
2
|
+
import {} from '@jini-ai/core/text';
|
|
3
|
+
const ADMISSIONS_KEY = ["external-mcp", "admissions"];
|
|
4
|
+
const PERMISSIONS_KEY = ["auth", "me"];
|
|
5
|
+
/** Splits the admissions read into "answered" and "could not be asked". Extracted so
|
|
6
|
+
* {@link useExternalMcpAdmissions} stays under the shop complexity ceiling; the fallback sentence
|
|
7
|
+
* is `describeApiError`'s job, so the route's own 503 body reaches the operator rather than being
|
|
8
|
+
* replaced by a generic one. */
|
|
9
|
+
function resolveUnavailable({ error, t, describeApiError }, _options = {}) {
|
|
10
|
+
if (!error)
|
|
11
|
+
return null;
|
|
12
|
+
return describeApiError({ e: error, fallback: t("The assistant is not reporting what it loaded — it may not be running.") });
|
|
13
|
+
}
|
|
14
|
+
/** The admissions route's own 503 code (`routes/external-mcp/admissions.ts`) for "the daemon could
|
|
15
|
+
* not be asked". */
|
|
16
|
+
const AGENT_DAEMON_UNAVAILABLE_CODE = "AGENT_DAEMON_UNAVAILABLE";
|
|
17
|
+
/**
|
|
18
|
+
* Whether a failed admissions read is one that normally clears on its own: the daemon is booting or
|
|
19
|
+
* respawning (the route's 503), or the API in front of it is (unreachable, timed out, or a 5xx from
|
|
20
|
+
* the dev proxy). A 401/403/404 is not — waiting changes nothing about those.
|
|
21
|
+
*
|
|
22
|
+
* Why waiting is the right default (2026-09-29): the daemon only binds its port AFTER it has
|
|
23
|
+
* connected every saved external MCP server, one after another (`agent-daemon-server.ts` `start()`),
|
|
24
|
+
* and the dev API respawns it on every source save. A boot was measured at ~80s after the API's own
|
|
25
|
+
* ~40s. Reading once on mount and showing "not reachable" for that whole window put a red error in
|
|
26
|
+
* front of an assistant that was simply starting — and nothing re-read it afterwards.
|
|
27
|
+
*
|
|
28
|
+
* @complexity O(1).
|
|
29
|
+
*/
|
|
30
|
+
export function isAssistantStartingError({ error, isApiError, apiUnreachableCode, requestTimeoutCode }, _options = {}) {
|
|
31
|
+
if (!isApiError(error))
|
|
32
|
+
return false;
|
|
33
|
+
if (error.code === AGENT_DAEMON_UNAVAILABLE_CODE || error.code === apiUnreachableCode || error.code === requestTimeoutCode)
|
|
34
|
+
return true;
|
|
35
|
+
return error.status >= 500;
|
|
36
|
+
}
|
|
37
|
+
/** Gap between automatic re-reads while the assistant is starting. */
|
|
38
|
+
export const UNAVAILABLE_RETRY_INTERVAL_MS = 3_000;
|
|
39
|
+
/** How long the automatic wait lasts before the real error is shown: 60 × 3s = three minutes, which
|
|
40
|
+
* holds a dev API reload plus a slow daemon boot with room to spare. A daemon that is genuinely
|
|
41
|
+
* down still gets reported — just not during the window where "down" is the wrong reading. */
|
|
42
|
+
export const UNAVAILABLE_RETRY_ATTEMPTS = 60;
|
|
43
|
+
/**
|
|
44
|
+
* Re-reads the admissions snapshot while it keeps failing with {@link isAssistantStartingError},
|
|
45
|
+
* up to {@link UNAVAILABLE_RETRY_ATTEMPTS} times, and resets once a read succeeds (or fails for a
|
|
46
|
+
* reason waiting cannot fix). Same `setTimeout`-chain-on-a-counter shape as {@link useRestartWatch},
|
|
47
|
+
* for the same reasons. A read already in flight is never interrupted: `refetch` cancels an in-flight
|
|
48
|
+
* request, so firing on a timer regardless would starve a slow-but-answering daemon forever.
|
|
49
|
+
*
|
|
50
|
+
* @returns `true` while still waiting — the caller shows a calm "starting" line instead of the error.
|
|
51
|
+
* @complexity O(1) per attempt; at most {@link UNAVAILABLE_RETRY_ATTEMPTS} attempts per outage.
|
|
52
|
+
*/
|
|
53
|
+
function useUnavailableRetry({ failingTransiently, isFetching, refetch, setTimeout, clearTimeout }, _options = {}) {
|
|
54
|
+
const [attempts, setAttempts] = useState(0);
|
|
55
|
+
const refetchRef = useRef(refetch);
|
|
56
|
+
useEffect(() => {
|
|
57
|
+
refetchRef.current = refetch;
|
|
58
|
+
});
|
|
59
|
+
// Judge the outage only on SETTLED reads. `@jini-ai/ui`'s fetch-query cache clears `error` while a
|
|
60
|
+
// re-read of a never-answered query is in flight (Jini kept it), so reading the live value made
|
|
61
|
+
// every retry look like a recovery: the counter reset to 0 each time and a daemon that is genuinely
|
|
62
|
+
// down was polled forever and never reported. Holding the last settled value across the in-flight
|
|
63
|
+
// read keeps the bound real and the "starting" line steady. (React's adjust-state-during-render
|
|
64
|
+
// pattern, so the held value is never one render stale.)
|
|
65
|
+
const [settledFailing, setSettledFailing] = useState(failingTransiently);
|
|
66
|
+
if (!isFetching && settledFailing !== failingTransiently)
|
|
67
|
+
setSettledFailing(failingTransiently);
|
|
68
|
+
useEffect(() => {
|
|
69
|
+
if (!settledFailing)
|
|
70
|
+
setAttempts(0);
|
|
71
|
+
}, [settledFailing]);
|
|
72
|
+
const waiting = settledFailing && attempts < UNAVAILABLE_RETRY_ATTEMPTS;
|
|
73
|
+
useEffect(() => {
|
|
74
|
+
const handle = !waiting || isFetching
|
|
75
|
+
? undefined
|
|
76
|
+
: setTimeout(() => {
|
|
77
|
+
refetchRef.current();
|
|
78
|
+
setAttempts((used) => used + 1);
|
|
79
|
+
}, UNAVAILABLE_RETRY_INTERVAL_MS);
|
|
80
|
+
return () => clearTimeout(handle);
|
|
81
|
+
}, [waiting, isFetching, attempts]);
|
|
82
|
+
return waiting;
|
|
83
|
+
}
|
|
84
|
+
/** Gap between post-restart re-reads. The daemon is a child of the API process and comes back in
|
|
85
|
+
* roughly three seconds, so this is a little under two boots — long enough that a slow boot is not
|
|
86
|
+
* spent on the first two attempts, short enough that the banner is not visibly lagging. */
|
|
87
|
+
const RESTART_WATCH_INTERVAL_MS = 2_500;
|
|
88
|
+
/** How many re-reads one accepted restart buys. Eight × 2.5s covers twenty seconds, which is far
|
|
89
|
+
* outside any observed daemon boot. Bounded rather than "until the snapshot changes" because
|
|
90
|
+
* nothing in the snapshot identifies WHICH daemon answered — a restart into an identical
|
|
91
|
+
* configuration produces a byte-identical reply, so "it changed" is not a signal that exists. */
|
|
92
|
+
const RESTART_WATCH_ATTEMPTS = 8;
|
|
93
|
+
/**
|
|
94
|
+
* A bounded re-read of the admissions snapshot, armed by an accepted restart.
|
|
95
|
+
*
|
|
96
|
+
* Not `invalidates: [ADMISSIONS_KEY]` on the restart mutation, and that is the whole design point.
|
|
97
|
+
* `POST .../system/assistant-daemon/restart` answers as soon as a restart has been INITIATED and
|
|
98
|
+
* structurally cannot wait for the new daemon to be healthy (that route's own header states this
|
|
99
|
+
* and points the caller at polling instead). A refetch fired on its 200 is therefore guaranteed to
|
|
100
|
+
* read the dying daemon or a 503 — it would replace one wrong answer with another and then stop.
|
|
101
|
+
*
|
|
102
|
+
* A chain of `setTimeout`s driven by the remaining-attempt count, rather than one `setInterval`:
|
|
103
|
+
* the count is the state the UI already needs to render (`watching`), so deriving the schedule from
|
|
104
|
+
* it keeps one source of truth and makes React's own cleanup cancel the pending read on unmount.
|
|
105
|
+
*
|
|
106
|
+
* @param input.refetch - The admissions query's `refetch`. Read through a ref so a change of query
|
|
107
|
+
* identity cannot re-arm the timer on every render — a spin, not a schedule. Jini keeps
|
|
108
|
+
* the callable stable while the cache entry stays the same.
|
|
109
|
+
* @complexity O(1) per attempt; at most {@link RESTART_WATCH_ATTEMPTS} attempts per accepted restart.
|
|
110
|
+
*/
|
|
111
|
+
function useRestartWatch({ refetch, setTimeout, clearTimeout }, _options = {}) {
|
|
112
|
+
const [attemptsLeft, setAttemptsLeft] = useState(0);
|
|
113
|
+
const refetchRef = useRef(refetch);
|
|
114
|
+
useEffect(() => {
|
|
115
|
+
refetchRef.current = refetch;
|
|
116
|
+
});
|
|
117
|
+
useEffect(() => {
|
|
118
|
+
// One arming expression and one cleanup, rather than an early `return` for the idle case:
|
|
119
|
+
// `clearTimeout(undefined)` is a specified no-op, so the idle render still yields a cleanup and
|
|
120
|
+
// the effect has a single exit.
|
|
121
|
+
const handle = attemptsLeft <= 0
|
|
122
|
+
? undefined
|
|
123
|
+
: setTimeout(() => {
|
|
124
|
+
refetchRef.current();
|
|
125
|
+
setAttemptsLeft((left) => left - 1);
|
|
126
|
+
}, RESTART_WATCH_INTERVAL_MS);
|
|
127
|
+
return () => clearTimeout(handle);
|
|
128
|
+
}, [attemptsLeft]);
|
|
129
|
+
const begin = useCallback(() => setAttemptsLeft(RESTART_WATCH_ATTEMPTS), []);
|
|
130
|
+
return { watching: attemptsLeft > 0, begin };
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* The click handler: fire the restart, record its outcome, and arm the post-restart watch only when
|
|
134
|
+
* the restart was ACCEPTED. A `{ok: false}` refusal ("shutting down") means nothing was restarted,
|
|
135
|
+
* so there is no new daemon to catch up to and re-reading would just re-fetch the same snapshot
|
|
136
|
+
* eight times.
|
|
137
|
+
*
|
|
138
|
+
* Split out of {@link useExternalMcpAdmissions} to keep that hook under the shop complexity ceiling.
|
|
139
|
+
*
|
|
140
|
+
* @complexity O(1).
|
|
141
|
+
*/
|
|
142
|
+
function useRestartAction({ mutate, setOutcome, beginRestartWatch, reportRestartFailure }, _options = {}) {
|
|
143
|
+
return useCallback(() => {
|
|
144
|
+
setOutcome(null);
|
|
145
|
+
// `mutate` reports a rejected restart through `restartCall.error`, but `.then` derives a new
|
|
146
|
+
// promise that needs a handler too; a failure in its success callback needs its own diagnostic.
|
|
147
|
+
void mutate({ input: undefined })
|
|
148
|
+
.then((result) => {
|
|
149
|
+
setOutcome(result);
|
|
150
|
+
if (result.ok)
|
|
151
|
+
beginRestartWatch();
|
|
152
|
+
}, () => { })
|
|
153
|
+
.catch((error) => reportRestartFailure(error));
|
|
154
|
+
}, [mutate, setOutcome, beginRestartWatch, reportRestartFailure]);
|
|
155
|
+
}
|
|
156
|
+
/** The route's own refusal reason, or `null`. Its 409 body carries `reason`; an older build that
|
|
157
|
+
* refuses without one still has to say something, so the fallback is a sentence rather than a
|
|
158
|
+
* silent `null` that would render as "the restart worked". */
|
|
159
|
+
function resolveRefusal({ outcome, t }, _options = {}) {
|
|
160
|
+
if (!outcome || outcome.ok)
|
|
161
|
+
return null;
|
|
162
|
+
return outcome.reason ?? t("the restart was refused");
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* @param deps.port - See {@link ExternalMcpAdmissionsPort}.
|
|
166
|
+
* @param deps.savedAllowedToolNamesById - Each roster card's own `allowedToolNames` field value,
|
|
167
|
+
* keyed by server id, plus its on/off toggle, so the banner can state saved-vs-live rather than
|
|
168
|
+
* only live — including for a saved connection the daemon never reported (ADM-001).
|
|
169
|
+
* @complexity O(c · t) in connections and their refused tools.
|
|
170
|
+
* @overallScore 100
|
|
171
|
+
*/
|
|
172
|
+
export function useExternalMcpAdmissions(deps, _optional = {}) {
|
|
173
|
+
const { port, savedAllowedToolNamesById, t, useFetchQuery, useFetchMutation, hasPermission, describeAdmissionDrift, admissionRestartHelps, driftCopy, describeApiError, isApiError, apiUnreachableCode, requestTimeoutCode, setTimeout, clearTimeout, reportRestartFailure } = deps;
|
|
174
|
+
const admissions = useFetchQuery({ key: ADMISSIONS_KEY, fetch: () => port.getAdmissions() });
|
|
175
|
+
const permissions = useFetchQuery({ key: PERMISSIONS_KEY, fetch: () => port.me() });
|
|
176
|
+
const restartCall = useFetchMutation({ run: () => port.restartAssistantDaemon() });
|
|
177
|
+
// `MutationResult` carries `status`/`error` but no `data`, and this route's "refused right now"
|
|
178
|
+
// outcome is a RESOLVED `{ ok: false, reason }` rather than a rejection (`api.ts`'s own comment on
|
|
179
|
+
// `restartAssistantDaemon`) — so the refusal reason has to be captured here or it is lost.
|
|
180
|
+
const [outcome, setOutcome] = useState(null);
|
|
181
|
+
const connections = useMemo(() => describeAdmissionDrift({ snapshot: admissions.data, savedById: savedAllowedToolNamesById, copy: driftCopy }), [admissions.data, savedAllowedToolNamesById, describeAdmissionDrift, driftCopy]);
|
|
182
|
+
const { watching, begin: beginRestartWatch } = useRestartWatch({ refetch: admissions.refetch, setTimeout, clearTimeout });
|
|
183
|
+
const restart = useRestartAction({ mutate: restartCall.mutate, setOutcome, beginRestartWatch, reportRestartFailure });
|
|
184
|
+
const waitingForAssistant = useUnavailableRetry({ failingTransiently: isAssistantStartingError({ error: admissions.error, isApiError, apiUnreachableCode, requestTimeoutCode }), isFetching: admissions.isFetching, refetch: admissions.refetch, setTimeout, clearTimeout });
|
|
185
|
+
const refusal = resolveRefusal({ outcome, t });
|
|
186
|
+
return {
|
|
187
|
+
loading: admissions.status === "loading",
|
|
188
|
+
unavailable: waitingForAssistant ? null : resolveUnavailable({ error: admissions.error, t, describeApiError }),
|
|
189
|
+
waitingForAssistant,
|
|
190
|
+
connections,
|
|
191
|
+
restartHelps: admissionRestartHelps({ connections }),
|
|
192
|
+
canRestart: hasPermission({ permissions: permissions.data?.effectivePermissions ?? [], permission: "system.write" }),
|
|
193
|
+
restarting: restartCall.status === "pending",
|
|
194
|
+
restartError: refusal ?? (restartCall.error ? describeApiError({ e: restartCall.error, fallback: t("Could not restart the assistant.") }) : null),
|
|
195
|
+
restartAccepted: outcome?.ok === true && watching,
|
|
196
|
+
restart,
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
export function bindExternalMcpAdmissions({ hooks, deps }, _optional = {}) {
|
|
200
|
+
return {
|
|
201
|
+
isAssistantStartingError: ({ error }, _optional = {}) => isAssistantStartingError({ error, ...deps }),
|
|
202
|
+
useExternalMcpAdmissions: ({ port, savedAllowedToolNamesById, t = (key) => key }, _optional = {}) => useExternalMcpAdmissions({ ...deps, ...hooks, port, savedAllowedToolNamesById, t }),
|
|
203
|
+
useWiredExternalMcpAdmissions: (savedAllowedToolNamesById, _optional = {}) => {
|
|
204
|
+
const t = hooks.useCopyHook();
|
|
205
|
+
return useExternalMcpAdmissions({ ...deps, ...hooks, savedAllowedToolNamesById, t });
|
|
206
|
+
},
|
|
207
|
+
};
|
|
208
|
+
}
|
|
209
|
+
//# sourceMappingURL=use-external-mcp-admissions.hooks.js.map
|