-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathapi.ts
More file actions
757 lines (655 loc) · 25.1 KB
/
Copy pathapi.ts
File metadata and controls
757 lines (655 loc) · 25.1 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
import type { APIResponse, Server, Tool, ToolApproval, SearchResult, StatusUpdate, SecretRef, MigrationAnalysis, ConfigSecretsResponse, GetToolCallsResponse, GetToolCallDetailResponse, GetServerToolCallsResponse, GetConfigResponse, ValidateConfigResponse, ConfigApplyResult, ServerTokenMetrics, GetRegistriesResponse, SearchRegistryServersResponse, RepositoryServer, GetSessionsResponse, GetSessionDetailResponse, InfoResponse, ActivityListResponse, ActivityDetailResponse, ActivitySummaryResponse, ImportResponse, AgentTokenInfo, CreateAgentTokenRequest, CreateAgentTokenResponse, RoutingInfo } from '@/types'
// Event types for API service
export interface APIAuthEvent {
type: 'auth-error'
error: string
status: number
}
type APIEventListener = (event: APIAuthEvent) => void
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',
}
// 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
})
}
async getServerTools(serverName: string): Promise<APIResponse<{ tools: Tool[] }>> {
return this.request<{ tools: Tool[] }>(`/api/v1/servers/${encodeURIComponent(serverName)}/tools`)
}
// Tool-level quarantine (Spec 032)
async getToolApprovals(serverName: string): Promise<APIResponse<{ tools: ToolApproval[], count: number }>> {
return this.request<{ tools: ToolApproval[], count: number }>(`/api/v1/servers/${encodeURIComponent(serverName)}/tools/export`)
}
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 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'
})
}
// 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')
}
// 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)
})
}
// 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)
}
async addServerFromRepository(server: RepositoryServer): Promise<APIResponse<any>> {
// Use the upstream_servers tool to add the server
const args: Record<string, any> = {
operation: 'add',
name: server.id,
enabled: true,
protocol: 'stdio'
}
// Determine command and args from installCmd or connectUrl
if (server.installCmd) {
const parts = server.installCmd.split(' ')
args.command = parts[0]
if (parts.length > 1) {
args.args_json = JSON.stringify(parts.slice(1))
}
} else if (server.url) {
// Remote server with HTTP protocol
args.protocol = 'http'
args.url = server.url
} else if (server.connectUrl) {
args.protocol = 'http'
args.url = server.connectUrl
}
return this.callTool('upstream_servers', args)
}
// Info endpoint (version and update information)
async getInfo(): Promise<APIResponse<InfoResponse>> {
return this.request<InfoResponse>('/api/v1/info')
}
// 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}`)
}
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
async importServersFromPath(params: {
path: string
format?: string
server_names?: string[]
preview?: boolean
}): Promise<APIResponse<ImportResponse>> {
const url = `/api/v1/servers/import/path${params.preview ? '?preview=true' : ''}`
return this.request<ImportResponse>(url, {
method: 'POST',
body: JSON.stringify({
path: params.path,
format: params.format,
server_names: params.server_names
})
})
}
// Agent Token Management (Spec 028)
async listAgentTokens(): Promise<APIResponse<{ tokens: AgentTokenInfo[] }>> {
return this.request<{ tokens: AgentTokenInfo[] }>('/api/v1/tokens')
}
async createAgentToken(req: CreateAgentTokenRequest): Promise<APIResponse<CreateAgentTokenResponse>> {
return this.request<CreateAgentTokenResponse>('/api/v1/tokens', {
method: 'POST',
body: JSON.stringify(req),
})
}
async revokeAgentToken(name: string): Promise<APIResponse<void>> {
return this.request<void>(`/api/v1/tokens/${encodeURIComponent(name)}`, {
method: 'DELETE',
})
}
async regenerateAgentToken(name: string): Promise<APIResponse<{ name: string; token: string }>> {
return this.request<{ name: string; token: string }>(`/api/v1/tokens/${encodeURIComponent(name)}/regenerate`, {
method: 'POST',
})
}
// Admin server management (Server edition)
async adminEnableServer(name: string): Promise<APIResponse<any>> {
return this.request(`/api/v1/admin/servers/${encodeURIComponent(name)}/enable`, { method: 'POST', credentials: 'include' } as RequestInit)
}
async adminDisableServer(name: string): Promise<APIResponse<any>> {
return this.request(`/api/v1/admin/servers/${encodeURIComponent(name)}/disable`, { method: 'POST', credentials: 'include' } as RequestInit)
}
async adminRestartServer(name: string): Promise<APIResponse<any>> {
return this.request(`/api/v1/admin/servers/${encodeURIComponent(name)}/restart`, { method: 'POST', credentials: 'include' } as RequestInit)
}
// User tokens (Server edition)
async listUserTokens(): Promise<APIResponse<{ tokens: AgentTokenInfo[] }>> {
return this.request<{ tokens: AgentTokenInfo[] }>('/api/v1/user/tokens', { credentials: 'include' } as RequestInit)
}
async createUserToken(data: CreateAgentTokenRequest): Promise<APIResponse<CreateAgentTokenResponse>> {
return this.request<CreateAgentTokenResponse>('/api/v1/user/tokens', {
method: 'POST',
body: JSON.stringify(data),
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
} as RequestInit)
}
async revokeUserToken(name: string): Promise<APIResponse<void>> {
return this.request<void>(`/api/v1/user/tokens/${encodeURIComponent(name)}`, {
method: 'DELETE',
credentials: 'include',
} as RequestInit)
}
async regenerateUserToken(name: string): Promise<APIResponse<{ name: string; token: string }>> {
return this.request<{ name: string; token: string }>(`/api/v1/user/tokens/${encodeURIComponent(name)}/regenerate`, {
method: 'POST',
credentials: 'include',
} as RequestInit)
}
// Utility methods
async testConnection(): Promise<boolean> {
try {
const response = await this.getServers()
return response.success
} catch {
return false
}
}
}
// Canonical config path types
export interface CanonicalConfigPath {
name: string
format: string
path: string
exists: boolean
os: string
description: string
}
export interface CanonicalConfigPathsResponse {
os: string
paths: CanonicalConfigPath[]
}
export default new APIService()