-
Notifications
You must be signed in to change notification settings - Fork 630
Expand file tree
/
Copy pathtools.js
More file actions
3504 lines (3183 loc) · 126 KB
/
tools.js
File metadata and controls
3504 lines (3183 loc) · 126 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 { AppState } from "./appState.js";
import { loadAuthHeaders, updateAuthHeadersJSON } from "./auth.js";
import { escapeAttrValue } from "./security.js";
import { updateEditToolRequestTypes } from "./formFieldHandlers.js";
import { getSelectedGatewayIds } from "./gateways.js";
import { closeModal, openModal } from "./modals.js";
import {
escapeHtml,
safeSetInnerHTML,
validateInputName,
validateJson,
validatePassthroughHeader,
validateUrl,
} from "./security.js";
import { getEditSelections } from "./servers.js";
import { getUiHiddenSections } from "./tabs.js";
import { applyVisibilityRestrictions } from "./teams.js";
import {
decodeHtml,
fetchWithTimeout,
getCurrentTeamId,
handleFetchError,
isInactiveChecked,
makeCopyIdButton,
safeGetElement,
showErrorMessage,
showSuccessMessage,
updateEditToolUrl,
} from "./utils.js";
// ===================================================================
// ENHANCED TOOL VIEWING with Secure Display
// ===================================================================
/**
* SECURE: View Tool function with safe display
*/
export const viewTool = async function (toolId) {
try {
console.log(`Fetching tool details for ID: ${toolId}`);
const response = await fetchWithTimeout(
`${window.ROOT_PATH}/admin/tools/${toolId}`
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const tool = await response.json();
// Build auth HTML safely with new styling
let authHTML = "";
if (tool.auth?.username && tool.auth?.password) {
authHTML = `
<span class="font-medium text-gray-700 dark:text-gray-300">Authentication Type:</span>
<div class="mt-1 text-sm">
<div class="text-gray-600 dark:text-gray-400">Basic Authentication</div>
<div class="mt-1">Username: <span class="auth-username font-medium"></span></div>
<div>Password: <span class="font-medium">********</span></div>
</div>
`;
} else if (tool.auth?.token) {
authHTML = `
<span class="font-medium text-gray-700 dark:text-gray-300">Authentication Type:</span>
<div class="mt-1 text-sm">
<div class="text-gray-600 dark:text-gray-400">Bearer Token</div>
<div class="mt-1">Token: <span class="font-medium">********</span></div>
</div>
`;
} else if (
tool.auth?.authHeaders &&
Array.isArray(tool.auth.authHeaders) &&
tool.auth.authHeaders.length > 0
) {
// Multi-header format
const headerRows = tool.auth.authHeaders
.map(
(header) =>
`<div class="mt-1"><span class="font-medium">${escapeHtml(header.key)}:</span> ********</div>`
)
.join("");
authHTML = `
<span class="font-medium text-gray-700 dark:text-gray-300">Authentication Type:</span>
<div class="mt-1 text-sm">
<div class="text-gray-600 dark:text-gray-400">Custom Headers</div>
${headerRows}
</div>
`;
} else if (tool.auth?.authHeaderKey && tool.auth?.authHeaderValue) {
// Legacy single-header format (backward compatibility)
authHTML = `
<span class="font-medium text-gray-700 dark:text-gray-300">Authentication Type:</span>
<div class="mt-1 text-sm">
<div class="text-gray-600 dark:text-gray-400">Custom Headers</div>
<div class="mt-1">Header: <span class="auth-header-key font-medium"></span></div>
<div>Value: <span class="font-medium">********</span></div>
</div>
`;
} else {
authHTML = `
<span class="font-medium text-gray-700 dark:text-gray-300">Authentication Type:</span>
<div class="mt-1 text-sm">None</div>
`;
}
// Create annotation badges safely - NO ESCAPING since we're using textContent
const renderAnnotations = (annotations) => {
if (!annotations || Object.keys(annotations).length === 0) {
return '<p><strong>Annotations:</strong> <span class="text-gray-600 dark:text-gray-300">None</span></p>';
}
const badges = [];
// Show title if present
if (annotations.title) {
badges.push(
'<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-blue-100 text-blue-800 mr-1 mb-1 annotation-title"></span>'
);
}
// Show behavior hints with appropriate colors
if (annotations.readOnlyHint === true) {
badges.push(
'<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800 mr-1 mb-1">📖 Read-Only</span>'
);
}
if (annotations.destructiveHint === true) {
badges.push(
'<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 mr-1 mb-1">⚠️ Destructive</span>'
);
}
if (annotations.idempotentHint === true) {
badges.push(
'<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-purple-100 text-purple-800 mr-1 mb-1">🔄 Idempotent</span>'
);
}
if (annotations.openWorldHint === true) {
badges.push(
'<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-yellow-100 text-yellow-800 mr-1 mb-1">🌐 External Access</span>'
);
}
// Show any other custom annotations
Object.keys(annotations).forEach((key) => {
if (
![
"title",
"readOnlyHint",
"destructiveHint",
"idempotentHint",
"openWorldHint",
].includes(key)
) {
const value = annotations[key];
badges.push(
`<span class="inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:text-gray-200 mr-1 mb-1 custom-annotation" data-key="${key}" data-value="${value}"></span>`
);
}
});
return `
<div>
<strong>Annotations:</strong>
<div class="mt-1 flex flex-wrap">
${badges.join("")}
</div>
</div>
`;
};
const toolDetailsDiv = safeGetElement("tool-details");
if (toolDetailsDiv) {
// Create structure safely without double-escaping
const safeHTML = `
<div class="bg-transparent dark:bg-transparent dark:text-gray-300">
<!-- Two Column Layout for Main Info -->
<div class="grid grid-cols-2 gap-6 mb-6">
<!-- Left Column -->
<div class="space-y-3">
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">Tool ID:</span>
<div class="mt-1 tool-id text-sm font-mono"></div>
</div>
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">Display Name:</span>
<div class="mt-1 tool-display-name font-medium"></div>
</div>
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">Technical Name:</span>
<div class="mt-1 tool-name text-sm"></div>
</div>
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">URL:</span>
<div class="mt-1 tool-url text-sm"></div>
</div>
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">Type:</span>
<div class="mt-1 tool-type text-sm"></div>
</div>
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">Visibility:</span>
<div class="mt-1 tool-visibility text-sm"></div>
</div>
</div>
<!-- Right Column -->
<div class="space-y-3">
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">Description:</span>
<div class="mt-1 tool-description text-sm"></div>
</div>
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">Tags:</span>
<div class="mt-1 tool-tags text-sm"></div>
</div>
<div>
<span class="font-medium text-gray-700 dark:text-gray-300">Request Type:</span>
<div class="mt-1 tool-request-type text-sm"></div>
</div>
<div class="auth-info">
${authHTML}
</div>
</div>
</div>
<!-- Annotations Section -->
<div class="mb-6">
${renderAnnotations(tool.annotations)}
</div>
<!-- Technical Details Section -->
<div class="space-y-4">
<div>
<strong class="text-gray-700 dark:text-gray-300">Headers:</strong>
<pre class="mt-1 bg-gray-100 p-3 rounded text-xs dark:bg-gray-800 dark:text-gray-200 tool-headers overflow-x-auto"></pre>
</div>
<div>
<strong class="text-gray-700 dark:text-gray-300">Input Schema:</strong>
<pre class="mt-1 bg-gray-100 p-3 rounded text-xs dark:bg-gray-800 dark:text-gray-200 tool-schema overflow-x-auto"></pre>
</div>
<div>
<strong class="text-gray-700 dark:text-gray-300">Output Schema:</strong>
<pre class="mt-1 bg-gray-100 p-3 rounded text-xs dark:bg-gray-800 dark:text-gray-200 tool-output-schema overflow-x-auto"></pre>
</div>
</div>
<!-- Metrics Section -->
<div class="mt-6 pt-4 border-t border-gray-200 dark:border-gray-600">
<strong class="text-gray-700 dark:text-gray-300">Metrics:</strong>
<div class="grid grid-cols-2 gap-4 mt-3 text-sm">
<div class="space-y-2">
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Total Executions:</span>
<span class="metric-total font-medium"></span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Successful Executions:</span>
<span class="metric-success font-medium text-green-600"></span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Failed Executions:</span>
<span class="metric-failed font-medium text-red-600"></span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Failure Rate:</span>
<span class="metric-failure-rate font-medium"></span>
</div>
</div>
<div class="space-y-2">
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Min Response Time:</span>
<span class="metric-min-time font-medium"></span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Max Response Time:</span>
<span class="metric-max-time font-medium"></span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Average Response Time:</span>
<span class="metric-avg-time font-medium"></span>
</div>
<div class="flex justify-between">
<span class="text-gray-600 dark:text-gray-400">Last Execution Time:</span>
<span class="metric-last-time font-medium"></span>
</div>
</div>
</div>
</div>
<div class="mt-6 border-t pt-4">
<!-- Metadata Section -->
<strong>Metadata:</strong>
<div class="grid grid-cols-2 gap-4 mt-2 text-sm">
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Created By:</span>
<span class="ml-2 metadata-created-by"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Created At:</span>
<span class="ml-2 metadata-created-at"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Created From IP:</span>
<span class="ml-2 metadata-created-from"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Created Via:</span>
<span class="ml-2 metadata-created-via"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Last Modified By:</span>
<span class="ml-2 metadata-modified-by"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Last Modified At:</span>
<span class="ml-2 metadata-modified-at"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Modified From IP:</span>
<span class="ml-2 modified-from"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Modified Via:</span>
<span class="ml-2 metadata-modified-via"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Version:</span>
<span class="ml-2 metadata-version"></span>
</div>
<div>
<span class="font-medium text-gray-600 dark:text-gray-400">Import Batch:</span>
<span class="ml-2 metadata-import-batch"></span>
</div>
</div>
</div>
</div>
`;
// Set structure first
safeSetInnerHTML(toolDetailsDiv, safeHTML, true);
// Now safely set text content - NO ESCAPING since textContent is safe
const setTextSafely = (selector, value) => {
const element = toolDetailsDiv.querySelector(selector);
if (element) {
element.textContent = value || "N/A";
}
};
setTextSafely(".tool-id", tool.id);
// Inject copy button next to tool ID
const toolIdEl = toolDetailsDiv.querySelector(".tool-id");
if (toolIdEl && tool.id) {
toolIdEl.appendChild(makeCopyIdButton(tool.id));
}
setTextSafely(
".tool-display-name",
tool.displayName || tool.customName || tool.name
);
const cleanDesc = tool.description
? tool.description.slice(
0,
tool.description.indexOf("*") > 0
? tool.description.indexOf("*")
: tool.description.length
)
: "";
const decodedDesc = decodeHtml(cleanDesc);
setTextSafely(".tool-name", tool.name);
setTextSafely(".tool-url", tool.url);
setTextSafely(".tool-type", tool.integrationType);
setTextSafely(".tool-description", decodedDesc);
setTextSafely(".tool-visibility", tool.visibility);
// Set tags as HTML with badges
const tagsElement = toolDetailsDiv.querySelector(".tool-tags");
if (tagsElement) {
if (tool.tags && tool.tags.length > 0) {
tagsElement.innerHTML = tool.tags
.map((tag) => {
const raw =
typeof tag === "object" && tag !== null
? tag.id || tag.label || JSON.stringify(tag)
: tag;
return `<span class="inline-block bg-blue-100 text-blue-800 text-xs px-2 py-1 rounded-full mr-1 mb-1 dark:bg-blue-900 dark:text-blue-200">${escapeHtml(raw)}</span>`;
})
.join("");
} else {
tagsElement.textContent = "None";
}
}
setTextSafely(".tool-request-type", tool.requestType);
setTextSafely(
".tool-headers",
JSON.stringify(tool.headers || {}, null, 2)
);
setTextSafely(
".tool-schema",
JSON.stringify(tool.inputSchema || {}, null, 2)
);
setTextSafely(
".tool-output-schema",
JSON.stringify(tool.outputSchema || {}, null, 2)
);
// Set auth fields safely
if (tool.auth?.username) {
setTextSafely(".auth-username", tool.auth.username);
}
if (tool.auth?.authHeaderKey) {
setTextSafely(".auth-header-key", tool.auth.authHeaderKey);
}
// Set annotation title safely
if (tool.annotations?.title) {
setTextSafely(".annotation-title", tool.annotations.title);
}
// Set custom annotations safely
const customAnnotations =
toolDetailsDiv.querySelectorAll(".custom-annotation");
customAnnotations.forEach((element) => {
const key = element.dataset.key;
const value = element.dataset.value;
element.textContent = `${key}: ${value}`;
});
// Set metrics safely
setTextSafely(".metric-total", tool.metrics?.totalExecutions ?? 0);
setTextSafely(".metric-success", tool.metrics?.successfulExecutions ?? 0);
setTextSafely(".metric-failed", tool.metrics?.failedExecutions ?? 0);
setTextSafely(".metric-failure-rate", tool.metrics?.failureRate ?? 0);
setTextSafely(".metric-min-time", tool.metrics?.minResponseTime ?? "N/A");
setTextSafely(".metric-max-time", tool.metrics?.maxResponseTime ?? "N/A");
setTextSafely(".metric-avg-time", tool.metrics?.avgResponseTime ?? "N/A");
setTextSafely(
".metric-last-time",
tool.metrics?.lastExecutionTime ?? "N/A"
);
// Set metadata fields safely with appropriate fallbacks for legacy entities
setTextSafely(
".metadata-created-by",
tool.created_by || tool.createdBy || "Legacy Entity"
);
setTextSafely(
".metadata-created-at",
tool.created_at
? new Date(tool.created_at).toLocaleString()
: tool.createdAt
? new Date(tool.createdAt).toLocaleString()
: "Pre-metadata"
);
setTextSafely(
".metadata-created-from",
tool.created_from_ip || tool.createdFromIp || "Unknown"
);
setTextSafely(
".metadata-created-via",
tool.created_via || tool.createdVia || "Unknown"
);
setTextSafely(
".metadata-modified-by",
tool.modified_by || tool.modifiedBy || "N/A"
);
setTextSafely(
".metadata-modified-at",
tool.updated_at
? new Date(tool.updated_at).toLocaleString()
: tool.updatedAt
? new Date(tool.updatedAt).toLocaleString()
: "N/A"
);
setTextSafely(
".metadata-modified-from",
tool.modified_from_ip || tool.modifiedFromIp || "N/A"
);
setTextSafely(
".metadata-modified-via",
tool.modified_via || tool.modifiedVia || "N/A"
);
setTextSafely(".metadata-version", tool.version || "1");
setTextSafely(
".metadata-import-batch",
tool.import_batch_id || tool.importBatchId || "N/A"
);
}
openModal("tool-modal");
console.log("✓ Tool details loaded successfully");
} catch (error) {
console.error("Error fetching tool details:", error);
const errorMessage = handleFetchError(error, "load tool details");
showErrorMessage(errorMessage);
}
};
/**
* SECURE: Edit Tool function with input validation
*/
export const editTool = async function (toolId) {
try {
console.log(`Editing tool ID: ${toolId}`);
const response = await fetchWithTimeout(
`${window.ROOT_PATH}/admin/tools/${toolId}`
);
if (!response.ok) {
// If the response is not OK, throw an error
throw new Error(`HTTP ${response.status}: ${response.statusText}`);
}
const tool = await response.json();
const isInactiveCheckedBool = isInactiveChecked("tools");
let hiddenField = safeGetElement("edit-show-inactive");
if (!hiddenField) {
hiddenField = document.createElement("input");
hiddenField.type = "hidden";
hiddenField.name = "is_inactive_checked";
hiddenField.id = "edit-show-inactive";
const editForm = safeGetElement("edit-tool-form");
if (editForm) {
editForm.appendChild(hiddenField);
}
}
hiddenField.value = isInactiveCheckedBool;
// Set form action and populate basic fields with validation
const editForm = safeGetElement("edit-tool-form");
if (editForm) {
editForm.action = `${window.ROOT_PATH}/admin/tools/${toolId}/edit`;
}
// Validate and set fields
const nameValidation = validateInputName(tool.name, "tool");
const customNameValidation = validateInputName(tool.customName, "tool");
const urlValidation = validateUrl(tool.url);
const nameField = safeGetElement("edit-tool-name");
const customNameField = safeGetElement("edit-tool-custom-name");
const urlField = safeGetElement("edit-tool-url");
const descField = safeGetElement("edit-tool-description");
const typeField = safeGetElement("edit-tool-type");
if (nameField && nameValidation.valid) {
nameField.value = nameValidation.value;
}
if (customNameField && customNameValidation.valid) {
customNameField.value = customNameValidation.value;
}
const displayNameField = safeGetElement("edit-tool-display-name");
if (displayNameField) {
displayNameField.value = tool.displayName || "";
}
if (urlField && urlValidation.valid) {
urlField.value = urlValidation.value;
}
if (descField) {
// Decode HTML entities to prevent double-encoding when saving
const cleanDesc = tool.description
? tool.description.slice(
0,
tool.description.indexOf("*") > 0
? tool.description.indexOf("*")
: tool.description.length
)
: "";
descField.value = decodeHtml(cleanDesc);
}
if (typeField) {
typeField.value = tool.integrationType || "MCP";
}
// Set tags field
const tagsField = safeGetElement("edit-tool-tags");
if (tagsField) {
const rawTags = tool.tags
? tool.tags.map((tag) =>
typeof tag === "object" && tag !== null ? tag.label || tag.id : tag
)
: [];
tagsField.value = rawTags.join(", ");
}
const teamId = new URL(window.location.href).searchParams.get("team_id");
if (teamId) {
const hiddenInput = document.createElement("input");
hiddenInput.type = "hidden";
hiddenInput.name = "team_id";
hiddenInput.value = teamId;
editForm.appendChild(hiddenInput);
}
const visibility = tool.visibility ? tool.visibility.toLowerCase() : null;
const publicRadio = safeGetElement("edit-tool-visibility-public");
const teamRadio = safeGetElement("edit-tool-visibility-team");
const privateRadio = safeGetElement("edit-tool-visibility-private");
// Clear all first
if (publicRadio) {
publicRadio.checked = false;
}
if (teamRadio) {
teamRadio.checked = false;
}
if (privateRadio) {
privateRadio.checked = false;
}
if (visibility) {
// When public visibility is disabled and we're in a team-scoped view,
// coerce legacy-public records to team.
const effectiveVisibility =
window.ALLOW_PUBLIC_VISIBILITY === false &&
visibility === "public" &&
teamId
? "team"
: visibility;
if (effectiveVisibility === "public" && publicRadio) {
publicRadio.checked = true;
} else if (effectiveVisibility === "team" && teamRadio) {
teamRadio.checked = true;
} else if (effectiveVisibility === "private" && privateRadio) {
privateRadio.checked = true;
}
}
// Handle JSON fields safely with validation
const headersValidation = validateJson(
JSON.stringify(tool.headers || {}),
"Headers"
);
const schemaValidation = validateJson(
JSON.stringify(tool.inputSchema || {}),
"Schema"
);
const outputSchemaValidation = validateJson(
tool.outputSchema ? JSON.stringify(tool.outputSchema) : "",
"Output Schema"
);
const annotationsValidation = validateJson(
JSON.stringify(tool.annotations || {}),
"Annotations"
);
const headersField = safeGetElement("edit-tool-headers");
const schemaField = safeGetElement("edit-tool-schema");
const outputSchemaField = safeGetElement("edit-tool-output-schema");
const annotationsField = safeGetElement("edit-tool-annotations");
if (headersField && headersValidation.valid) {
headersField.value = JSON.stringify(headersValidation.value, null, 2);
}
if (schemaField && schemaValidation.valid) {
schemaField.value = JSON.stringify(schemaValidation.value, null, 2);
}
if (outputSchemaField) {
if (tool.outputSchema) {
outputSchemaField.value = outputSchemaValidation.valid
? JSON.stringify(outputSchemaValidation.value, null, 2)
: "";
} else {
outputSchemaField.value = "";
}
}
if (annotationsField && annotationsValidation.valid) {
annotationsField.value = JSON.stringify(
annotationsValidation.value,
null,
2
);
}
// Update CodeMirror editors if they exist
if (window.editToolHeadersEditor && headersValidation.valid) {
window.editToolHeadersEditor.setValue(
JSON.stringify(headersValidation.value, null, 2)
);
window.editToolHeadersEditor.refresh();
}
if (window.editToolSchemaEditor && schemaValidation.valid) {
window.editToolSchemaEditor.setValue(
JSON.stringify(schemaValidation.value, null, 2)
);
window.editToolSchemaEditor.refresh();
}
if (window.editToolOutputSchemaEditor) {
if (tool.outputSchema && outputSchemaValidation.valid) {
window.editToolOutputSchemaEditor.setValue(
JSON.stringify(outputSchemaValidation.value, null, 2)
);
} else {
window.editToolOutputSchemaEditor.setValue("");
}
window.editToolOutputSchemaEditor.refresh();
}
// Prefill integration type from DB and set request types accordingly
if (typeField) {
typeField.value = tool.integrationType || "REST";
// Disable integration type field for MCP tools (cannot be changed)
if (tool.integrationType === "MCP") {
typeField.disabled = true;
} else {
typeField.disabled = false;
}
updateEditToolRequestTypes(tool.requestType || null); // preselect from DB
updateEditToolUrl(tool.url || null);
}
// Request Type field handling (disable for MCP)
const requestTypeField = safeGetElement("edit-tool-request-type");
if (requestTypeField) {
if ((tool.integrationType || "REST") === "MCP") {
requestTypeField.value = "";
requestTypeField.disabled = true; // disabled -> not submitted
} else {
requestTypeField.disabled = false;
requestTypeField.value = tool.requestType || ""; // keep DB verb or blank
}
}
// Set auth type field
const authTypeField = safeGetElement("edit-auth-type");
if (authTypeField) {
authTypeField.value = tool.auth?.authType || "";
}
const editAuthTokenField = safeGetElement("edit-auth-token");
// Prefill integration type from DB and set request types accordingly
if (typeField) {
// Always set value from DB, never from previous UI state
typeField.value = tool.integrationType;
// Remove any previous hidden field for type
const prevHiddenType = safeGetElement("hidden-edit-tool-type");
if (prevHiddenType) {
prevHiddenType.remove();
}
// Remove any previous hidden field for authType
const prevHiddenAuthType = safeGetElement("hidden-edit-auth-type");
if (prevHiddenAuthType) {
prevHiddenAuthType.remove();
}
// Disable integration type field for MCP tools (cannot be changed)
if (tool.integrationType === "MCP") {
typeField.disabled = true;
if (authTypeField) {
authTypeField.disabled = true;
// Add hidden field for authType
const hiddenAuthTypeField = document.createElement("input");
hiddenAuthTypeField.type = "hidden";
hiddenAuthTypeField.name = authTypeField.name;
hiddenAuthTypeField.value = authTypeField.value;
hiddenAuthTypeField.id = "hidden-edit-auth-type";
authTypeField.form.appendChild(hiddenAuthTypeField);
}
if (urlField) {
urlField.readOnly = true;
}
if (headersField) {
headersField.setAttribute("readonly", "readonly");
}
if (schemaField) {
schemaField.setAttribute("readonly", "readonly");
}
if (editAuthTokenField) {
editAuthTokenField.setAttribute("readonly", "readonly");
}
if (window.editToolHeadersEditor) {
window.editToolHeadersEditor.setOption("readOnly", true);
}
if (window.editToolSchemaEditor) {
window.editToolSchemaEditor.setOption("readOnly", true);
}
if (window.editToolOutputSchemaEditor) {
window.editToolOutputSchemaEditor.setOption("readOnly", true);
}
} else {
typeField.disabled = false;
if (authTypeField) {
authTypeField.disabled = false;
}
if (urlField) {
urlField.readOnly = false;
}
if (headersField) {
headersField.removeAttribute("readonly");
}
if (schemaField) {
schemaField.removeAttribute("readonly");
}
if (editAuthTokenField) {
editAuthTokenField.removeAttribute("readonly");
}
if (window.editToolHeadersEditor) {
window.editToolHeadersEditor.setOption("readOnly", false);
}
if (window.editToolSchemaEditor) {
window.editToolSchemaEditor.setOption("readOnly", false);
}
if (window.editToolOutputSchemaEditor) {
window.editToolOutputSchemaEditor.setOption("readOnly", false);
}
}
// Update request types and URL field
updateEditToolRequestTypes(tool.requestType || null);
updateEditToolUrl(tool.url || null);
}
// Auth containers
const authBasicSection = safeGetElement("edit-auth-basic-fields");
const authBearerSection = safeGetElement("edit-auth-bearer-fields");
const authHeadersSection = safeGetElement("edit-auth-headers-fields");
// Individual fields
const authUsernameField = authBasicSection?.querySelector(
"input[name='auth_username']"
);
const authPasswordField = authBasicSection?.querySelector(
"input[name='auth_password']"
);
const authTokenField = authBearerSection?.querySelector(
"input[name='auth_token']"
);
const authHeaderKeyField = authHeadersSection?.querySelector(
"input[name='auth_header_key']"
);
const authHeaderValueField = authHeadersSection?.querySelector(
"input[name='auth_header_value']"
);
const authHeadersContainer = safeGetElement(
"auth-headers-container-gw-edit"
);
const authHeadersJsonInput = safeGetElement("auth-headers-json-gw-edit");
if (authHeadersContainer) {
authHeadersContainer.innerHTML = "";
}
if (authHeadersJsonInput) {
authHeadersJsonInput.value = "";
}
// Hide all auth sections first
if (authBasicSection) {
authBasicSection.style.display = "none";
}
if (authBearerSection) {
authBearerSection.style.display = "none";
}
if (authHeadersSection) {
authHeadersSection.style.display = "none";
}
// Clear old values
if (authUsernameField) {
authUsernameField.value = "";
}
if (authPasswordField) {
authPasswordField.value = "";
}
if (authTokenField) {
authTokenField.value = "";
}
if (authHeaderKeyField) {
authHeaderKeyField.value = "";
}
if (authHeaderValueField) {
authHeaderValueField.value = "";
}
// Display appropriate auth section and populate values
switch (tool.auth?.authType) {
case "basic":
if (authBasicSection) {
authBasicSection.style.display = "block";
if (authUsernameField) {
authUsernameField.value = tool.auth.username || "";
}
if (authPasswordField) {
authPasswordField.value = "*****"; // masked
}
}
break;
case "bearer":
if (authBearerSection) {
authBearerSection.style.display = "block";
if (authTokenField) {
authTokenField.value = "*****"; // masked
}
}
break;
case "authheaders":
if (authHeadersSection) {
authHeadersSection.style.display = "block";
if (
Array.isArray(tool.auth.authHeaders) &&
tool.auth.authHeaders.length > 0
) {
loadAuthHeaders(
"edit-auth-headers-container",
tool.auth.authHeaders,
{ maskValues: true }
);
} else {
updateAuthHeadersJSON("edit-auth-headers-container");
}
if (authHeaderKeyField) {
authHeaderKeyField.value = tool.auth.authHeaderKey || "";
}
if (authHeaderValueField) {
if (
Array.isArray(tool.auth.authHeaders) &&
tool.auth.authHeaders.length === 1
) {
authHeaderValueField.dataset.isMasked = "true";
authHeaderValueField.dataset.realValue =
tool.auth.authHeaders[0].value ?? "";
}
authHeaderValueField.value = "*****"; // masked
}
}
break;
case "":
default:
// No auth – keep everything hidden
break;
}
openModal("tool-edit-modal");
applyVisibilityRestrictions(["edit-resource-visibility"]); // Disable public radio if restricted, preserve checked state
// Ensure editors are refreshed after modal display
setTimeout(() => {
if (window.editToolHeadersEditor) {
window.editToolHeadersEditor.refresh();
}
if (window.editToolSchemaEditor) {
window.editToolSchemaEditor.refresh();
}
if (window.editToolOutputSchemaEditor) {
window.editToolOutputSchemaEditor.refresh();
}
}, 100);
console.log("✓ Tool edit modal loaded successfully");
} catch (error) {
console.error("Error fetching tool details for editing:", error);
const errorMessage = handleFetchError(error, "load tool for editing");
showErrorMessage(errorMessage);
}
};
// ===================================================================
// TOOL SELECT FUNCTIONALITY
// ===================================================================
export const initToolSelect = function (
selectId,
pillsId,
warnId,
max = 6,
selectBtnId = null,
clearBtnId = null
) {
const container = safeGetElement(selectId);
const pillsBox = safeGetElement(pillsId);
const warnBox = safeGetElement(warnId);
const clearBtn = clearBtnId ? safeGetElement(clearBtnId) : null;
const selectBtn = selectBtnId ? safeGetElement(selectBtnId) : null;
if (!container || !pillsBox || !warnBox) {
console.warn(
`Tool select elements not found: ${selectId}, ${pillsId}, ${warnId}`
);
return;
}
const pillClasses =
"inline-block bg-green-100 text-green-800 text-xs px-2 py-1 rounded-full dark:bg-green-900 dark:text-green-200";
const update = function () {
try {
const checkboxes = container.querySelectorAll('input[type="checkbox"]');
const checked = Array.from(checkboxes).filter((cb) => cb.checked);
// Check if "Select All" mode is active
const selectAllInput = container.querySelector(
'input[name="selectAllTools"]'
);
const allIdsInput = container.querySelector('input[name="allToolIds"]');
// Check if this is the edit server tools container