-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathToolSelect.tsx
More file actions
934 lines (872 loc) · 32.7 KB
/
ToolSelect.tsx
File metadata and controls
934 lines (872 loc) · 32.7 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
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ========= Copyright 2025-2026 @ Eigent.ai All Rights Reserved. =========
import {
fetchGet,
fetchPost,
proxyFetchGet,
proxyFetchPost,
proxyFetchPut,
} from '@/api/http';
import githubIcon from '@/assets/github.svg';
import IntegrationList from '@/components/IntegrationList';
import { Badge } from '@/components/ui/badge';
import { capitalizeFirstLetter, getProxyBaseURL } from '@/lib';
import { useAuthStore } from '@/store/authStore';
import { CircleAlert, Store, X } from 'lucide-react';
import {
forwardRef,
useCallback,
useEffect,
useImperativeHandle,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import { Button } from '../ui/button';
import { Textarea } from '../ui/textarea';
import { TooltipSimple } from '../ui/tooltip';
import AnthropicIcon from '@/assets/mcp/Anthropic.svg?url';
import CamelIcon from '@/assets/mcp/Camel.svg?url';
import CommunityIcon from '@/assets/mcp/Community.svg?url';
import OfficialIcon from '@/assets/mcp/Official.svg?url';
interface McpItem {
id: number;
name: string;
key: string;
description: string;
category?: { name: string };
home_page?: string;
install_command?: {
env?: { [key: string]: string };
};
toolkit?: string;
isLocal?: boolean;
}
interface ToolSelectProps {
onShowEnvConfig?: (mcp: McpItem) => void;
onSelectedToolsChange?: (tools: McpItem[]) => void;
initialSelectedTools?: McpItem[];
}
const ToolSelect = forwardRef<
{ installMcp: (id: number, env?: any, activeMcp?: any) => Promise<void> },
ToolSelectProps
>(({ onShowEnvConfig, onSelectedToolsChange, initialSelectedTools }, ref) => {
const { t } = useTranslation();
// state management - remove internal selected state, use parent passed initialSelectedTools
const [keyword, setKeyword] = useState<string>('');
const [mcpList, setMcpList] = useState<McpItem[]>([]);
const [allMcpList, setAllMcpList] = useState<McpItem[]>([]);
const [customMcpList, setCustomMcpList] = useState<any[]>([]);
const [isOpen, setIsOpen] = useState(false);
const [installed, setInstalled] = useState<{ [id: number]: boolean }>({});
const [installing, setInstalling] = useState<{ [id: number]: boolean }>({});
const [installedIds, setInstalledIds] = useState<number[]>([]);
const { email } = useAuthStore();
// add: integration service list
const [integrations, setIntegrations] = useState<any[]>([]);
// select management
const addOption = useCallback(
(item: McpItem, isLocal?: boolean) => {
setKeyword('');
const currentSelected = initialSelectedTools || [];
console.log(currentSelected.find((i) => i.id === item.id));
if (isLocal) {
if (!currentSelected.find((i) => i.key === item.key)) {
const newSelected = [...currentSelected, { ...item, isLocal }];
onSelectedToolsChange?.(newSelected);
}
return;
}
if (!currentSelected.find((i) => i.id === item.id)) {
if (!isLocal) isLocal = false;
const newSelected = [...currentSelected, { ...item, isLocal }];
onSelectedToolsChange?.(newSelected);
}
},
[initialSelectedTools, onSelectedToolsChange]
);
const fetchIntegrationsData = useCallback(
(keyword?: string) => {
proxyFetchGet('/api/v1/config/info')
.then((res) => {
if (res && typeof res === 'object' && !res.error) {
const baseURL = getProxyBaseURL();
const list = Object.entries(res)
.filter(([key]) => {
if (!keyword) return true;
return key.toLowerCase().includes(keyword.toLowerCase());
})
.map(([key, value]: [string, any]) => {
let onInstall = null;
// Special handling for Notion MCP
if (key.toLowerCase() === 'notion') {
onInstall = async () => {
try {
const response = await fetchPost('/install/tool/notion');
if (response.success) {
// Check if there's a warning (connection failed but installation marked as complete)
if (response.warning) {
console.warn(
'Notion MCP connection warning:',
response.warning
);
// Still proceed but log the warning
}
// Save to config to mark as installed
await proxyFetchPost('/api/v1/configs', {
config_group: 'Notion',
config_name: 'MCP_REMOTE_CONFIG_DIR',
config_value:
response.toolkit_name || 'NotionMCPToolkit',
});
console.log('Notion MCP installed successfully');
// After successful installation, add to selected tools
const notionItem = {
id: 0, // Use 0 for integration items
key: key,
name: key,
description:
'Notion workspace integration for reading and managing Notion pages',
toolkit: 'notion_mcp_toolkit', // Add the toolkit name
isLocal: true,
};
addOption(notionItem, true);
} else {
console.error(
'Failed to install Notion MCP:',
response.error || 'Unknown error'
);
throw new Error(
response.error || 'Failed to install Notion MCP'
);
}
} catch (error: any) {
console.error(
'Failed to install Notion MCP:',
error.message
);
throw error;
}
};
} else if (key.toLowerCase() === 'google calendar') {
onInstall = async () => {
try {
const response = await fetchPost(
'/install/tool/google_calendar'
);
if (response.success) {
if (response.warning) {
console.warn(
'Google Calendar connection warning:',
response.warning
);
}
try {
const existingConfigs =
await proxyFetchGet('/api/v1/configs');
const existing = Array.isArray(existingConfigs)
? existingConfigs.find(
(c: any) =>
c.config_group?.toLowerCase() ===
'google calendar' &&
c.config_name === 'GOOGLE_REFRESH_TOKEN'
)
: null;
const configPayload = {
config_group: 'Google Calendar',
config_name: 'GOOGLE_REFRESH_TOKEN',
config_value: 'exists',
};
if (existing) {
await proxyFetchPut(
`/api/v1/configs/${existing.id}`,
configPayload
);
} else {
await proxyFetchPost(
'/api/v1/configs',
configPayload
);
}
} catch (configError) {
console.warn(
'Failed to persist Google Calendar config',
configError
);
}
console.log('Google Calendar installed successfully');
const calendarItem = {
id: 0, // Use 0 for integration items
key: key,
name: key,
description:
'Google Calendar integration for managing events and schedules',
toolkit: 'google_calendar_toolkit', // Add the toolkit name
isLocal: true,
};
addOption(calendarItem, true);
} else if (response.status === 'authorizing') {
console.log(
'Google Calendar authorization in progress. Please complete in browser.'
);
if (response.message) {
console.log(response.message);
}
} else {
console.error(
'Failed to install Google Calendar:',
response.error || 'Unknown error'
);
throw new Error(
response.error || 'Failed to install Google Calendar'
);
}
return response;
} catch (error: any) {
if (!error.message?.includes('authorization')) {
console.error(
'Failed to install Google Calendar:',
error.message
);
throw error;
}
return null; // Return null on authorization flow errors
}
};
} else {
onInstall = () =>
window.open(
`${baseURL}/api/v1/oauth/${key.toLowerCase()}/login`,
'_blank',
'width=600,height=700'
);
}
return {
key: key,
name: key,
env_vars: value.env_vars,
toolkit: value.toolkit,
desc:
value.env_vars && value.env_vars.length > 0
? `${t('layout.environmental-variables-required')} ${value.env_vars.join(
', '
)}`
: key.toLowerCase() === 'notion'
? t('layout.notion-workspace-integration')
: key.toLowerCase() === 'google calendar'
? t('layout.google-calendar-integration')
: '',
onInstall,
};
});
setIntegrations(list);
} else {
console.error('Failed to fetch integrations:', res);
setIntegrations([]);
}
})
.catch((error) => {
console.error('Error fetching integrations:', error);
setIntegrations([]);
});
},
[addOption, t]
);
// Refs
const inputRef = useRef<HTMLTextAreaElement>(null);
const debounceTimerRef = useRef<NodeJS.Timeout | null>(null);
const containerRef = useRef<HTMLDivElement>(null);
// constants
const categoryIconMap: Record<string, string> = {
anthropic: 'Anthropic',
community: 'Community',
official: 'Official',
camel: 'Camel',
};
const svgIcons: Record<string, string> = {
Anthropic: AnthropicIcon,
Community: CommunityIcon,
Official: OfficialIcon,
Camel: CamelIcon,
};
// data fetching
const fetchData = useCallback((keyword?: string) => {
proxyFetchGet('/api/v1/mcps', {
keyword: keyword || '',
page: 1,
size: 100,
})
.then((res) => {
// Add defensive check for API errors
if (res && res.items && Array.isArray(res.items)) {
setAllMcpList(res.items);
} else {
console.error('Failed to fetch MCPs:', res);
setAllMcpList([]);
}
})
.catch((error) => {
console.error('Error fetching MCPs:', error);
setAllMcpList([]);
});
}, []);
const fetchInstalledMcps = useCallback(() => {
proxyFetchGet('/api/v1/mcp/users')
.then((res) => {
let dataList = [];
let ids: number[] = [];
if (Array.isArray(res)) {
ids = res.map((item: any) => item.mcp_id);
dataList = res;
} else if (res && Array.isArray(res.items)) {
ids = res.items.map((item: any) => item.mcp_id);
dataList = res.items;
}
setInstalledIds(ids);
const customMcpList = dataList.filter((item: any) => item.mcp_id === 0);
setCustomMcpList(customMcpList);
})
.catch((error) => {
console.error('Error fetching installed MCPs:', error);
setInstalledIds([]);
setCustomMcpList([]);
});
}, []);
// only surface installed MCPs from the market list
useEffect(() => {
// Add defensive check and fix logic: should filter when installedIds has items
if (Array.isArray(allMcpList) && installedIds.length > 0) {
const filtered = allMcpList.filter((item) =>
installedIds.includes(item.id)
);
setMcpList(filtered);
} else if (Array.isArray(allMcpList)) {
// If no installed IDs, show empty list instead of all
setMcpList([]);
}
}, [allMcpList, installedIds]);
// public save env/config logic
const saveEnvAndConfig = async (
provider: string,
envVarKey: string,
value: string
) => {
// First fetch current configs to check for existing ones
const configsRes = await proxyFetchGet('/api/v1/configs');
const configs = Array.isArray(configsRes) ? configsRes : [];
const configPayload = {
config_group: capitalizeFirstLetter(provider),
config_name: envVarKey,
config_value: value,
};
// Check if config already exists
const existingConfig = configs.find(
(c: any) =>
c.config_name === envVarKey &&
c.config_group?.toLowerCase() === provider.toLowerCase()
);
if (existingConfig) {
// Update existing config
await proxyFetchPut(
`/api/v1/configs/${existingConfig.id}`,
configPayload
);
} else {
// Create new config
await proxyFetchPost('/api/v1/configs', configPayload);
}
if (window.electronAPI?.envWrite) {
await window.electronAPI.envWrite(email, { key: envVarKey, value });
}
};
// MCP install related
const installMcp = async (
id: number,
envValue?: { [key: string]: any },
activeMcp?: any
) => {
// is exa search or google calendar
if (activeMcp && envValue) {
const env: { [key: string]: string } = {};
Object.keys(envValue).map((key) => {
env[key] = envValue[key]?.value;
});
activeMcp.install_command.env = env;
// Save all env vars and wait for completion
console.log('[installMcp] Saving env vars for', activeMcp.key);
try {
await Promise.all(
Object.keys(activeMcp.install_command.env).map(async (key) => {
console.log(
'[installMcp] Saving',
key,
'=',
activeMcp.install_command.env[key]
);
return saveEnvAndConfig(
activeMcp.key,
key,
activeMcp.install_command.env[key]
);
})
);
console.log('[installMcp] All env vars saved successfully');
} catch (error) {
console.error('[installMcp] Failed to save env vars:', error);
// Continue anyway to trigger installation
}
if (activeMcp.key !== 'Google Calendar') {
const integrationItem = integrations.find(
(item) => item.key === activeMcp.key
);
addOption(
{
id: activeMcp.id,
key: activeMcp.key,
name: activeMcp.name ?? activeMcp.key,
description:
typeof integrationItem?.desc === 'string'
? integrationItem.desc
: '',
toolkit: integrationItem?.toolkit,
isLocal: true,
},
true
);
return;
}
// Trigger instantiation for Google Calendar
if (activeMcp.key === 'Google Calendar') {
console.log(
'[ToolSelect installMcp] Starting Google Calendar installation'
);
try {
const response = await fetchPost('/install/tool/google_calendar');
if (response.success) {
console.log('[ToolSelect installMcp] Immediate success');
// Mark as successfully installed by writing refresh token marker
const existingConfigs = await proxyFetchGet('/api/v1/configs');
const existing = Array.isArray(existingConfigs)
? existingConfigs.find(
(c: any) =>
c.config_group?.toLowerCase() === 'google calendar' &&
c.config_name === 'GOOGLE_REFRESH_TOKEN'
)
: null;
const configPayload = {
config_group: 'Google Calendar',
config_name: 'GOOGLE_REFRESH_TOKEN',
config_value: 'exists',
};
if (existing) {
await proxyFetchPut(
`/api/v1/configs/${existing.id}`,
configPayload
);
} else {
await proxyFetchPost('/api/v1/configs', configPayload);
}
// Refresh integrations to update install status
fetchIntegrationsData();
const selectedItem = {
id: activeMcp.id,
key: activeMcp.key,
name: activeMcp.name,
description:
'Google Calendar integration for managing events and schedules',
toolkit: 'google_calendar_toolkit',
isLocal: true,
};
addOption(selectedItem, true);
} else if (response.status === 'authorizing') {
// Authorization in progress - browser should have opened
console.log(
'[ToolSelect installMcp] Authorization required, starting polling loop'
);
// WAIT for OAuth status completion instead of using setInterval
const start = Date.now();
const timeoutMs = 5 * 60 * 1000; // 5 minutes
while (Date.now() - start < timeoutMs) {
try {
const statusResponse = await fetchGet(
'/oauth/status/google_calendar'
);
console.log(
'[ToolSelect installMcp] OAuth status:',
statusResponse.status
);
if (statusResponse.status === 'success') {
console.log(
'[ToolSelect installMcp] Authorization completed successfully!'
);
// Try installing again now that authorization is complete
const retryResponse = await fetchPost(
'/install/tool/google_calendar'
);
if (retryResponse.success) {
// Mark as successfully installed
const existingConfigs =
await proxyFetchGet('/api/v1/configs');
const existing = Array.isArray(existingConfigs)
? existingConfigs.find(
(c: any) =>
c.config_group?.toLowerCase() ===
'google calendar' &&
c.config_name === 'GOOGLE_REFRESH_TOKEN'
)
: null;
const configPayload = {
config_group: 'Google Calendar',
config_name: 'GOOGLE_REFRESH_TOKEN',
config_value: 'exists',
};
if (existing) {
await proxyFetchPut(
`/api/v1/configs/${existing.id}`,
configPayload
);
} else {
await proxyFetchPost('/api/v1/configs', configPayload);
}
fetchIntegrationsData();
const selectedItem = {
id: activeMcp.id,
key: activeMcp.key,
name: activeMcp.name,
description:
'Google Calendar integration for managing events and schedules',
toolkit: 'google_calendar_toolkit',
isLocal: true,
};
addOption(selectedItem, true);
}
console.log(
'[ToolSelect installMcp] Installation complete, returning'
);
return;
} else if (statusResponse.status === 'failed') {
console.error(
'[ToolSelect installMcp] Authorization failed:',
statusResponse.error
);
return;
} else if (statusResponse.status === 'cancelled') {
console.log(
'[ToolSelect installMcp] Authorization cancelled'
);
return;
}
} catch (error) {
console.error(
'[ToolSelect installMcp] Error polling OAuth status:',
error
);
}
// Wait before next poll
await new Promise((r) => setTimeout(r, 1500));
}
console.log('[ToolSelect installMcp] Polling timeout');
return;
} else {
console.error(
'Failed to install Google Calendar:',
response.error || 'Unknown error'
);
}
} catch (error: any) {
console.error('Failed to install Google Calendar:', error.message);
}
}
return;
}
setInstalling((prev) => ({ ...prev, [id]: true }));
try {
await proxyFetchPost('/api/v1/mcp/install?mcp_id=' + id);
setInstalled((prev) => ({ ...prev, [id]: true }));
const installedMcp = mcpList.find((mcp) => mcp.id === id);
if (window.ipcRenderer && installedMcp) {
const env: { [key: string]: string } = {};
if (envValue) {
Object.keys(envValue).map((key) => {
env[key] = envValue[key]?.value;
});
installedMcp.install_command!.env = env;
}
await window.ipcRenderer.invoke(
'mcp-install',
installedMcp.key,
installedMcp.install_command
);
}
// after install successfully, automatically add to selected list
if (installedMcp) {
addOption(installedMcp);
}
} catch (e) {
console.error('Failed to install MCP:', e);
} finally {
setInstalling((prev) => ({ ...prev, [id]: false }));
}
};
// expose install method to parent component
useImperativeHandle(ref, () => ({
installMcp,
}));
const checkEnv = (id: number) => {
const mcp = mcpList.find((mcp) => mcp.id === id);
if (mcp && Object.keys(mcp?.install_command?.env || {}).length > 0) {
if (onShowEnvConfig) {
onShowEnvConfig(mcp);
}
} else {
installMcp(id);
}
};
const removeOption = (item: McpItem) => {
const currentSelected = initialSelectedTools || [];
const newSelected = currentSelected.filter((i) => i.id !== item.id);
onSelectedToolsChange?.(newSelected);
};
// tool functions
const getCategoryIcon = (categoryName?: string) => {
if (!categoryName) return <Store className="h-4 w-4 text-icon-primary" />;
const normalizedName = categoryName.toLowerCase();
const iconKey = categoryIconMap[normalizedName];
const iconUrl = iconKey ? svgIcons[iconKey] : undefined;
return iconUrl ? (
<img src={iconUrl} alt={categoryName} className="h-4 w-4" />
) : (
<Store className="h-4 w-4 text-icon-primary" />
);
};
const getGithubRepoName = (homePage?: string) => {
if (!homePage || !homePage.startsWith('https://github.com/')) return null;
const parts = homePage.split('/');
return parts.length > 4 ? parts[4] : homePage;
};
const getInstallButtonText = (itemId: number) => {
if (installedIds.includes(itemId)) return t('layout.installed');
if (installing[itemId]) return t('layout.installing');
if (installed[itemId]) return t('layout.installed');
return t('layout.install');
};
// Effects
useEffect(() => {
fetchData();
fetchIntegrationsData();
fetchInstalledMcps();
}, [fetchData, fetchIntegrationsData, fetchInstalledMcps]);
useEffect(() => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
debounceTimerRef.current = setTimeout(() => {
fetchData(keyword);
fetchIntegrationsData(keyword);
}, 500);
return () => {
if (debounceTimerRef.current) {
clearTimeout(debounceTimerRef.current);
}
};
}, [keyword, fetchData, fetchIntegrationsData]);
useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
if (
containerRef.current &&
!containerRef.current.contains(event.target as Node)
) {
setIsOpen(false);
}
};
document.addEventListener('mousedown', handleClickOutside);
return () => {
document.removeEventListener('mousedown', handleClickOutside);
};
}, []);
// render functions
const renderSelectedItems = () => (
<>
{(initialSelectedTools || []).map((item: any) => (
<Badge
key={item.id + item.key + (item.isLocal + '')}
className="h-5 gap-1 bg-button-tertiery-fill-default px-xs flex w-auto flex-shrink-0 items-center"
>
{item.name || item.mcp_name || item.key || `tool_${item.id}`}
<div className="rounded-sm bg-button-secondary-fill-disabled flex items-center justify-center">
<X
className="h-4 w-4 text-button-secondary-icon-disabled cursor-pointer"
onClick={() => removeOption(item)}
/>
</div>
</Badge>
))}
</>
);
const renderMcpItem = (item: McpItem) => (
<div
key={item.id}
onClick={() => {
// check if already installed
const isAlreadyInstalled =
installedIds.includes(item.id) || installed[item.id];
if (isAlreadyInstalled) {
// if already installed, add to selected list directly
addOption(item);
setKeyword('');
} else {
// if not installed, first check environment configuration, then install and add to selected list
checkEnv(item.id);
}
}}
className="px-3 py-2 hover:bg-surface-hover-subtle flex cursor-pointer justify-between"
>
<div className="gap-1 flex items-center">
{getCategoryIcon(item.category?.name)}
<div className="text-sm font-bold leading-17 text-text-action line-clamp-1 overflow-hidden break-words text-ellipsis">
{item.name}
</div>
<TooltipSimple content={item.description}>
<CircleAlert
className="h-4 w-4 text-icon-primary cursor-pointer"
onClick={(e) => e.stopPropagation()}
/>
</TooltipSimple>
</div>
<div className="gap-1 flex items-center">
{getGithubRepoName(item.home_page) && (
<div className="flex items-center">
<img
src={githubIcon}
alt="github"
style={{
width: 14.7,
height: 14.7,
marginRight: 4,
display: 'inline-block',
verticalAlign: 'middle',
}}
/>
<span className="text-xs font-medium leading-3 line-clamp-1 items-center justify-center self-stretch overflow-hidden break-words text-ellipsis">
{getGithubRepoName(item.home_page)}
</span>
</div>
)}
<Button
variant="primary"
size="sm"
disabled={
installed[item.id] ||
installing[item.id] ||
installedIds.includes(item.id)
}
onClick={(e) => {
e.stopPropagation();
checkEnv(item.id);
}}
>
{getInstallButtonText(item.id)}
</Button>
</div>
</div>
);
const renderCustomMcpItem = (item: any) => (
<div
key={item.id}
onClick={() => {
addOption(item);
setKeyword('');
}}
className="px-3 py-2 hover:bg-surface-hover-subtle flex cursor-pointer justify-between"
>
<div className="gap-1 flex items-center">
{/* {getCategoryIcon(item.category?.name)} */}
<div className="text-sm font-bold leading-17 text-text-action line-clamp-1 overflow-hidden break-words text-ellipsis">
{item.mcp_name}
</div>
<TooltipSimple content={item.mcp_desc}>
<CircleAlert
className="h-4 w-4 text-icon-primary cursor-pointer"
onClick={(e) => e.stopPropagation()}
/>
</TooltipSimple>
</div>
<div className="gap-1 flex items-center">
<Button
className="h-6 rounded-md bg-button-secondary-fill-default px-sm py-xs text-xs font-bold leading-17 text-button-secondary-text-default shadow-sm hover:bg-button-tertiery-text-default"
disabled={true}
>
{t('layout.installed')}
</Button>
</div>
</div>
);
return (
<div className="relative w-full" ref={containerRef}>
<div className="bg-white gap-1.5 rounded-lg flex min-h-[40px] flex-wrap border">
<div className="gap-1 text-sm font-bold leading-normal text-text-body flex items-center">
{t('workforce.agent-tool')}
<TooltipSimple content={t('workforce.agent-tool-tooltip')}>
<CircleAlert size={16} className="text-icon-primary" />
</TooltipSimple>
</div>
<div
onClick={() => {
inputRef.current?.focus();
setIsOpen(true);
}}
className="gap-1 rounded-lg border-input-border-default bg-input-bg-default py-1 flex max-h-[120px] min-h-[60px] w-full flex-wrap justify-start overflow-y-auto border border-solid px-[6px]"
>
{renderSelectedItems()}
<Textarea
variant="none"
value={keyword}
onChange={(e) => setKeyword(e.target.value)}
onFocus={() => setIsOpen(true)}
ref={inputRef}
className="p-0 text-sm leading-normal !h-[20px] w-auto resize-none border-none bg-transparent !shadow-none !ring-0 !ring-offset-0"
/>
</div>
</div>
{/* floating dropdown */}
{isOpen && (
<div className="left-0 right-0 mt-1 rounded-lg border-input-border-default bg-dropdown-bg absolute top-full z-50 overflow-y-auto border border-solid">
<div className="max-h-[192px] overflow-y-auto">
<IntegrationList
variant="select"
onShowEnvConfig={onShowEnvConfig}
addOption={addOption}
items={integrations}
translationNamespace="layout"
/>
{mcpList
.filter(
(opt) =>
!(initialSelectedTools || []).find((i) => i.id === opt.id)
)
.map(renderMcpItem)}
{customMcpList
.filter(
(opt) =>
!(initialSelectedTools || []).find((i) => i.id === opt.id)
)
.map(renderCustomMcpItem)}
</div>
</div>
)}
</div>
);
});
ToolSelect.displayName = 'ToolSelect';
export default ToolSelect;