-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathapi.ts
More file actions
1267 lines (1109 loc) · 44.9 KB
/
Copy pathapi.ts
File metadata and controls
1267 lines (1109 loc) · 44.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { APIResponse, Server, Tool, ToolApproval, SearchResult, StatusUpdate, SecretRef, MigrationAnalysis, ConfigSecretsResponse, GetToolCallsResponse, GetToolCallDetailResponse, GetServerToolCallsResponse, GetConfigResponse, ValidateConfigResponse, ConfigApplyResult, ServerTokenMetrics, GetRegistriesResponse, SearchRegistryServersResponse, RegistrySummary, GetSessionsResponse, GetSessionDetailResponse, InfoResponse, ActivityListResponse, ActivityDetailResponse, ActivitySummaryResponse, ImportResponse, AgentTokenInfo, CreateAgentTokenRequest, CreateAgentTokenResponse, RoutingInfo, ConnectStatusResponse, ConnectResult, OnboardingStateResponse, OnboardingMarkRequest, DiagnosticFixResponse, GlobalToolsResponse, UsageAggregateResponse, UsageWindow, UsageSort, UsageStatus } from '@/types'
// Event types for API service
export interface APIAuthEvent {
type: 'auth-error'
error: string
status: number
}
type APIEventListener = (event: APIAuthEvent) => void
// Spec 070: result of the reference-based add-from-registry flow. Unlike the
// generic request() helper (which collapses errors to a single message), this
// carries the stable cross-surface error `code` and the missing-input names so
// the Web UI can drive the required-input prompt without re-parsing strings.
export interface AddedServerSummary {
name: string
protocol?: string
command?: string
args?: string[]
url?: string
quarantined?: boolean
}
export interface AddFromRegistryResult {
success: boolean
server?: AddedServerSummary
error?: string
// Stable cross-surface code: missing_required_input | no_install_info |
// duplicate_name | registry_not_found | server_not_found
code?: string
// Names of unmet required inputs; present when code === 'missing_required_input'.
missingInputs?: string[]
}
// MCP-866 / MCP-867: result of adding a *registry source* (POST /registries).
// Carries the stable error `code` (invalid_registry_url | registries_locked |
// registry_shadows_builtin | duplicate_registry) so the UI can render an
// actionable message instead of a generic string.
export interface AddRegistrySourceResult {
success: boolean
registry?: RegistrySummary
error?: string
code?: string
}
// MCP-1064 / MCP-1057: result of removing a *custom/unverified registry source*
// (DELETE /registries/{id}). Carries the stable error `code`
// (registry_not_found | registry_shadows_builtin | registries_locked) so the UI
// can render an actionable message. Removing a source does not touch upstream
// servers already added from it.
export interface RemoveRegistrySourceResult {
success: boolean
registry?: RegistrySummary
error?: string
code?: string
}
class APIService {
private baseUrl = ''
private apiKey = ''
private initialized = false
private eventListeners: APIEventListener[] = []
constructor() {
// In development, Vite proxy handles API calls
// In production, the frontend is served from the same origin as the API
this.baseUrl = import.meta.env.DEV ? '' : ''
// Extract API key from URL parameters on initialization
this.initializeAPIKey()
}
private initializeAPIKey() {
// Set initialized flag first to prevent race conditions
this.initialized = true
const urlParams = new URLSearchParams(window.location.search)
const apiKeyFromURL = urlParams.get('apikey')
if (apiKeyFromURL) {
// URL param always takes priority (for backend restarts with new keys)
this.apiKey = apiKeyFromURL
// Store the new API key for future navigation/refreshes
localStorage.setItem('mcpproxy-api-key', apiKeyFromURL)
console.log('API key from URL (updating storage):', this.apiKey.substring(0, 8) + '...')
// Clean the URL by removing the API key parameter for security
urlParams.delete('apikey')
const newURL = window.location.pathname + (urlParams.toString() ? '?' + urlParams.toString() : '')
window.history.replaceState({}, '', newURL)
} else {
// No URL param - check localStorage as fallback
const storedApiKey = localStorage.getItem('mcpproxy-api-key')
if (storedApiKey) {
this.apiKey = storedApiKey
console.log('API key from localStorage:', this.apiKey.substring(0, 8) + '...')
} else {
console.log('No API key found in URL or localStorage')
}
}
}
// Public method to reinitialize API key if needed
public reinitializeAPIKey() {
this.initialized = false
this.initializeAPIKey()
}
// Check if API key is available
public hasAPIKey(): boolean {
return !!this.apiKey
}
// Get API key (for debugging purposes)
public getAPIKeyPreview(): string {
return this.apiKey ? this.apiKey.substring(0, 8) + '...' : 'none'
}
// Clear API key from both memory and localStorage
public clearAPIKey(): void {
this.apiKey = ''
localStorage.removeItem('mcpproxy-api-key')
console.log('API key cleared from memory and localStorage')
}
// Set API key programmatically and store it
public setAPIKey(key: string): void {
this.apiKey = key
if (key) {
localStorage.setItem('mcpproxy-api-key', key)
console.log('API key set and stored:', key.substring(0, 8) + '...')
} else {
localStorage.removeItem('mcpproxy-api-key')
console.log('API key cleared')
}
}
// Event system for global error handling
public addEventListener(listener: APIEventListener): () => void {
this.eventListeners.push(listener)
return () => {
const index = this.eventListeners.indexOf(listener)
if (index > -1) {
this.eventListeners.splice(index, 1)
}
}
}
private emitAuthError(error: string, status: number): void {
const event: APIAuthEvent = {
type: 'auth-error',
error,
status
}
this.eventListeners.forEach(listener => {
try {
listener(event)
} catch (err) {
console.error('Error in API event listener:', err)
}
})
}
// Validate the current API key by making a test request
public async validateAPIKey(): Promise<boolean> {
if (!this.apiKey) {
return false
}
try {
const response = await this.getServers()
return response.success
} catch (error) {
console.warn('API key validation failed:', error)
return false
}
}
private async request<T>(endpoint: string, options: RequestInit = {}): Promise<APIResponse<T>> {
// Ensure API key initialization is complete
if (!this.initialized) {
console.log('API service not initialized, initializing now...')
this.initializeAPIKey()
}
try {
const headers: Record<string, string> = {
'Content-Type': 'application/json',
// Spec 042: telemetry surface header so the daemon can attribute
// requests to the web UI for the surface_requests counter. Version
// is intentionally a constant string — the daemon already reports
// its own build version separately and we don't want to leak the
// browser/UA fingerprint into telemetry.
'X-MCPProxy-Client': 'webui/web',
}
// Merge headers from options if they exist
if (options.headers) {
if (options.headers instanceof Headers) {
options.headers.forEach((value, key) => {
headers[key] = value
})
} else if (Array.isArray(options.headers)) {
options.headers.forEach(([key, value]) => {
headers[key] = value
})
} else {
Object.assign(headers, options.headers)
}
}
// Add API key header if available
if (this.apiKey) {
headers['X-API-Key'] = this.apiKey
console.log(`API request to ${endpoint} with API key: ${this.getAPIKeyPreview()}`)
} else {
console.log(`API request to ${endpoint} without API key - initialized: ${this.initialized}`)
console.log('Current URL search params:', window.location.search)
console.log('LocalStorage API key:', localStorage.getItem('mcpproxy-api-key')?.substring(0, 8) + '...')
}
const response = await fetch(`${this.baseUrl}${endpoint}`, {
...options,
headers,
})
if (!response.ok) {
// Try to extract error message from response body
const errorData = await response.json().catch(() => ({}))
const errorMsg = errorData.error || `HTTP ${response.status}: ${response.statusText}`
console.error(`API request failed: ${errorMsg}`)
// Special handling for authentication errors
if (response.status === 401 || response.status === 403) {
console.error('Authentication failed - API key may be invalid or missing')
this.emitAuthError(errorMsg, response.status)
}
throw new Error(errorMsg)
}
// Handle 204 No Content (e.g., DELETE responses)
if (response.status === 204) {
console.log(`API request to ${endpoint} succeeded (204 No Content)`)
return { success: true } as APIResponse<T>
}
const data = await response.json()
console.log(`API request to ${endpoint} succeeded`)
return data as APIResponse<T>
} catch (error) {
console.error('API request failed:', error)
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error',
}
}
}
// Status endpoint
async getStatus(): Promise<APIResponse<{ edition: string; running: boolean; routing_mode: string }>> {
return this.request<{ edition: string; running: boolean; routing_mode: string }>('/api/v1/status')
}
// Routing mode endpoint
async getRouting(): Promise<APIResponse<RoutingInfo>> {
return this.request<RoutingInfo>('/api/v1/routing')
}
// Server endpoints
async getServers(): Promise<APIResponse<{ servers: Server[] }>> {
return this.request<{ servers: Server[] }>('/api/v1/servers')
}
async enableServer(serverName: string): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/enable`, {
method: 'POST',
})
}
async disableServer(serverName: string): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/disable`, {
method: 'POST',
})
}
async restartServer(serverName: string): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/restart`, {
method: 'POST',
})
}
async triggerOAuthLogin(serverName: string): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/login`, {
method: 'POST',
})
}
async triggerOAuthLogout(serverName: string): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/logout`, {
method: 'POST',
})
}
async quarantineServer(serverName: string): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/quarantine`, {
method: 'POST',
})
}
async unquarantineServer(serverName: string): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/unquarantine`, {
method: 'POST',
})
}
async discoverServerTools(serverName: string): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/discover-tools`, {
method: 'POST',
})
}
async deleteServer(serverName: string): Promise<APIResponse> {
return this.callTool('upstream_servers', {
operation: 'remove',
name: serverName
})
}
// patchServer issues a partial update to an existing upstream server. The
// backend (handlePatchServer in internal/httpapi/server.go) treats every
// request field as optional and preserves anything not supplied, so callers
// can send only what they want to change. Passing `headers: {}` clears
// headers; omitting the field keeps the existing value.
async patchServer(serverName: string, patch: Record<string, unknown>): Promise<APIResponse> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}`, {
method: 'PATCH',
body: JSON.stringify(patch),
})
}
// storeSecret stashes a value in the OS keyring under the given name and
// returns the ${keyring:<name>} reference string callers can substitute
// back into the server config. Kept for legacy callers; the
// Headers/Environment Variables "Convert to secret" flow now uses the
// atomic convertConfigToSecret() instead.
async storeSecret(name: string, value: string): Promise<APIResponse<{ reference?: string }>> {
return this.request<{ reference?: string }>('/api/v1/secrets', {
method: 'POST',
body: JSON.stringify({ name, value, type: 'keyring' }),
})
}
// convertConfigToSecret asks the backend to atomically (a) read the real
// value of a header / env key from the server config, (b) store it in
// the OS keyring under `secretName`, and (c) rewrite the config field
// with the `${keyring:<name>}` reference. The client never has to
// possess the real value — which matters when the API redacts
// sensitive header values on the read path.
async convertConfigToSecret(
serverName: string,
scope: 'header' | 'env',
key: string,
secretName: string
): Promise<APIResponse<{ reference?: string }>> {
return this.request<{ reference?: string }>(
`/api/v1/servers/${encodeURIComponent(serverName)}/config-to-secret`,
{
method: 'POST',
body: JSON.stringify({ scope, key, secret_name: secretName }),
}
)
}
async getServerTools(serverName: string): Promise<APIResponse<{ tools: Tool[] }>> {
return this.request<{ tools: Tool[] }>(`/api/v1/servers/${encodeURIComponent(serverName)}/tools`)
}
// Global tools listing (Spec 050) — all tools across all servers from a single consolidated endpoint.
async getGlobalTools(): Promise<APIResponse<GlobalToolsResponse>> {
return this.request<GlobalToolsResponse>('/api/v1/tools')
}
// Tool-level quarantine (Spec 032)
async getToolApprovals(serverName: string): Promise<APIResponse<{ tools: ToolApproval[], count: number }>> {
const response = await this.request<{ tools: ToolApproval[], count: number }>(`/api/v1/servers/${encodeURIComponent(serverName)}/tools/export`)
if (response.success && response.data?.tools) {
response.data.tools = response.data.tools.map((tool) => {
const disabled = typeof tool.disabled === 'boolean'
? tool.disabled
: (typeof tool.enabled === 'boolean' ? !tool.enabled : false)
return {
...tool,
disabled,
enabled: !disabled,
}
})
}
return response
}
async getToolDiff(serverName: string, toolName: string): Promise<APIResponse<ToolApproval>> {
return this.request<ToolApproval>(`/api/v1/servers/${encodeURIComponent(serverName)}/tools/${encodeURIComponent(toolName)}/diff`)
}
async approveTools(serverName: string, tools?: string[]): Promise<APIResponse<{ approved: number }>> {
const body = tools && tools.length > 0
? { tools }
: { approve_all: true }
return this.request<{ approved: number }>(`/api/v1/servers/${encodeURIComponent(serverName)}/tools/approve`, {
method: 'POST',
body: JSON.stringify(body),
})
}
async setToolEnabled(serverName: string, toolName: string, enabled: boolean): Promise<APIResponse<{
server_name: string
tool_name: string
enabled: boolean
}>> {
return this.request<{ server_name: string; tool_name: string; enabled: boolean }>(`/api/v1/servers/${encodeURIComponent(serverName)}/tools/${encodeURIComponent(toolName)}/enabled`, {
method: 'POST',
body: JSON.stringify({ enabled }),
})
}
// Bulk-toggle every known tool of a server. The response's `changed`
// field reflects only tools whose state actually changed — already-correct
// tools are skipped on the server side.
async setAllToolsEnabled(serverName: string, enabled: boolean): Promise<APIResponse<{
server_name: string
enabled: boolean
changed: number
}>> {
const action = enabled ? 'enable_all' : 'disable_all'
return this.request<{ server_name: string; enabled: boolean; changed: number }>(`/api/v1/servers/${encodeURIComponent(serverName)}/tools/${action}`, {
method: 'POST',
})
}
async getServerLogs(serverName: string, tail?: number): Promise<APIResponse<{ logs: string[] }>> {
const params = tail ? `?tail=${tail}` : ''
return this.request<{ logs: string[] }>(`/api/v1/servers/${encodeURIComponent(serverName)}/logs${params}`)
}
// Tool search
async searchTools(query: string, limit = 10): Promise<APIResponse<{ results: SearchResult[] }>> {
const params = new URLSearchParams({ q: query, limit: limit.toString() })
return this.request<{ results: SearchResult[] }>(`/api/v1/index/search?${params}`)
}
// Server-Sent Events
createEventSource(): EventSource {
const url = this.apiKey
? `${this.baseUrl}/events?apikey=${encodeURIComponent(this.apiKey)}`
: `${this.baseUrl}/events`
console.log('Creating EventSource:', {
hasApiKey: !!this.apiKey,
apiKeyPreview: this.getAPIKeyPreview(),
url: this.apiKey ? url.replace(this.apiKey, this.getAPIKeyPreview()) : url
})
return new EventSource(url)
}
// Secret endpoints
async getSecretRefs(): Promise<APIResponse<{ refs: SecretRef[] }>> {
return this.request<{ refs: SecretRef[] }>('/api/v1/secrets/refs')
}
async getConfigSecrets(): Promise<APIResponse<ConfigSecretsResponse>> {
return this.request<ConfigSecretsResponse>('/api/v1/secrets/config')
}
async runMigrationAnalysis(): Promise<APIResponse<{ analysis: MigrationAnalysis }>> {
return this.request<{ analysis: MigrationAnalysis }>('/api/v1/secrets/migrate', {
method: 'POST',
})
}
async setSecret(name: string, value: string, type: string = 'keyring'): Promise<APIResponse<{
message: string
name: string
type: string
reference: string
}>> {
return this.request('/api/v1/secrets', {
method: 'POST',
body: JSON.stringify({ name, value, type })
})
}
async deleteSecret(name: string, type: string = 'keyring'): Promise<APIResponse<{
message: string
name: string
type: string
}>> {
const url = `/api/v1/secrets/${encodeURIComponent(name)}?type=${encodeURIComponent(type)}`
return this.request(url, {
method: 'DELETE'
})
}
// Docker status
async getDockerStatus(): Promise<APIResponse<{
docker_available: boolean
recovery_mode: boolean
failure_count: number
attempts_since_up: number
last_attempt: string
last_error: string
last_successful_at: string
}>> {
return this.request('/api/v1/docker/status')
}
// Diagnostics
async getDiagnostics(): Promise<APIResponse<{
upstream_errors: Array<{
type: string
category: string
server?: string
title: string
message: string
timestamp: string
severity: string
metadata?: Record<string, any>
}>
oauth_required: string[]
missing_secrets: Array<{
name: string
reference: string
server: string
type: string
}>
runtime_warnings: Array<{
type: string
category: string
server?: string
title: string
message: string
timestamp: string
severity: string
metadata?: Record<string, any>
}>
total_issues: number
last_updated: string
}>> {
return this.request('/api/v1/diagnostics')
}
// Spec 044 — per-server diagnostics.
async getServerDiagnostic(serverName: string): Promise<APIResponse<{
server: string
connected: boolean
status: string
health: any
diagnostic: any | null
error_code: string | null
catalog_size: number
}>> {
return this.request(`/api/v1/servers/${encodeURIComponent(serverName)}/diagnostics`)
}
// Spec 044 — invoke a registered fixer. Destructive fixers default to
// dry_run unless mode='execute' is supplied by the caller.
async invokeDiagnosticFix(params: {
server: string
code: string
fixer_key: string
mode?: 'dry_run' | 'execute'
}): Promise<APIResponse<DiagnosticFixResponse>> {
return this.request<DiagnosticFixResponse>('/api/v1/diagnostics/fix', {
method: 'POST',
body: JSON.stringify(params),
})
}
// Tool Call History endpoints
async getToolCalls(params?: { limit?: number; offset?: number }): Promise<APIResponse<GetToolCallsResponse>> {
const searchParams = new URLSearchParams()
if (params?.limit) searchParams.set('limit', params.limit.toString())
if (params?.offset) searchParams.set('offset', params.offset.toString())
const url = `/api/v1/tool-calls${searchParams.toString() ? '?' + searchParams.toString() : ''}`
return this.request<GetToolCallsResponse>(url)
}
async getToolCallDetail(id: string): Promise<APIResponse<GetToolCallDetailResponse>> {
return this.request<GetToolCallDetailResponse>(`/api/v1/tool-calls/${encodeURIComponent(id)}`)
}
async getServerToolCalls(serverName: string, limit?: number): Promise<APIResponse<GetServerToolCallsResponse>> {
const url = `/api/v1/servers/${encodeURIComponent(serverName)}/tool-calls${limit ? `?limit=${limit}` : ''}`
return this.request<GetServerToolCallsResponse>(url)
}
async replayToolCall(id: string, args: Record<string, any>): Promise<APIResponse<any>> {
return this.request(`/api/v1/tool-calls/${encodeURIComponent(id)}/replay`, {
method: 'POST',
body: JSON.stringify({ arguments: args })
})
}
// Session management endpoints
async getSessions(limit?: number): Promise<APIResponse<GetSessionsResponse>> {
const url = `/api/v1/sessions${limit ? `?limit=${limit}` : ''}`
return this.request<GetSessionsResponse>(url)
}
async getSessionDetail(sessionId: string): Promise<APIResponse<GetSessionDetailResponse>> {
return this.request<GetSessionDetailResponse>(`/api/v1/sessions/${encodeURIComponent(sessionId)}`)
}
// Configuration management endpoints
async getConfig(): Promise<APIResponse<GetConfigResponse>> {
return this.request<GetConfigResponse>('/api/v1/config')
}
async validateConfig(config: any): Promise<APIResponse<ValidateConfigResponse>> {
return this.request<ValidateConfigResponse>('/api/v1/config/validate', {
method: 'POST',
body: JSON.stringify(config)
})
}
async applyConfig(config: any): Promise<APIResponse<ConfigApplyResult>> {
return this.request<ConfigApplyResult>('/api/v1/config/apply', {
method: 'POST',
body: JSON.stringify(config)
})
}
// setDockerIsolationEnabled flips the global docker_isolation.enabled
// flag without resending the full config. Mirrors the PATCH endpoint
// added on the backend.
async setDockerIsolationEnabled(enabled: boolean): Promise<APIResponse<ConfigApplyResult>> {
return this.request<ConfigApplyResult>('/api/v1/config/docker-isolation', {
method: 'PATCH',
body: JSON.stringify({ enabled })
})
}
// patchConfig applies a partial (deep-merged) config update — only the
// fields present in `partial` are changed; everything else (including masked
// secrets like api_key) is preserved server-side. Spec 060.
async patchConfig(partial: Record<string, any>): Promise<APIResponse<ConfigApplyResult>> {
return this.request<ConfigApplyResult>('/api/v1/config', {
method: 'PATCH',
body: JSON.stringify(partial)
})
}
// Token statistics endpoints
async getTokenStats(): Promise<APIResponse<ServerTokenMetrics>> {
return this.request<ServerTokenMetrics>('/api/v1/stats/tokens')
}
// Tool Call via REST API
async callTool(toolName: string, args: Record<string, any>): Promise<APIResponse<any>> {
return this.request<any>('/api/v1/tools/call', {
method: 'POST',
body: JSON.stringify({
tool_name: toolName,
arguments: args
})
})
}
// Registry browsing (Phase 7)
async listRegistries(): Promise<APIResponse<GetRegistriesResponse>> {
return this.request<GetRegistriesResponse>('/api/v1/registries')
}
async searchRegistryServers(
registryId: string,
options?: {
query?: string
tag?: string
limit?: number
}
): Promise<APIResponse<SearchRegistryServersResponse>> {
const params = new URLSearchParams()
if (options?.query) params.append('q', options.query)
if (options?.tag) params.append('tag', options.tag)
if (options?.limit) params.append('limit', options.limit.toString())
const url = `/api/v1/registries/${encodeURIComponent(registryId)}/servers${params.toString() ? '?' + params.toString() : ''}`
return this.request<SearchRegistryServersResponse>(url)
}
// MCP-866 / MCP-867: add a user-supplied registry source. The server always
// tags an added source custom/unverified (provenance is NOT part of the
// request), so every server later discovered through it lands quarantined and
// can never skip quarantine. We mirror the structured-error pattern of
// addServerFromRegistry so the UI can branch on the stable `code`
// (invalid_registry_url | registries_locked | registry_shadows_builtin |
// duplicate_registry).
async addRegistrySource(
url: string,
opts?: { protocol?: string; id?: string; name?: string }
): Promise<AddRegistrySourceResult> {
const body: Record<string, unknown> = { url }
if (opts?.protocol) body.protocol = opts.protocol
if (opts?.id) body.id = opts.id
if (opts?.name) body.name = opts.name
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (this.apiKey) headers['X-API-Key'] = this.apiKey
try {
const response = await fetch(`${this.baseUrl}/api/v1/registries`, {
method: 'POST',
headers,
body: JSON.stringify(body)
})
const payload: any = await response.json().catch(() => ({}))
if (!response.ok) {
if (response.status === 401 || response.status === 403) {
// registries_locked is a 403 but is a policy decision, not an auth
// failure — only emit the auth-error path for a missing/invalid key.
if (payload?.code !== 'registries_locked') {
this.emitAuthError(payload?.error || `HTTP ${response.status}`, response.status)
}
}
return {
success: false,
error: payload?.error || `HTTP ${response.status}: ${response.statusText}`,
code: payload?.code
}
}
return { success: true, registry: payload?.data?.registry }
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
}
}
}
// MCP-1064 / MCP-1057: remove a user-added custom/unverified registry source.
// Mirrors the structured-error pattern of addRegistrySource so the UI can
// branch on the stable `code` (registry_not_found | registry_shadows_builtin
// | registries_locked). Built-in official/trusted registries cannot be
// removed (the backend refuses them with registry_shadows_builtin), so the UI
// only offers this on custom sources. Removing a source leaves any upstream
// servers already added from it untouched.
async removeRegistrySource(registryId: string): Promise<RemoveRegistrySourceResult> {
const headers: Record<string, string> = {}
if (this.apiKey) headers['X-API-Key'] = this.apiKey
try {
const response = await fetch(`${this.baseUrl}/api/v1/registries/${encodeURIComponent(registryId)}`, {
method: 'DELETE',
headers
})
const payload: any = await response.json().catch(() => ({}))
if (!response.ok) {
if (response.status === 401 || response.status === 403) {
// registries_locked is a 403 policy decision, not an auth failure —
// only emit the auth-error path for a missing/invalid key.
if (payload?.code !== 'registries_locked') {
this.emitAuthError(payload?.error || `HTTP ${response.status}`, response.status)
}
}
return {
success: false,
error: payload?.error || `HTTP ${response.status}: ${response.statusText}`,
code: payload?.code
}
}
return { success: true, registry: payload?.data?.registry }
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
}
}
}
// Spec 070 (CN-001): add a server to upstream by *reference* — the server
// re-derives and validates the config from the registry entry. The client no
// longer splits install_cmd / chooses protocol (that client-side parsing was
// the source of issue #483 and let a buggy client smuggle in arbitrary
// command/args). All add surfaces (REST/MCP/CLI) funnel through the same
// backend keystone (AddServerFromRegistry), so identical input → identical
// persisted, quarantined config (CN-004).
async addServerFromRegistry(
registryId: string,
serverId: string,
opts?: { name?: string; enabled?: boolean; env?: Record<string, string> }
): Promise<AddFromRegistryResult> {
const url = `/api/v1/registries/${encodeURIComponent(registryId)}/servers/${encodeURIComponent(serverId)}/add`
const body: Record<string, unknown> = {}
if (opts?.name) body.name = opts.name
if (opts?.enabled !== undefined) body.enabled = opts.enabled
if (opts?.env && Object.keys(opts.env).length > 0) body.env = opts.env
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
if (this.apiKey) headers['X-API-Key'] = this.apiKey
try {
const response = await fetch(`${this.baseUrl}${url}`, {
method: 'POST',
headers,
body: JSON.stringify(body)
})
const payload: any = await response.json().catch(() => ({}))
if (!response.ok) {
if (response.status === 401 || response.status === 403) {
this.emitAuthError(payload?.error || `HTTP ${response.status}`, response.status)
}
return {
success: false,
error: payload?.error || `HTTP ${response.status}: ${response.statusText}`,
code: payload?.code,
missingInputs: payload?.missing_inputs
}
}
return { success: true, server: payload?.data?.server }
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
}
}
}
// Info endpoint (version and update information)
async getInfo(opts?: { refresh?: boolean }): Promise<APIResponse<InfoResponse>> {
const url = opts?.refresh ? '/api/v1/info?refresh=true' : '/api/v1/info'
return this.request<InfoResponse>(url)
}
// Activity Log endpoints (RFC-003)
async getActivities(params?: {
type?: string
server?: string
tool?: string
session_id?: string
status?: string
intent_type?: string
start_time?: string
end_time?: string
limit?: number
offset?: number
}): Promise<APIResponse<ActivityListResponse>> {
const searchParams = new URLSearchParams()
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== '') {
searchParams.append(key, String(value))
}
})
}
const url = `/api/v1/activity${searchParams.toString() ? '?' + searchParams.toString() : ''}`
return this.request<ActivityListResponse>(url)
}
async getActivityDetail(id: string): Promise<APIResponse<ActivityDetailResponse>> {
return this.request<ActivityDetailResponse>(`/api/v1/activity/${encodeURIComponent(id)}`)
}
async getActivitySummary(period: string = '24h'): Promise<APIResponse<ActivitySummaryResponse>> {
return this.request<ActivitySummaryResponse>(`/api/v1/activity/summary?period=${period}`)
}
// Usage statistics aggregate for the Web UI usage graphs (Spec 069).
async getActivityUsage(params?: {
window?: UsageWindow
server?: string
tool?: string
status?: UsageStatus
top?: number
sort?: UsageSort
}): Promise<APIResponse<UsageAggregateResponse>> {
const searchParams = new URLSearchParams()
if (params) {
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== '') {
searchParams.append(key, String(value))
}
})
}
const qs = searchParams.toString()
return this.request<UsageAggregateResponse>(`/api/v1/activity/usage${qs ? '?' + qs : ''}`)
}
getActivityExportUrl(params: {
format: 'json' | 'csv'
type?: string
server?: string
status?: string
start_time?: string
end_time?: string
include_bodies?: boolean
}): string {
const searchParams = new URLSearchParams()
searchParams.append('format', params.format)
if (this.apiKey) {
searchParams.append('apikey', this.apiKey)
}
Object.entries(params).forEach(([key, value]) => {
if (key !== 'format' && value !== undefined && value !== '') {
searchParams.append(key, String(value))
}
})
return `${this.baseUrl}/api/v1/activity/export?${searchParams.toString()}`
}
// Import server configurations
async importServersFromJSON(params: {
content: string
format?: string
server_names?: string[]
preview?: boolean
}): Promise<APIResponse<ImportResponse>> {
const url = `/api/v1/servers/import/json${params.preview ? '?preview=true' : ''}`
return this.request<ImportResponse>(url, {
method: 'POST',
body: JSON.stringify({
content: params.content,
format: params.format,
server_names: params.server_names
})
})
}
async importServersFromFile(file: File, params?: {
format?: string
server_names?: string[]
preview?: boolean
}): Promise<APIResponse<ImportResponse>> {
const formData = new FormData()
formData.append('file', file)
const searchParams = new URLSearchParams()
if (params?.preview) searchParams.append('preview', 'true')
if (params?.format) searchParams.append('format', params.format)
if (params?.server_names?.length) searchParams.append('server_names', params.server_names.join(','))
const url = `/api/v1/servers/import${searchParams.toString() ? '?' + searchParams.toString() : ''}`
// Use custom fetch without Content-Type header (let browser set it for FormData)
try {
const headers: Record<string, string> = {}
if (this.apiKey) {
headers['X-API-Key'] = this.apiKey
}
const response = await fetch(`${this.baseUrl}${url}`, {
method: 'POST',
headers,
body: formData
})
if (!response.ok) {
// Extract error message from response body if available
const errorData = await response.json().catch(() => ({}))
const errorMsg = errorData.error || `HTTP ${response.status}: ${response.statusText}`
throw new Error(errorMsg)
}
const data = await response.json()
return data as APIResponse<ImportResponse>
} catch (error) {
return {
success: false,
error: error instanceof Error ? error.message : 'Unknown error'
}
}
}
// Get canonical config paths for import hints
async getCanonicalConfigPaths(): Promise<APIResponse<CanonicalConfigPathsResponse>> {
return this.request<CanonicalConfigPathsResponse>('/api/v1/servers/import/paths')
}
// Import servers from a file path on the server's filesystem.
// Spec 046 v2: skip_quarantine=true imports as already-trusted (skips
// the quarantine holding state). Default false preserves the safe-by-
// default posture for any caller that doesn't pass the flag.
async importServersFromPath(params: {
path: string
format?: string
server_names?: string[]
preview?: boolean
skip_quarantine?: boolean
rename?: Record<string, string>