@shellui/core 0.7.0 → 0.8.1
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/LICENSE +21 -0
- package/README.md +3 -1
- package/package.json +2 -2
- package/schemas/shellui.config.schema.json +45 -2
- package/src/app.tsx +2 -0
- package/src/features/auth/AuthProvider.tsx +212 -97
- package/src/features/auth/appBackend/configSchema.spec.ts +1 -0
- package/src/features/auth/appBackend/frameAuth.ts +5 -0
- package/src/features/auth/backends/shellui.spec.ts +110 -0
- package/src/features/auth/backends/shellui.ts +47 -20
- package/src/features/auth/backends/types.ts +5 -0
- package/src/features/auth/hooks/useAuth.tsx +6 -1
- package/src/features/auth/types.ts +5 -0
- package/src/features/auth/utils/bffAuthClient.spec.ts +313 -0
- package/src/features/auth/utils/bffAuthClient.ts +171 -49
- package/src/features/auth/utils/buildSessionFromParams.ts +5 -2
- package/src/features/auth/utils/buildSessionFromTokenPayload.spec.ts +12 -0
- package/src/features/auth/utils/buildSessionFromTokenPayload.ts +3 -1
- package/src/features/auth/utils/canRestoreStoredSession.spec.ts +140 -4
- package/src/features/auth/utils/canRestoreStoredSession.ts +47 -0
- package/src/features/auth/utils/cliCallback.ts +5 -0
- package/src/features/auth/utils/identityBrowserLogout.spec.ts +185 -0
- package/src/features/auth/utils/identityBrowserLogout.ts +174 -0
- package/src/features/auth/utils/index.ts +21 -3
- package/src/features/auth/utils/isBffAuthEnabled.ts +10 -2
- package/src/features/auth/utils/normalizeAuthSettings.spec.ts +9 -0
- package/src/features/auth/utils/normalizeAuthSettings.ts +3 -1
- package/src/features/auth/utils/pkce.spec.ts +29 -1
- package/src/features/auth/utils/pkce.ts +106 -2
- package/src/features/config/types.ts +37 -5
- package/src/features/mcp/mcpActivityErrorCodeI18n.spec.ts +32 -0
- package/src/features/mcp/mcpActivityErrorCodeI18n.ts +30 -0
- package/src/features/mcp/mcpAgentActivityMerge.spec.ts +91 -0
- package/src/features/mcp/mcpAgentActivityMerge.ts +53 -0
- package/src/features/mcp/mcpAgentActivityPresentation.spec.ts +129 -0
- package/src/features/mcp/mcpAgentActivityPresentation.ts +201 -0
- package/src/features/mcp/mcpAgentsConnect.spec.ts +215 -0
- package/src/features/mcp/mcpAgentsConnect.ts +189 -0
- package/src/features/mcp/mcpToolActivityRegistry.spec.ts +9 -0
- package/src/features/mcp/mcpToolActivityRegistry.ts +20 -0
- package/src/features/mcp/mcpToolApprovalsApi.spec.ts +113 -0
- package/src/features/mcp/mcpToolApprovalsApi.ts +162 -0
- package/src/features/mcp/personalAgentsApi.spec.ts +661 -0
- package/src/features/mcp/personalAgentsApi.ts +697 -0
- package/src/features/settings/SettingsIcons.tsx +28 -0
- package/src/features/settings/SettingsRoutes.tsx +8 -0
- package/src/features/settings/SettingsView.tsx +90 -26
- package/src/features/settings/components/McpAgentActivitySection.spec.tsx +255 -0
- package/src/features/settings/components/McpAgentActivitySection.tsx +481 -0
- package/src/features/settings/components/McpAgents.spec.tsx +336 -0
- package/src/features/settings/components/McpAgents.tsx +654 -0
- package/src/features/settings/components/McpPendingApprovals.spec.tsx +201 -0
- package/src/features/settings/components/McpPendingApprovals.tsx +168 -0
- package/src/features/settings/components/McpPersonalStatusPrefetch.tsx +21 -0
- package/src/features/settings/hooks/useMcpPendingToolApprovals.ts +69 -0
- package/src/features/settings/hooks/useMcpPersonalStatus.ts +83 -0
- package/src/features/settings/utils/buildSettingsForPropagation.spec.ts +44 -1
- package/src/features/settings/utils/buildSettingsForPropagation.ts +30 -1
- package/src/features/settings/utils/isMcpAgentsSettingsEligible.spec.ts +25 -0
- package/src/features/settings/utils/isMcpAgentsSettingsEligible.ts +14 -0
- package/src/features/settings/utils/loadMcpPersonalStatus.spec.ts +76 -0
- package/src/features/settings/utils/loadMcpPersonalStatus.ts +84 -0
- package/src/features/settings/utils/mcpPersonalStatusCache.spec.ts +77 -0
- package/src/features/settings/utils/mcpPersonalStatusCache.ts +95 -0
- package/src/features/settings/utils/shouldShowMcpAgentsSettings.spec.ts +66 -0
- package/src/features/settings/utils/shouldShowMcpAgentsSettings.ts +16 -0
- package/src/features/storage/StorageBridge.paths.spec.ts +286 -0
- package/src/features/storage/StorageBridge.tsx +25 -5
- package/src/features/storage/resolveStorageBridgeTarget.spec.ts +51 -0
- package/src/features/storage/resolveStorageBridgeTarget.ts +24 -0
- package/src/i18n/translations/en/settings.json +201 -0
- package/src/i18n/translations/fr/settings.json +201 -0
- package/src/index.ts +1 -0
- package/src/service-worker/sw.ts +4 -2
|
@@ -0,0 +1,697 @@
|
|
|
1
|
+
import type { ShellUIConfig } from '../config/types';
|
|
2
|
+
import { getShellUILoginCompanyId } from '../auth/utils/clientLoginContext';
|
|
3
|
+
|
|
4
|
+
export type McpAgentKind = 'oauth' | 'personal';
|
|
5
|
+
export type McpAccessMode = 'read_only' | 'ask' | 'full';
|
|
6
|
+
export type McpReadLevel = 'safe' | 'sensitive';
|
|
7
|
+
|
|
8
|
+
/** Selectable services for personal agent tokens (`ai` is always added server-side). */
|
|
9
|
+
export const MCP_PERSONAL_SERVICE_OPTIONS = [
|
|
10
|
+
'identity',
|
|
11
|
+
'storage',
|
|
12
|
+
'hosting',
|
|
13
|
+
'email',
|
|
14
|
+
'saas',
|
|
15
|
+
] as const;
|
|
16
|
+
|
|
17
|
+
export type McpPersonalService = (typeof MCP_PERSONAL_SERVICE_OPTIONS)[number];
|
|
18
|
+
|
|
19
|
+
export type McpPersonalStatus = {
|
|
20
|
+
mcpEnabled: boolean;
|
|
21
|
+
mcpUrl: string | null;
|
|
22
|
+
/**
|
|
23
|
+
* Full global MCP URL from identity: trusted `DASHBOARD_PUBLIC_URL` without a trailing slash, plus `/mcp`.
|
|
24
|
+
* Validated http(s) URL with path `/mcp` only. Identity may omit until ready. Use as the direct MCP endpoint in UI.
|
|
25
|
+
*/
|
|
26
|
+
globalMcpUrl: string | null;
|
|
27
|
+
/** When false, the signed-in session is regional-only (no saas grant). */
|
|
28
|
+
globalIdentity?: boolean;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
export type McpAgentSummary = {
|
|
32
|
+
id: string;
|
|
33
|
+
kind: McpAgentKind;
|
|
34
|
+
name: string;
|
|
35
|
+
accessMode: McpAccessMode;
|
|
36
|
+
readLevel: McpReadLevel;
|
|
37
|
+
allowDestructiveWithoutAsking: boolean;
|
|
38
|
+
servicesAllowed: string[];
|
|
39
|
+
expiresAt: string | null;
|
|
40
|
+
pausedAt: string | null;
|
|
41
|
+
revokedAt: string | null;
|
|
42
|
+
isActive: boolean;
|
|
43
|
+
createdAt: string;
|
|
44
|
+
oauthClientId: string | null;
|
|
45
|
+
personalTokenId: string | null;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
export type McpActivityAccessKind = 'read' | 'write' | 'destructive' | 'unknown';
|
|
49
|
+
|
|
50
|
+
export type McpActivityOutcomeKind =
|
|
51
|
+
| 'allowed'
|
|
52
|
+
| 'denied'
|
|
53
|
+
| 'failed'
|
|
54
|
+
| 'pending_approval'
|
|
55
|
+
| 'session_used'
|
|
56
|
+
| 'unknown';
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Identity `error_code` for activity rows: fixed allowlist from identity (and gateway when present).
|
|
60
|
+
* Parse accepts only these tokens (contract tests); settings maps each to translated labels only.
|
|
61
|
+
*/
|
|
62
|
+
export type McpActivityErrorCode =
|
|
63
|
+
| 'bad_request'
|
|
64
|
+
| 'unauthorized'
|
|
65
|
+
| 'forbidden'
|
|
66
|
+
| 'not_found'
|
|
67
|
+
| 'conflict'
|
|
68
|
+
| 'rate_limited'
|
|
69
|
+
| 'denied'
|
|
70
|
+
| 'expired'
|
|
71
|
+
| 'timeout'
|
|
72
|
+
| 'upstream_error'
|
|
73
|
+
| 'internal_error'
|
|
74
|
+
| 'out_of_sync'
|
|
75
|
+
| 'identity_unreachable'
|
|
76
|
+
| 'identity_unavailable'
|
|
77
|
+
| 'identity_invalid'
|
|
78
|
+
| 'invalid_grant'
|
|
79
|
+
| 'permission_changed'
|
|
80
|
+
| 'request_expired'
|
|
81
|
+
| 'agent_revoked'
|
|
82
|
+
| 'downstream_error'
|
|
83
|
+
| 'server_error'
|
|
84
|
+
| 'unknown';
|
|
85
|
+
|
|
86
|
+
export type McpAgentActivityRow = {
|
|
87
|
+
timestamp: string;
|
|
88
|
+
tool: string;
|
|
89
|
+
service: string;
|
|
90
|
+
result: string;
|
|
91
|
+
clientIp: string | null;
|
|
92
|
+
/** When the row refers to a specific company (often global MCP). */
|
|
93
|
+
companyId: string | null;
|
|
94
|
+
/** Human label for the company when the API provides one. */
|
|
95
|
+
companyLabel: string | null;
|
|
96
|
+
/** Safe description of the target resource (no secrets, query strings, or raw args). */
|
|
97
|
+
resourceLabel: string | null;
|
|
98
|
+
/** Human title for the operation when identity sends it (preferred over local tool registry). */
|
|
99
|
+
operationTitle: string | null;
|
|
100
|
+
/** Actor that performed the action when provided by the API. */
|
|
101
|
+
actorLabel: string | null;
|
|
102
|
+
/** Connected agent or client name when provided. */
|
|
103
|
+
agentName: string | null;
|
|
104
|
+
/** Explicit access classification when provided. */
|
|
105
|
+
accessKind: McpActivityAccessKind | null;
|
|
106
|
+
/** Request duration in milliseconds when provided. */
|
|
107
|
+
durationMs: number | null;
|
|
108
|
+
/** Machine-readable outcome when provided (preferred over inferring from `result`). */
|
|
109
|
+
outcome: McpActivityOutcomeKind | null;
|
|
110
|
+
/** Linked pending approval id when provided (matches approvals list). */
|
|
111
|
+
approvalRequestId: string | null;
|
|
112
|
+
/** Allowlisted machine error from identity or ai-service; UI maps to translated labels only. */
|
|
113
|
+
errorCode: McpActivityErrorCode | null;
|
|
114
|
+
/**
|
|
115
|
+
* Redacted failure text from an ai-service call log.
|
|
116
|
+
* Identity activity parsing leaves this unset.
|
|
117
|
+
*/
|
|
118
|
+
errorMessage?: string | null;
|
|
119
|
+
/** Set when the gateway ran the tool through a wrapper such as `ai_call_tool`. */
|
|
120
|
+
wrapperTool?: string | null;
|
|
121
|
+
/** Stored approval result, such as `accepted`, `denied`, or `session_used`. */
|
|
122
|
+
approvalOutcome?: string | null;
|
|
123
|
+
};
|
|
124
|
+
|
|
125
|
+
export type CreatePersonalAgentInput = {
|
|
126
|
+
name: string;
|
|
127
|
+
services: McpPersonalService[];
|
|
128
|
+
accessMode: McpAccessMode;
|
|
129
|
+
readLevel: McpReadLevel;
|
|
130
|
+
allowDestructive: boolean;
|
|
131
|
+
expiresAt: string;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
export type CreatePersonalAgentResult = {
|
|
135
|
+
agent: McpAgentSummary;
|
|
136
|
+
accessToken: string;
|
|
137
|
+
tokenType: string;
|
|
138
|
+
expiresAt: string;
|
|
139
|
+
resource: string;
|
|
140
|
+
};
|
|
141
|
+
|
|
142
|
+
export const getShellIdentityBackendUrl = (config: ShellUIConfig | undefined): string | null => {
|
|
143
|
+
if (config?.backend?.type !== 'shellui') return null;
|
|
144
|
+
const url = config.backend.url?.trim().replace(/\/+$/, '') || '';
|
|
145
|
+
return url || null;
|
|
146
|
+
};
|
|
147
|
+
|
|
148
|
+
export const getMcpPersonalCompanyId = (config: ShellUIConfig | undefined): string => {
|
|
149
|
+
return getShellUILoginCompanyId(config?.backend?.companyId);
|
|
150
|
+
};
|
|
151
|
+
|
|
152
|
+
const asString = (value: unknown): string | null =>
|
|
153
|
+
typeof value === 'string' && value.trim() ? value.trim() : null;
|
|
154
|
+
|
|
155
|
+
const asBool = (value: unknown): boolean => value === true;
|
|
156
|
+
|
|
157
|
+
const asStringArray = (value: unknown): string[] => {
|
|
158
|
+
if (!Array.isArray(value)) return [];
|
|
159
|
+
return value.filter((item): item is string => typeof item === 'string' && item.trim() !== '');
|
|
160
|
+
};
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* Identity `global_mcp_url`: full MCP endpoint `https?://host/mcp` (no query, hash, userinfo).
|
|
164
|
+
* Rejects a bare origin, `/mcp/mcp`, or any path other than `/mcp`.
|
|
165
|
+
*/
|
|
166
|
+
export function parseValidatedGlobalMcpEndpointUrl(raw: unknown): string | null {
|
|
167
|
+
const s = asString(raw);
|
|
168
|
+
if (!s) return null;
|
|
169
|
+
try {
|
|
170
|
+
const u = new URL(s);
|
|
171
|
+
if (u.protocol !== 'http:' && u.protocol !== 'https:') return null;
|
|
172
|
+
if (u.username || u.password) return null;
|
|
173
|
+
if (u.search || u.hash) return null;
|
|
174
|
+
const path = (u.pathname || '/').replace(/\/+$/, '') || '/';
|
|
175
|
+
if (path !== '/mcp') return null;
|
|
176
|
+
return `${u.origin}/mcp`;
|
|
177
|
+
} catch {
|
|
178
|
+
return null;
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export const parseMcpPersonalStatus = (payload: unknown): McpPersonalStatus | null => {
|
|
183
|
+
if (!payload || typeof payload !== 'object') return null;
|
|
184
|
+
const record = payload as Record<string, unknown>;
|
|
185
|
+
if (typeof record.mcp_enabled !== 'boolean') return null;
|
|
186
|
+
const mcpUrl = asString(record.mcp_url);
|
|
187
|
+
const globalMcpUrl = parseValidatedGlobalMcpEndpointUrl(record.global_mcp_url);
|
|
188
|
+
const globalIdentity =
|
|
189
|
+
typeof record.global_identity === 'boolean' ? record.global_identity : undefined;
|
|
190
|
+
return {
|
|
191
|
+
mcpEnabled: record.mcp_enabled,
|
|
192
|
+
mcpUrl,
|
|
193
|
+
globalMcpUrl,
|
|
194
|
+
...(globalIdentity !== undefined ? { globalIdentity } : {}),
|
|
195
|
+
};
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
export const parseMcpAgentSummary = (value: unknown): McpAgentSummary | null => {
|
|
199
|
+
if (!value || typeof value !== 'object') return null;
|
|
200
|
+
const record = value as Record<string, unknown>;
|
|
201
|
+
const id = asString(record.id);
|
|
202
|
+
const kind = asString(record.kind);
|
|
203
|
+
const name = asString(record.name);
|
|
204
|
+
const accessMode = asString(record.access_mode);
|
|
205
|
+
const readLevel = asString(record.read_level);
|
|
206
|
+
const createdAt = asString(record.created_at);
|
|
207
|
+
if (!id || !kind || !name || !accessMode || !readLevel || !createdAt) return null;
|
|
208
|
+
if (kind !== 'oauth' && kind !== 'personal') return null;
|
|
209
|
+
if (accessMode !== 'read_only' && accessMode !== 'ask' && accessMode !== 'full') return null;
|
|
210
|
+
if (readLevel !== 'safe' && readLevel !== 'sensitive') return null;
|
|
211
|
+
return {
|
|
212
|
+
id,
|
|
213
|
+
kind,
|
|
214
|
+
name,
|
|
215
|
+
accessMode,
|
|
216
|
+
readLevel,
|
|
217
|
+
allowDestructiveWithoutAsking: asBool(record.allow_destructive_without_asking),
|
|
218
|
+
servicesAllowed: asStringArray(record.services_allowed),
|
|
219
|
+
expiresAt: asString(record.expires_at),
|
|
220
|
+
pausedAt: asString(record.paused_at),
|
|
221
|
+
revokedAt: asString(record.revoked_at),
|
|
222
|
+
isActive: asBool(record.is_active),
|
|
223
|
+
createdAt,
|
|
224
|
+
oauthClientId: asString(record.oauth_client_id),
|
|
225
|
+
personalTokenId: asString(record.personal_token_id),
|
|
226
|
+
};
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
export const parseMcpAgentList = (payload: unknown): McpAgentSummary[] => {
|
|
230
|
+
if (!payload || typeof payload !== 'object') return [];
|
|
231
|
+
const agents = (payload as Record<string, unknown>).agents;
|
|
232
|
+
if (!Array.isArray(agents)) return [];
|
|
233
|
+
return agents
|
|
234
|
+
.map((row) => parseMcpAgentSummary(row))
|
|
235
|
+
.filter((row): row is McpAgentSummary => row !== null);
|
|
236
|
+
};
|
|
237
|
+
|
|
238
|
+
const asNumber = (value: unknown): number | null => {
|
|
239
|
+
if (typeof value === 'number' && Number.isFinite(value)) return value;
|
|
240
|
+
if (typeof value === 'string' && value.trim()) {
|
|
241
|
+
const n = Number(value);
|
|
242
|
+
if (Number.isFinite(n)) return n;
|
|
243
|
+
}
|
|
244
|
+
return null;
|
|
245
|
+
};
|
|
246
|
+
|
|
247
|
+
const normEnum = (value: string): string =>
|
|
248
|
+
value
|
|
249
|
+
.trim()
|
|
250
|
+
.toLowerCase()
|
|
251
|
+
.replace(/[\s-]+/g, '_');
|
|
252
|
+
|
|
253
|
+
/** Identity `access_kind`: exact tokens only. */
|
|
254
|
+
const parseAccessKind = (value: unknown): McpActivityAccessKind | null => {
|
|
255
|
+
const s = asString(value);
|
|
256
|
+
if (!s) return null;
|
|
257
|
+
const n = normEnum(s);
|
|
258
|
+
if (n === 'read' || n === 'read_only' || n === 'readonly') return 'read';
|
|
259
|
+
if (n === 'write') return 'write';
|
|
260
|
+
if (n === 'destructive') return 'destructive';
|
|
261
|
+
if (n === 'unknown') return 'unknown';
|
|
262
|
+
return null;
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
/** Identity `outcome`: exact tokens only (no substring matching). */
|
|
266
|
+
export const parseStrictMcpActivityOutcome = (value: unknown): McpActivityOutcomeKind | null => {
|
|
267
|
+
const s = asString(value);
|
|
268
|
+
if (!s) return null;
|
|
269
|
+
const n = normEnum(s);
|
|
270
|
+
if (
|
|
271
|
+
n === 'allowed' ||
|
|
272
|
+
n === 'ok' ||
|
|
273
|
+
n === 'success' ||
|
|
274
|
+
n === 'allow' ||
|
|
275
|
+
n === 'allow_success' ||
|
|
276
|
+
n === 'allowed_success'
|
|
277
|
+
)
|
|
278
|
+
return 'allowed';
|
|
279
|
+
if (n === 'denied' || n === 'forbidden') return 'denied';
|
|
280
|
+
if (n === 'failed' || n === 'error') return 'failed';
|
|
281
|
+
if (
|
|
282
|
+
n === 'pending' ||
|
|
283
|
+
n === 'pending_approval' ||
|
|
284
|
+
n === 'awaiting_approval' ||
|
|
285
|
+
n === 'waiting_approval'
|
|
286
|
+
)
|
|
287
|
+
return 'pending_approval';
|
|
288
|
+
if (n === 'session_used' || n === 'session') return 'session_used';
|
|
289
|
+
if (n === 'unknown') return 'unknown';
|
|
290
|
+
return null;
|
|
291
|
+
};
|
|
292
|
+
|
|
293
|
+
export const MCP_ACTIVITY_ERROR_CODES: readonly McpActivityErrorCode[] = [
|
|
294
|
+
'bad_request',
|
|
295
|
+
'unauthorized',
|
|
296
|
+
'forbidden',
|
|
297
|
+
'not_found',
|
|
298
|
+
'conflict',
|
|
299
|
+
'rate_limited',
|
|
300
|
+
'denied',
|
|
301
|
+
'expired',
|
|
302
|
+
'timeout',
|
|
303
|
+
'upstream_error',
|
|
304
|
+
'internal_error',
|
|
305
|
+
'out_of_sync',
|
|
306
|
+
'identity_unreachable',
|
|
307
|
+
'identity_unavailable',
|
|
308
|
+
'identity_invalid',
|
|
309
|
+
'invalid_grant',
|
|
310
|
+
'permission_changed',
|
|
311
|
+
'request_expired',
|
|
312
|
+
'agent_revoked',
|
|
313
|
+
'downstream_error',
|
|
314
|
+
'server_error',
|
|
315
|
+
'unknown',
|
|
316
|
+
] as const;
|
|
317
|
+
|
|
318
|
+
export const parseStrictMcpActivityErrorCode = (value: unknown): McpActivityErrorCode | null => {
|
|
319
|
+
const s = asString(value);
|
|
320
|
+
if (!s) return null;
|
|
321
|
+
const n = normEnum(s);
|
|
322
|
+
return (MCP_ACTIVITY_ERROR_CODES as readonly string[]).includes(n)
|
|
323
|
+
? (n as McpActivityErrorCode)
|
|
324
|
+
: null;
|
|
325
|
+
};
|
|
326
|
+
|
|
327
|
+
export const parseMcpAgentActivity = (
|
|
328
|
+
payload: unknown,
|
|
329
|
+
): { agentId: string; activity: McpAgentActivityRow[] } | null => {
|
|
330
|
+
if (!payload || typeof payload !== 'object') return null;
|
|
331
|
+
const record = payload as Record<string, unknown>;
|
|
332
|
+
const agentId = asString(record.agent_id);
|
|
333
|
+
if (!agentId) return null;
|
|
334
|
+
const rows = Array.isArray(record.activity) ? record.activity : [];
|
|
335
|
+
const activity: McpAgentActivityRow[] = [];
|
|
336
|
+
for (const row of rows) {
|
|
337
|
+
if (!row || typeof row !== 'object') continue;
|
|
338
|
+
const item = row as Record<string, unknown>;
|
|
339
|
+
const timestamp = asString(item.timestamp);
|
|
340
|
+
const tool = asString(item.tool);
|
|
341
|
+
const service = asString(item.service);
|
|
342
|
+
const result = asString(item.result);
|
|
343
|
+
if (!timestamp || !tool || !service || !result) continue;
|
|
344
|
+
const durationRaw = asNumber(item.duration_ms);
|
|
345
|
+
const durationMs =
|
|
346
|
+
durationRaw !== null && durationRaw >= 0 && Number.isFinite(durationRaw) ? durationRaw : null;
|
|
347
|
+
activity.push({
|
|
348
|
+
timestamp,
|
|
349
|
+
tool,
|
|
350
|
+
service,
|
|
351
|
+
result,
|
|
352
|
+
clientIp: asString(item.client_ip),
|
|
353
|
+
companyId: asString(item.company_id),
|
|
354
|
+
companyLabel: asString(item.company_name),
|
|
355
|
+
resourceLabel: asString(item.resource_label),
|
|
356
|
+
operationTitle: asString(item.operation_title),
|
|
357
|
+
actorLabel: asString(item.actor),
|
|
358
|
+
agentName: asString(item.agent_name),
|
|
359
|
+
accessKind: parseAccessKind(item.access_kind),
|
|
360
|
+
durationMs,
|
|
361
|
+
outcome: parseStrictMcpActivityOutcome(item.outcome),
|
|
362
|
+
approvalRequestId: asString(item.approval_request_id),
|
|
363
|
+
errorCode: parseStrictMcpActivityErrorCode(item.error_code),
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
return { agentId, activity };
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
export const parseCreatePersonalAgentResult = (
|
|
370
|
+
payload: unknown,
|
|
371
|
+
): CreatePersonalAgentResult | null => {
|
|
372
|
+
if (!payload || typeof payload !== 'object') return null;
|
|
373
|
+
const record = payload as Record<string, unknown>;
|
|
374
|
+
const agent = parseMcpAgentSummary(record.agent);
|
|
375
|
+
const accessToken = asString(record.access_token);
|
|
376
|
+
const tokenType = asString(record.token_type);
|
|
377
|
+
const expiresAt = asString(record.expires_at);
|
|
378
|
+
const resource = asString(record.resource);
|
|
379
|
+
if (!agent || !accessToken || !tokenType || !expiresAt || !resource) return null;
|
|
380
|
+
return { agent, accessToken, tokenType, expiresAt, resource };
|
|
381
|
+
};
|
|
382
|
+
|
|
383
|
+
export class McpPersonalApiError extends Error {
|
|
384
|
+
readonly status: number;
|
|
385
|
+
|
|
386
|
+
constructor(message: string, status: number) {
|
|
387
|
+
super(message);
|
|
388
|
+
this.name = 'McpPersonalApiError';
|
|
389
|
+
this.status = status;
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
const buildUrl = (backendUrl: string, path: string, companyId: string): URL => {
|
|
394
|
+
const url = new URL(`${backendUrl.replace(/\/+$/, '')}${path}`);
|
|
395
|
+
if (companyId) {
|
|
396
|
+
url.searchParams.set('company_id', companyId);
|
|
397
|
+
}
|
|
398
|
+
return url;
|
|
399
|
+
};
|
|
400
|
+
|
|
401
|
+
async function mcpJsonRequest<T>(
|
|
402
|
+
backendUrl: string,
|
|
403
|
+
accessToken: string,
|
|
404
|
+
companyId: string,
|
|
405
|
+
path: string,
|
|
406
|
+
init: RequestInit,
|
|
407
|
+
parse: (payload: unknown) => T | null,
|
|
408
|
+
): Promise<T> {
|
|
409
|
+
const url = buildUrl(backendUrl, path, companyId);
|
|
410
|
+
const headers: Record<string, string> = {
|
|
411
|
+
Accept: 'application/json',
|
|
412
|
+
Authorization: `Bearer ${accessToken}`,
|
|
413
|
+
};
|
|
414
|
+
if (init.body) {
|
|
415
|
+
headers['Content-Type'] = 'application/json';
|
|
416
|
+
}
|
|
417
|
+
const response = await fetch(url.toString(), {
|
|
418
|
+
...init,
|
|
419
|
+
headers: { ...headers, ...init.headers },
|
|
420
|
+
});
|
|
421
|
+
const payload = await response.json().catch(() => null);
|
|
422
|
+
if (!response.ok) {
|
|
423
|
+
let message = `HTTP ${response.status}`;
|
|
424
|
+
if (payload && typeof payload === 'object') {
|
|
425
|
+
const record = payload as Record<string, unknown>;
|
|
426
|
+
const err = record.error ?? record.detail;
|
|
427
|
+
if (typeof err === 'string' && err.trim()) message = err.trim();
|
|
428
|
+
}
|
|
429
|
+
throw new McpPersonalApiError(message, response.status);
|
|
430
|
+
}
|
|
431
|
+
const parsed = parse(payload);
|
|
432
|
+
if (!parsed) {
|
|
433
|
+
throw new McpPersonalApiError('Unexpected response from identity.', response.status);
|
|
434
|
+
}
|
|
435
|
+
return parsed;
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
export const fetchMcpPersonalStatus = (
|
|
439
|
+
backendUrl: string,
|
|
440
|
+
accessToken: string,
|
|
441
|
+
companyId: string,
|
|
442
|
+
): Promise<McpPersonalStatus> =>
|
|
443
|
+
mcpJsonRequest(
|
|
444
|
+
backendUrl,
|
|
445
|
+
accessToken,
|
|
446
|
+
companyId,
|
|
447
|
+
'/api/v1/mcp/personal/status',
|
|
448
|
+
{ method: 'GET' },
|
|
449
|
+
parseMcpPersonalStatus,
|
|
450
|
+
);
|
|
451
|
+
|
|
452
|
+
export const fetchMcpPersonalAgents = (
|
|
453
|
+
backendUrl: string,
|
|
454
|
+
accessToken: string,
|
|
455
|
+
companyId: string,
|
|
456
|
+
): Promise<McpAgentSummary[]> =>
|
|
457
|
+
mcpJsonRequest(
|
|
458
|
+
backendUrl,
|
|
459
|
+
accessToken,
|
|
460
|
+
companyId,
|
|
461
|
+
'/api/v1/mcp/personal/agents',
|
|
462
|
+
{ method: 'GET' },
|
|
463
|
+
(payload) => parseMcpAgentList(payload),
|
|
464
|
+
);
|
|
465
|
+
|
|
466
|
+
export type CreateMcpPersonalAgentOptions = {
|
|
467
|
+
/** When false, `saas` is removed from the request (regional identity surfaces). */
|
|
468
|
+
allowSaas?: boolean;
|
|
469
|
+
};
|
|
470
|
+
|
|
471
|
+
export const createMcpPersonalAgent = (
|
|
472
|
+
backendUrl: string,
|
|
473
|
+
accessToken: string,
|
|
474
|
+
companyId: string,
|
|
475
|
+
input: CreatePersonalAgentInput,
|
|
476
|
+
options: CreateMcpPersonalAgentOptions = {},
|
|
477
|
+
): Promise<CreatePersonalAgentResult> => {
|
|
478
|
+
const allowSaas = options.allowSaas === true;
|
|
479
|
+
const services = allowSaas
|
|
480
|
+
? input.services
|
|
481
|
+
: input.services.filter((service) => service !== 'saas');
|
|
482
|
+
return mcpJsonRequest(
|
|
483
|
+
backendUrl,
|
|
484
|
+
accessToken,
|
|
485
|
+
companyId,
|
|
486
|
+
'/api/v1/mcp/personal/agents/create',
|
|
487
|
+
{
|
|
488
|
+
method: 'POST',
|
|
489
|
+
body: JSON.stringify({
|
|
490
|
+
name: input.name,
|
|
491
|
+
services,
|
|
492
|
+
access_mode: input.accessMode,
|
|
493
|
+
read_level: input.readLevel,
|
|
494
|
+
allow_destructive: input.allowDestructive,
|
|
495
|
+
expires_at: input.expiresAt,
|
|
496
|
+
}),
|
|
497
|
+
},
|
|
498
|
+
parseCreatePersonalAgentResult,
|
|
499
|
+
);
|
|
500
|
+
};
|
|
501
|
+
|
|
502
|
+
export const revokeMcpPersonalAgent = (
|
|
503
|
+
backendUrl: string,
|
|
504
|
+
accessToken: string,
|
|
505
|
+
companyId: string,
|
|
506
|
+
agentId: string,
|
|
507
|
+
): Promise<McpAgentSummary> =>
|
|
508
|
+
mcpJsonRequest(
|
|
509
|
+
backendUrl,
|
|
510
|
+
accessToken,
|
|
511
|
+
companyId,
|
|
512
|
+
`/api/v1/mcp/personal/agents/${encodeURIComponent(agentId)}/revoke`,
|
|
513
|
+
{ method: 'POST' },
|
|
514
|
+
(payload) => {
|
|
515
|
+
if (!payload || typeof payload !== 'object') return null;
|
|
516
|
+
return parseMcpAgentSummary((payload as Record<string, unknown>).agent);
|
|
517
|
+
},
|
|
518
|
+
);
|
|
519
|
+
|
|
520
|
+
export const fetchMcpPersonalAgentActivity = (
|
|
521
|
+
backendUrl: string,
|
|
522
|
+
accessToken: string,
|
|
523
|
+
companyId: string,
|
|
524
|
+
agentId: string,
|
|
525
|
+
): Promise<McpAgentActivityRow[]> =>
|
|
526
|
+
mcpJsonRequest(
|
|
527
|
+
backendUrl,
|
|
528
|
+
accessToken,
|
|
529
|
+
companyId,
|
|
530
|
+
`/api/v1/mcp/personal/agents/${encodeURIComponent(agentId)}/activity`,
|
|
531
|
+
{ method: 'GET' },
|
|
532
|
+
(payload) => parseMcpAgentActivity(payload)?.activity ?? null,
|
|
533
|
+
);
|
|
534
|
+
|
|
535
|
+
/** Default page size for `GET /ai/v1/mcp/personal/agents/{id}/call-logs`. */
|
|
536
|
+
export const MCP_PERSONAL_CALL_LOG_PAGE_SIZE = 50;
|
|
537
|
+
|
|
538
|
+
const MCP_PERSONAL_CALL_LOG_MAX_PAGE_SIZE = 200;
|
|
539
|
+
|
|
540
|
+
export type McpPersonalCallLogPage = {
|
|
541
|
+
count: number;
|
|
542
|
+
limit: number;
|
|
543
|
+
offset: number;
|
|
544
|
+
callLogs: McpAgentActivityRow[];
|
|
545
|
+
};
|
|
546
|
+
|
|
547
|
+
export type FetchMcpPersonalCallLogsOptions = {
|
|
548
|
+
limit?: number;
|
|
549
|
+
offset?: number;
|
|
550
|
+
};
|
|
551
|
+
|
|
552
|
+
const clampPageLimit = (value: number | undefined): number => {
|
|
553
|
+
const raw = value ?? MCP_PERSONAL_CALL_LOG_PAGE_SIZE;
|
|
554
|
+
if (!Number.isFinite(raw)) return MCP_PERSONAL_CALL_LOG_PAGE_SIZE;
|
|
555
|
+
return Math.min(MCP_PERSONAL_CALL_LOG_MAX_PAGE_SIZE, Math.max(1, Math.floor(raw)));
|
|
556
|
+
};
|
|
557
|
+
|
|
558
|
+
const clampPageOffset = (value: number | undefined): number => {
|
|
559
|
+
if (value === undefined || !Number.isFinite(value)) return 0;
|
|
560
|
+
return Math.max(0, Math.floor(value));
|
|
561
|
+
};
|
|
562
|
+
|
|
563
|
+
const asCompanyId = (value: unknown): string | null => {
|
|
564
|
+
if (typeof value === 'number' && Number.isFinite(value)) return String(Math.trunc(value));
|
|
565
|
+
return asString(value);
|
|
566
|
+
};
|
|
567
|
+
|
|
568
|
+
/** Map one ai-service call log onto the activity row the settings list already renders. */
|
|
569
|
+
export const parseMcpCallLogActivityRow = (value: unknown): McpAgentActivityRow | null => {
|
|
570
|
+
if (!value || typeof value !== 'object') return null;
|
|
571
|
+
const item = value as Record<string, unknown>;
|
|
572
|
+
const timestamp = asString(item.created_at);
|
|
573
|
+
const tool = asString(item.tool_name);
|
|
574
|
+
if (!timestamp || !tool) return null;
|
|
575
|
+
const outcome =
|
|
576
|
+
parseStrictMcpActivityOutcome(item.outcome) ?? parseStrictMcpActivityOutcome(item.status);
|
|
577
|
+
const result = asString(item.outcome) ?? asString(item.status) ?? '';
|
|
578
|
+
const durationRaw = asNumber(item.duration_ms);
|
|
579
|
+
const durationMs =
|
|
580
|
+
durationRaw !== null && durationRaw >= 0 && Number.isFinite(durationRaw) ? durationRaw : null;
|
|
581
|
+
const errorMessage = asString(item.error_message);
|
|
582
|
+
const wrapperTool = asString(item.wrapper_tool);
|
|
583
|
+
const approvalOutcome = asString(item.approval_outcome);
|
|
584
|
+
return {
|
|
585
|
+
timestamp,
|
|
586
|
+
tool,
|
|
587
|
+
service: asString(item.service) ?? '',
|
|
588
|
+
result,
|
|
589
|
+
clientIp: null,
|
|
590
|
+
companyId: asCompanyId(item.company_id),
|
|
591
|
+
companyLabel: null,
|
|
592
|
+
resourceLabel: asString(item.resource_label),
|
|
593
|
+
operationTitle: asString(item.operation_title),
|
|
594
|
+
actorLabel: asString(item.user_email),
|
|
595
|
+
agentName: asString(item.agent_name),
|
|
596
|
+
accessKind: parseAccessKind(item.access_kind),
|
|
597
|
+
durationMs,
|
|
598
|
+
outcome,
|
|
599
|
+
approvalRequestId: asString(item.approval_id),
|
|
600
|
+
errorCode: parseStrictMcpActivityErrorCode(item.error_code),
|
|
601
|
+
...(errorMessage ? { errorMessage } : {}),
|
|
602
|
+
...(wrapperTool ? { wrapperTool } : {}),
|
|
603
|
+
...(approvalOutcome ? { approvalOutcome } : {}),
|
|
604
|
+
};
|
|
605
|
+
};
|
|
606
|
+
|
|
607
|
+
export const parseMcpPersonalCallLogPage = (payload: unknown): McpPersonalCallLogPage | null => {
|
|
608
|
+
if (!payload || typeof payload !== 'object') return null;
|
|
609
|
+
const record = payload as Record<string, unknown>;
|
|
610
|
+
const { count, limit, offset } = record;
|
|
611
|
+
if (typeof count !== 'number' || !Number.isFinite(count) || count < 0) return null;
|
|
612
|
+
if (typeof limit !== 'number' || !Number.isFinite(limit) || limit < 1 || limit > 200) return null;
|
|
613
|
+
if (typeof offset !== 'number' || !Number.isFinite(offset) || offset < 0) return null;
|
|
614
|
+
if (!Array.isArray(record.call_logs)) return null;
|
|
615
|
+
const callLogs = record.call_logs
|
|
616
|
+
.map((row) => parseMcpCallLogActivityRow(row))
|
|
617
|
+
.filter((row): row is McpAgentActivityRow => row !== null);
|
|
618
|
+
return { count, limit, offset, callLogs };
|
|
619
|
+
};
|
|
620
|
+
|
|
621
|
+
export const mcpCallLogPageHasMore = (
|
|
622
|
+
page: Pick<McpPersonalCallLogPage, 'count' | 'limit' | 'offset'>,
|
|
623
|
+
): boolean => page.offset + page.limit < page.count;
|
|
624
|
+
|
|
625
|
+
/** ai-service did not return a call-log page. A 404 is an empty page, not this error. */
|
|
626
|
+
export class McpCallLogUnavailableError extends Error {
|
|
627
|
+
readonly status: number | null;
|
|
628
|
+
|
|
629
|
+
constructor(message: string, status: number | null) {
|
|
630
|
+
super(message);
|
|
631
|
+
this.name = 'McpCallLogUnavailableError';
|
|
632
|
+
this.status = status;
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
const emptyCallLogPage = (limit: number, offset: number): McpPersonalCallLogPage => ({
|
|
637
|
+
count: 0,
|
|
638
|
+
limit,
|
|
639
|
+
offset,
|
|
640
|
+
callLogs: [],
|
|
641
|
+
});
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* Tool calls for one personal or OAuth agent.
|
|
645
|
+
* `GET {ai-service}/ai/v1/mcp/personal/agents/{agent_id}/call-logs`.
|
|
646
|
+
* The app JWT carries the user and company. A 404 means this caller has no rows.
|
|
647
|
+
*/
|
|
648
|
+
export const fetchMcpPersonalAgentCallLogs = async (
|
|
649
|
+
aiServiceUrl: string,
|
|
650
|
+
accessToken: string,
|
|
651
|
+
agentId: string,
|
|
652
|
+
options: FetchMcpPersonalCallLogsOptions = {},
|
|
653
|
+
): Promise<McpPersonalCallLogPage> => {
|
|
654
|
+
const limit = clampPageLimit(options.limit);
|
|
655
|
+
const offset = clampPageOffset(options.offset);
|
|
656
|
+
const agent = agentId.trim();
|
|
657
|
+
if (!agent) {
|
|
658
|
+
throw new McpCallLogUnavailableError('Missing agent id.', null);
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
let url: URL;
|
|
662
|
+
try {
|
|
663
|
+
const base = aiServiceUrl.trim().replace(/\/+$/, '');
|
|
664
|
+
url = new URL(`${base}/ai/v1/mcp/personal/agents/${encodeURIComponent(agent)}/call-logs`);
|
|
665
|
+
} catch {
|
|
666
|
+
throw new McpCallLogUnavailableError('ai-service URL is not usable.', null);
|
|
667
|
+
}
|
|
668
|
+
url.searchParams.set('limit', String(limit));
|
|
669
|
+
url.searchParams.set('offset', String(offset));
|
|
670
|
+
|
|
671
|
+
let response: Response;
|
|
672
|
+
try {
|
|
673
|
+
response = await fetch(url.toString(), {
|
|
674
|
+
method: 'GET',
|
|
675
|
+
headers: {
|
|
676
|
+
Accept: 'application/json',
|
|
677
|
+
Authorization: `Bearer ${accessToken}`,
|
|
678
|
+
},
|
|
679
|
+
});
|
|
680
|
+
} catch {
|
|
681
|
+
throw new McpCallLogUnavailableError('ai-service unreachable', null);
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
if (response.status === 404) {
|
|
685
|
+
return emptyCallLogPage(limit, offset);
|
|
686
|
+
}
|
|
687
|
+
|
|
688
|
+
const payload = await response.json().catch(() => null);
|
|
689
|
+
if (!response.ok) {
|
|
690
|
+
throw new McpCallLogUnavailableError(`HTTP ${response.status}`, response.status);
|
|
691
|
+
}
|
|
692
|
+
const parsed = parseMcpPersonalCallLogPage(payload);
|
|
693
|
+
if (!parsed) {
|
|
694
|
+
throw new McpCallLogUnavailableError('Unexpected response from ai-service.', response.status);
|
|
695
|
+
}
|
|
696
|
+
return parsed;
|
|
697
|
+
};
|