File size: 57,042 Bytes
2517be1 | 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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 | /**
* mcpStore - Reactive State Store for MCP Operations
*
* Implements the "Host" role in MCP architecture, coordinating multiple server
* connections and providing a unified interface for tool operations.
*
* **Architecture & Relationships:**
* - **MCPService**: Stateless protocol layer (transport, connect, callTool)
* - **mcpStore** (this): Reactive state + business logic
*
* **Key Responsibilities:**
* - Lifecycle management (initialize, shutdown)
* - Multi-server coordination
* - Tool name conflict detection and resolution
* - OpenAI-compatible tool definition generation
* - Automatic tool-to-server routing
* - Health checks
*
* @see MCPService in services/mcp.service.ts for protocol operations
*/
import { browser } from '$app/environment';
import { base } from '$app/paths';
import { MCPService } from '$lib/services/mcp.service';
import { config, settingsStore } from '$lib/stores/settings.svelte';
import { mcpResourceStore } from '$lib/stores/mcp-resources.svelte';
import { mode } from 'mode-watcher';
import {
getProxiedUrlString,
parseMcpServerSettings,
detectMcpTransportFromUrl,
getFaviconUrl,
uuid
} from '$lib/utils';
import {
MCPConnectionPhase,
MCPLogLevel,
HealthCheckStatus,
MCPRefType,
ColorMode,
UrlProtocol,
JsonSchemaType,
ToolCallType
} from '$lib/enums';
import {
CORS_PROXY_ENDPOINT,
DEFAULT_CACHE_TTL_MS,
DEFAULT_MCP_CONFIG,
EXPECTED_THEMED_ICON_PAIR_COUNT,
MCP_ALLOWED_ICON_MIME_TYPES,
MCP_SERVER_ID_PREFIX,
MCP_RECONNECT_INITIAL_DELAY,
MCP_RECONNECT_BACKOFF_MULTIPLIER,
MCP_RECONNECT_MAX_DELAY,
MCP_RECONNECT_ATTEMPT_TIMEOUT_MS
} from '$lib/constants';
import type {
MCPToolCall,
OpenAIToolDefinition,
ServerStatus,
ToolExecutionResult,
MCPClientConfig,
MCPConnection,
HealthCheckParams,
ServerCapabilities,
ClientCapabilities,
MCPCapabilitiesInfo,
MCPConnectionLog,
MCPPromptInfo,
GetPromptResult,
Tool,
HealthCheckState,
MCPServerSettingsEntry,
MCPServerConfig,
MCPResourceIcon,
MCPResourceAttachment,
MCPResourceContent
} from '$lib/types';
import type { ListChangedHandlers } from '@modelcontextprotocol/sdk/types.js';
import type { DatabaseMessageExtraMcpResource, McpServerOverride } from '$lib/types/database';
import type { SettingsConfigType } from '$lib/types/settings';
class MCPStore {
private _isInitializing = $state(false);
private _error = $state<string | null>(null);
private _toolCount = $state(0);
private _connectedServers = $state<string[]>([]);
private _healthChecks = $state<Record<string, HealthCheckState>>({});
private _proxyAvailable = $state(false);
private connections = new Map<string, MCPConnection>();
private toolsIndex = new Map<string, string>();
private serverConfigs = new Map<string, MCPServerConfig>(); // Store configs for reconnection
private reconnectingServers = new Set<string>(); // Guard against concurrent reconnections
private configSignature: string | null = null;
private initPromise: Promise<boolean> | null = null;
private activeFlowCount = 0;
constructor() {
if (browser) {
this.probeProxy();
}
}
/**
* Probes the CORS proxy endpoint to determine availability.
* The endpoint is only registered when llama-server runs with --webui-mcp-proxy.
*/
async probeProxy(): Promise<void> {
try {
const response = await fetch(`${base}${CORS_PROXY_ENDPOINT}`, { method: 'HEAD' });
this._proxyAvailable = response.status !== 404;
} catch {
this._proxyAvailable = false;
}
}
get isProxyAvailable(): boolean {
return this._proxyAvailable;
}
/**
* Generates a unique server ID from an optional ID string or index.
*/
#generateServerId(id: unknown, index: number): string {
if (typeof id === 'string' && id.trim()) {
return id.trim();
}
return `${MCP_SERVER_ID_PREFIX}-${index + 1}`;
}
/**
* Parses raw server settings from config into MCPServerSettingsEntry array.
*/
#parseServerSettings(rawServers: unknown): MCPServerSettingsEntry[] {
if (!rawServers) {
return [];
}
let parsed: unknown;
if (typeof rawServers === 'string') {
const trimmed = rawServers.trim();
if (!trimmed) {
return [];
}
try {
parsed = JSON.parse(trimmed);
} catch (error) {
console.warn('[MCP] Failed to parse mcpServers JSON:', error);
return [];
}
} else {
parsed = rawServers;
}
if (!Array.isArray(parsed)) {
return [];
}
return parsed.map((entry, index) => {
const url = typeof entry?.url === 'string' ? entry.url.trim() : '';
const headers = typeof entry?.headers === 'string' ? entry.headers.trim() : undefined;
return {
id: this.#generateServerId((entry as { id?: unknown })?.id, index),
enabled: Boolean((entry as { enabled?: unknown })?.enabled),
url,
name: (entry as { name?: string })?.name,
requestTimeoutSeconds: DEFAULT_MCP_CONFIG.requestTimeoutSeconds,
headers: headers || undefined,
useProxy: Boolean((entry as { useProxy?: unknown })?.useProxy)
} satisfies MCPServerSettingsEntry;
});
}
/**
* Builds server configuration from a settings entry.
*/
#buildServerConfig(
entry: MCPServerSettingsEntry,
connectionTimeoutMs = DEFAULT_MCP_CONFIG.connectionTimeoutMs
): MCPServerConfig | undefined {
if (!entry?.url) {
return undefined;
}
let headers: Record<string, string> | undefined;
if (entry.headers) {
try {
const parsed = JSON.parse(entry.headers);
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed))
headers = parsed as Record<string, string>;
} catch {
console.warn('[MCP] Failed to parse custom headers JSON:', entry.headers);
}
}
return {
url: entry.url,
transport: detectMcpTransportFromUrl(entry.url),
handshakeTimeoutMs: connectionTimeoutMs,
requestTimeoutMs: Math.round(entry.requestTimeoutSeconds * 1000),
headers,
useProxy: entry.useProxy
};
}
/**
* Checks if a server is enabled, considering per-chat overrides.
*/
#checkServerEnabled(
server: MCPServerSettingsEntry,
perChatOverrides?: McpServerOverride[]
): boolean {
if (!server.enabled) {
return false;
}
if (perChatOverrides) {
const override = perChatOverrides.find((o) => o.serverId === server.id);
return override?.enabled ?? false;
}
return false;
}
/**
* Builds MCP client configuration from settings.
*/
#buildMcpClientConfig(
cfg: SettingsConfigType,
perChatOverrides?: McpServerOverride[]
): MCPClientConfig | undefined {
const rawServers = this.#parseServerSettings(cfg.mcpServers);
if (!rawServers.length) {
return undefined;
}
const servers: Record<string, MCPServerConfig> = {};
for (const [index, entry] of rawServers.entries()) {
if (!this.#checkServerEnabled(entry, perChatOverrides)) continue;
const normalized = this.#buildServerConfig(entry);
if (normalized) servers[this.#generateServerId(entry.id, index)] = normalized;
}
if (Object.keys(servers).length === 0) {
return undefined;
}
return {
protocolVersion: DEFAULT_MCP_CONFIG.protocolVersion,
capabilities: DEFAULT_MCP_CONFIG.capabilities,
clientInfo: DEFAULT_MCP_CONFIG.clientInfo,
requestTimeoutMs: Math.round(DEFAULT_MCP_CONFIG.requestTimeoutSeconds * 1000),
servers
};
}
/**
* Builds capabilities info from server and client capabilities.
*/
#buildCapabilitiesInfo(
serverCaps?: ServerCapabilities,
clientCaps?: ClientCapabilities
): MCPCapabilitiesInfo {
return {
server: {
tools: serverCaps?.tools ? { listChanged: serverCaps.tools.listChanged } : undefined,
prompts: serverCaps?.prompts ? { listChanged: serverCaps.prompts.listChanged } : undefined,
resources: serverCaps?.resources
? {
subscribe: serverCaps.resources.subscribe,
listChanged: serverCaps.resources.listChanged
}
: undefined,
logging: !!serverCaps?.logging,
completions: !!serverCaps?.completions,
tasks: !!serverCaps?.tasks
},
client: {
roots: clientCaps?.roots ? { listChanged: clientCaps.roots.listChanged } : undefined,
sampling: !!clientCaps?.sampling,
elicitation: clientCaps?.elicitation
? { form: !!clientCaps.elicitation.form, url: !!clientCaps.elicitation.url }
: undefined,
tasks: !!clientCaps?.tasks
}
};
}
get isInitializing(): boolean {
return this._isInitializing;
}
get isInitialized(): boolean {
return this.connections.size > 0;
}
get error(): string | null {
return this._error;
}
get toolCount(): number {
return this._toolCount;
}
get connectedServerCount(): number {
return this._connectedServers.length;
}
get connectedServerNames(): string[] {
return this._connectedServers;
}
get isEnabled(): boolean {
const mcpConfig = this.#buildMcpClientConfig(config());
return (
mcpConfig !== null && mcpConfig !== undefined && Object.keys(mcpConfig.servers).length > 0
);
}
get availableTools(): string[] {
return Array.from(this.toolsIndex.keys());
}
private updateState(state: {
isInitializing?: boolean;
error?: string | null;
toolCount?: number;
connectedServers?: string[];
}): void {
if (state.isInitializing !== undefined) {
this._isInitializing = state.isInitializing;
}
if (state.error !== undefined) {
this._error = state.error;
}
if (state.toolCount !== undefined) {
this._toolCount = state.toolCount;
}
if (state.connectedServers !== undefined) {
this._connectedServers = state.connectedServers;
}
}
updateHealthCheck(serverId: string, state: HealthCheckState): void {
this._healthChecks = { ...this._healthChecks, [serverId]: state };
}
getHealthCheckState(serverId: string): HealthCheckState {
return this._healthChecks[serverId] ?? { status: HealthCheckStatus.IDLE };
}
hasHealthCheck(serverId: string): boolean {
return (
serverId in this._healthChecks &&
this._healthChecks[serverId].status !== HealthCheckStatus.IDLE
);
}
clearHealthCheck(serverId: string): void {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
const { [serverId]: _removed, ...rest } = this._healthChecks;
this._healthChecks = rest;
}
clearAllHealthChecks(): void {
this._healthChecks = {};
}
clearError(): void {
this._error = null;
}
getServers(): MCPServerSettingsEntry[] {
return parseMcpServerSettings(config().mcpServers);
}
/**
* Get all active MCP connections.
* @returns Map of server names to connections
*/
getConnections(): Map<string, MCPConnection> {
return this.connections;
}
getServerLabel(server: MCPServerSettingsEntry): string {
const healthState = this.getHealthCheckState(server.id);
if (healthState?.status === HealthCheckStatus.SUCCESS)
return (
healthState.serverInfo?.title || healthState.serverInfo?.name || server.name || server.url
);
return server.url;
}
getServerById(serverId: string): MCPServerSettingsEntry | undefined {
return this.getServers().find((s) => s.id === serverId);
}
/**
* Get display name for an MCP server by its ID.
* Falls back to the server ID if server is not found.
*/
getServerDisplayName(serverId: string): string {
const server = this.getServerById(serverId);
return server ? this.getServerLabel(server) : serverId;
}
/**
* Validates that an icon URI uses a safe scheme (https: or data:).
*/
#isValidIconUri(src: string): boolean {
try {
if (src.startsWith(UrlProtocol.DATA)) return true;
const url = new URL(src);
return url.protocol === UrlProtocol.HTTPS;
} catch {
return false;
}
}
/**
* Selects the best icon URL from an MCP icons array.
* Follows security guidelines from the MCP specification:
* - Only allows https: and data: URIs
* - Filters to supported MIME types
*
* Selection priority:
* 1. Icon matching the current color scheme (dark/light)
* 2. Universal icon (no theme specified); if exactly 2, assumes [0]=light, [1]=dark
* 3. First valid icon as last resort
*/
#getMcpIconUrl(icons: MCPResourceIcon[] | undefined, isDark = false): string | null {
if (!icons?.length) return null;
const validIcons = icons.filter((icon) => {
if (!icon.src || !this.#isValidIconUri(icon.src)) return false;
if (icon.mimeType && !MCP_ALLOWED_ICON_MIME_TYPES.has(icon.mimeType)) return false;
return true;
});
if (validIcons.length === 0) return null;
const preferredTheme = isDark ? ColorMode.DARK : ColorMode.LIGHT;
// 1. Prefer icon explicitly matching the current color scheme
const themedIcon = validIcons.find((icon) => icon.theme === preferredTheme);
if (themedIcon) return this.#proxyIconSrc(themedIcon.src);
// 2. Handle universal icons (no theme specified)
const universalIcons = validIcons.filter((icon) => !icon.theme);
if (universalIcons.length === EXPECTED_THEMED_ICON_PAIR_COUNT) {
// Heuristic: two theme-less icons → assume [0] = light, [1] = dark
return this.#proxyIconSrc(universalIcons[isDark ? 1 : 0].src);
}
if (universalIcons.length > 0) {
return this.#proxyIconSrc(universalIcons[0].src);
}
// 3. Last resort: use opposite-theme icon
return this.#proxyIconSrc(validIcons[0].src);
}
/**
* Route an icon src through the CORS proxy if it's an HTTPS URL.
* Data URIs are returned as-is.
*/
#proxyIconSrc(src: string): string {
if (src.startsWith('data:')) return src;
if (!this._proxyAvailable) return src;
return getProxiedUrlString(src);
}
/**
* Get icon URL for an MCP server by its ID.
* Prefers the server's own icons (from MCP spec) and falls back
* to Google's favicon service.
* Returns null if server is not found.
*/
getServerFavicon(serverId: string): string | null {
const server = this.getServerById(serverId);
if (!server) {
return null;
}
const isDark = mode.current === ColorMode.DARK;
const healthState = this.getHealthCheckState(serverId);
if (healthState.status === HealthCheckStatus.SUCCESS && healthState.serverInfo?.icons) {
const mcpIconUrl = this.#getMcpIconUrl(healthState.serverInfo.icons, isDark);
if (mcpIconUrl) {
return mcpIconUrl;
}
}
return getFaviconUrl(server.url, this._proxyAvailable);
}
isAnyServerLoading(): boolean {
return this.getServers().some((s) => {
const state = this.getHealthCheckState(s.id);
return (
state.status === HealthCheckStatus.IDLE || state.status === HealthCheckStatus.CONNECTING
);
});
}
getServersSorted(): MCPServerSettingsEntry[] {
const servers = this.getServers();
if (this.isAnyServerLoading()) {
return servers;
}
return [...servers].sort((a, b) =>
this.getServerLabel(a).localeCompare(this.getServerLabel(b))
);
}
addServer(
serverData: Omit<MCPServerSettingsEntry, 'id' | 'requestTimeoutSeconds'> & { id?: string }
): void {
const servers = this.getServers();
const newServer: MCPServerSettingsEntry = {
id: serverData.id || (uuid() ?? `server-${Date.now()}`),
enabled: serverData.enabled,
url: serverData.url.trim(),
name: serverData.name,
headers: serverData.headers?.trim() || undefined,
requestTimeoutSeconds: DEFAULT_MCP_CONFIG.requestTimeoutSeconds,
useProxy: serverData.useProxy
};
settingsStore.updateConfig('mcpServers', JSON.stringify([...servers, newServer]));
}
updateServer(id: string, updates: Partial<MCPServerSettingsEntry>): void {
const servers = this.getServers();
settingsStore.updateConfig(
'mcpServers',
JSON.stringify(
servers.map((server) => (server.id === id ? { ...server, ...updates } : server))
)
);
}
removeServer(id: string): void {
const servers = this.getServers();
settingsStore.updateConfig('mcpServers', JSON.stringify(servers.filter((s) => s.id !== id)));
this.clearHealthCheck(id);
}
hasAvailableServers(): boolean {
return parseMcpServerSettings(config().mcpServers).some((s) => s.enabled && s.url.trim());
}
hasEnabledServers(perChatOverrides?: McpServerOverride[]): boolean {
return Boolean(this.#buildMcpClientConfig(config(), perChatOverrides));
}
getEnabledServersForConversation(
perChatOverrides?: McpServerOverride[]
): MCPServerSettingsEntry[] {
if (!perChatOverrides?.length) {
return [];
}
return this.getServers().filter((server) => {
if (!server.enabled) {
return false;
}
const override = perChatOverrides.find((o) => o.serverId === server.id);
return override?.enabled ?? false;
});
}
async ensureInitialized(perChatOverrides?: McpServerOverride[]): Promise<boolean> {
if (!browser) {
return false;
}
const mcpConfig = this.#buildMcpClientConfig(config(), perChatOverrides);
const signature = mcpConfig ? JSON.stringify(mcpConfig) : null;
if (!signature) {
await this.shutdown();
return false;
}
if (this.isInitialized && this.configSignature === signature) {
return true;
}
if (this.initPromise && this.configSignature === signature) {
return this.initPromise;
}
if (this.connections.size > 0 || this.initPromise) await this.shutdown();
return this.initialize(signature, mcpConfig!);
}
private async initialize(signature: string, mcpConfig: MCPClientConfig): Promise<boolean> {
this.updateState({ isInitializing: true, error: null });
this.configSignature = signature;
const serverEntries = Object.entries(mcpConfig.servers);
if (serverEntries.length === 0) {
this.updateState({ isInitializing: false, toolCount: 0, connectedServers: [] });
return false;
}
this.initPromise = this.doInitialize(signature, mcpConfig, serverEntries);
return this.initPromise;
}
private async doInitialize(
signature: string,
mcpConfig: MCPClientConfig,
serverEntries: [string, MCPClientConfig['servers'][string]][]
): Promise<boolean> {
const clientInfo = mcpConfig.clientInfo ?? DEFAULT_MCP_CONFIG.clientInfo;
const capabilities = mcpConfig.capabilities ?? DEFAULT_MCP_CONFIG.capabilities;
const results = await Promise.allSettled(
serverEntries.map(async ([name, serverConfig]) => {
// Store config for reconnection
this.serverConfigs.set(name, serverConfig);
const listChangedHandlers = this.createListChangedHandlers(name);
const connection = await MCPService.connect(
name,
serverConfig,
clientInfo,
capabilities,
(phase) => {
// Handle WebSocket disconnection
if (phase === MCPConnectionPhase.DISCONNECTED) {
console.log(`[MCPStore][${name}] Connection lost, starting auto-reconnect`);
this.autoReconnect(name);
}
},
listChangedHandlers
);
return { name, connection };
})
);
if (this.configSignature !== signature) {
for (const result of results) {
if (result.status === 'fulfilled')
await MCPService.disconnect(result.value.connection).catch(console.warn);
}
return false;
}
for (const result of results) {
if (result.status === 'fulfilled') {
const { name, connection } = result.value;
this.connections.set(name, connection);
for (const tool of connection.tools) {
if (this.toolsIndex.has(tool.name))
console.warn(
`[MCPStore] Tool name conflict: "${tool.name}" exists in "${this.toolsIndex.get(tool.name)}" and "${name}". Using tool from "${name}".`
);
this.toolsIndex.set(tool.name, name);
}
} else {
console.error(`[MCPStore] Failed to connect:`, result.reason);
}
}
const successCount = this.connections.size;
if (successCount === 0 && serverEntries.length > 0) {
this.updateState({
isInitializing: false,
error: 'All MCP server connections failed',
toolCount: 0,
connectedServers: []
});
this.initPromise = null;
return false;
}
this.updateState({
isInitializing: false,
error: null,
toolCount: this.toolsIndex.size,
connectedServers: Array.from(this.connections.keys())
});
this.initPromise = null;
return true;
}
private createListChangedHandlers(serverName: string): ListChangedHandlers {
return {
tools: {
onChanged: (error: Error | null, tools: Tool[] | null) => {
if (error) {
console.warn(`[MCPStore][${serverName}] Tools list changed error:`, error);
return;
}
this.handleToolsListChanged(serverName, tools ?? []);
}
},
prompts: {
onChanged: (error: Error | null) => {
if (error) {
console.warn(`[MCPStore][${serverName}] Prompts list changed error:`, error);
return;
}
}
}
};
}
private handleToolsListChanged(serverName: string, tools: Tool[]): void {
const connection = this.connections.get(serverName);
if (!connection) {
return;
}
for (const [toolName, ownerServer] of this.toolsIndex.entries()) {
if (ownerServer === serverName) this.toolsIndex.delete(toolName);
}
connection.tools = tools;
for (const tool of tools) {
if (this.toolsIndex.has(tool.name))
console.warn(
`[MCPStore] Tool name conflict after list change: "${tool.name}" exists in "${this.toolsIndex.get(tool.name)}" and "${serverName}". Using tool from "${serverName}".`
);
this.toolsIndex.set(tool.name, serverName);
}
this.updateState({ toolCount: this.toolsIndex.size });
}
acquireConnection(): void {
this.activeFlowCount++;
}
/**
* Release a connection reference.
* By default, keeps connections alive for reuse (shutdownIfUnused=false).
* MCP spec encourages long-lived sessions to avoid reconnection overhead.
*/
async releaseConnection(shutdownIfUnused = false): Promise<void> {
this.activeFlowCount = Math.max(0, this.activeFlowCount - 1);
if (shutdownIfUnused && this.activeFlowCount === 0) {
await this.shutdown();
}
}
getActiveFlowCount(): number {
return this.activeFlowCount;
}
async shutdown(): Promise<void> {
if (this.initPromise) {
await this.initPromise.catch(() => {});
this.initPromise = null;
}
if (this.connections.size === 0) {
return;
}
await Promise.all(
Array.from(this.connections.values()).map((conn) =>
MCPService.disconnect(conn).catch((error) =>
console.warn(`[MCPStore] Error disconnecting ${conn.serverName}:`, error)
)
)
);
this.connections.clear();
this.toolsIndex.clear();
this.serverConfigs.clear();
this.configSignature = null;
this.updateState({ isInitializing: false, error: null, toolCount: 0, connectedServers: [] });
}
/**
* Immediately reconnect to a server by creating a fresh transport and session.
* Used when a session-expired error (HTTP 404) is detected during tool execution.
* Per MCP spec 2025-11-25: client MUST discard session ID and re-initialize.
*
* Unlike autoReconnect (which uses exponential backoff for connectivity issues),
* this performs a single immediate reconnection attempt since the server is known
* to be reachable (it responded with 404).
*/
private async reconnectServer(serverName: string): Promise<void> {
const serverConfig = this.serverConfigs.get(serverName);
if (!serverConfig) {
throw new Error(`[MCPStore] No config found for ${serverName}, cannot reconnect`);
}
// Disconnect stale connection (clears old transport + session ID)
const oldConnection = this.connections.get(serverName);
if (oldConnection) {
await MCPService.disconnect(oldConnection).catch(console.warn);
this.connections.delete(serverName);
}
console.log(`[MCPStore][${serverName}] Session expired, reconnecting with fresh session...`);
const listChangedHandlers = this.createListChangedHandlers(serverName);
const connection = await MCPService.connect(
serverName,
serverConfig,
DEFAULT_MCP_CONFIG.clientInfo,
DEFAULT_MCP_CONFIG.capabilities,
(phase) => {
if (phase === MCPConnectionPhase.DISCONNECTED) {
console.log(`[MCPStore][${serverName}] Connection lost, starting auto-reconnect`);
this.autoReconnect(serverName);
}
},
listChangedHandlers
);
// Replace connection and rebuild tool index for this server
this.connections.set(serverName, connection);
for (const tool of connection.tools) {
this.toolsIndex.set(tool.name, serverName);
}
console.log(`[MCPStore][${serverName}] Session recovered successfully`);
}
/**
* Auto-reconnect to a server with exponential backoff.
* Continues indefinitely until successful.
*
* Race-condition safety: when the phase callback fires a DISCONNECTED event
* while we are still inside this function (e.g., the server drops right after
* a successful connect()), a naive inner `autoReconnect()` call would be
* swallowed by the `reconnectingServers` guard, leaving the server
* permanently disconnected once the outer call exits. We solve this by
* deferring the new reconnection via the `needsReconnect` flag: the flag is
* set inside the phase callback and honoured in the `finally` block after
* the guard entry has been removed.
*/
private async autoReconnect(serverName: string): Promise<void> {
// Guard against concurrent reconnections
if (this.reconnectingServers.has(serverName)) {
console.log(`[MCPStore][${serverName}] Reconnection already in progress, skipping`);
return;
}
const serverConfig = this.serverConfigs.get(serverName);
if (!serverConfig) {
console.error(`[MCPStore] No config found for ${serverName}, cannot reconnect`);
return;
}
this.reconnectingServers.add(serverName);
let backoff = MCP_RECONNECT_INITIAL_DELAY;
// Flag set by the phase callback when a DISCONNECTED event fires while
// reconnectingServers still holds this server (see JSDoc above).
let needsReconnect = false;
try {
while (true) {
await new Promise((resolve) => setTimeout(resolve, backoff));
console.log(`[MCPStore][${serverName}] Auto-reconnecting...`);
try {
// Per-attempt timeout: reject if the server doesn't respond in time,
// then fall through to backoff logic as with any other failure.
const timeoutPromise = new Promise<never>((_, reject) =>
setTimeout(
() =>
reject(
new Error(
`Reconnect attempt timed out after ${MCP_RECONNECT_ATTEMPT_TIMEOUT_MS}ms`
)
),
MCP_RECONNECT_ATTEMPT_TIMEOUT_MS
)
);
needsReconnect = false;
const listChangedHandlers = this.createListChangedHandlers(serverName);
const connectPromise = MCPService.connect(
serverName,
serverConfig,
DEFAULT_MCP_CONFIG.clientInfo,
DEFAULT_MCP_CONFIG.capabilities,
(phase) => {
if (phase === MCPConnectionPhase.DISCONNECTED) {
if (this.reconnectingServers.has(serverName)) {
// Reconnect loop is active; defer to after it exits.
needsReconnect = true;
} else {
console.log(
`[MCPStore][${serverName}] Connection lost, restarting auto-reconnect`
);
this.autoReconnect(serverName);
}
}
},
listChangedHandlers
);
const connection = await Promise.race([connectPromise, timeoutPromise]);
// Replace old connection with new one
this.connections.set(serverName, connection);
// Rebuild tool index for this server
for (const tool of connection.tools) {
this.toolsIndex.set(tool.name, serverName);
}
console.log(`[MCPStore][${serverName}] Reconnected successfully`);
break;
} catch (error) {
console.warn(`[MCPStore][${serverName}] Reconnection failed:`, error);
backoff = Math.min(backoff * MCP_RECONNECT_BACKOFF_MULTIPLIER, MCP_RECONNECT_MAX_DELAY);
}
}
} finally {
this.reconnectingServers.delete(serverName);
// If the phase callback signalled a disconnect while this function held
// the guard, kick off a fresh reconnect now that the guard is released.
if (needsReconnect) {
console.log(
`[MCPStore][${serverName}] Deferred disconnect detected, restarting auto-reconnect`
);
this.autoReconnect(serverName);
}
}
}
getToolDefinitionsForLLM(): OpenAIToolDefinition[] {
const tools: OpenAIToolDefinition[] = [];
for (const connection of this.connections.values()) {
for (const tool of connection.tools) {
const rawSchema = (tool.inputSchema as Record<string, unknown>) ?? {
type: JsonSchemaType.OBJECT,
properties: {},
required: []
};
tools.push({
type: ToolCallType.FUNCTION as const,
function: {
name: tool.name,
description: tool.description,
parameters: this.normalizeSchemaProperties(rawSchema)
}
});
}
}
return tools;
}
private normalizeSchemaProperties(schema: Record<string, unknown>): Record<string, unknown> {
if (!schema || typeof schema !== 'object') {
return schema;
}
const normalized = { ...schema };
if (normalized.properties && typeof normalized.properties === 'object') {
const props = normalized.properties as Record<string, Record<string, unknown>>;
const normalizedProps: Record<string, Record<string, unknown>> = {};
for (const [key, prop] of Object.entries(props)) {
if (!prop || typeof prop !== 'object') {
normalizedProps[key] = prop;
continue;
}
const normalizedProp = { ...prop };
if (!normalizedProp.type && normalizedProp.default !== undefined) {
const defaultVal = normalizedProp.default;
if (typeof defaultVal === 'string') normalizedProp.type = 'string';
else if (typeof defaultVal === 'number')
normalizedProp.type = Number.isInteger(defaultVal) ? 'integer' : 'number';
else if (typeof defaultVal === 'boolean') normalizedProp.type = 'boolean';
else if (Array.isArray(defaultVal)) normalizedProp.type = 'array';
else if (typeof defaultVal === 'object' && defaultVal !== null)
normalizedProp.type = 'object';
}
if (normalizedProp.properties)
Object.assign(
normalizedProp,
this.normalizeSchemaProperties(normalizedProp as Record<string, unknown>)
);
if (normalizedProp.items && typeof normalizedProp.items === 'object')
normalizedProp.items = this.normalizeSchemaProperties(
normalizedProp.items as Record<string, unknown>
);
normalizedProps[key] = normalizedProp;
}
normalized.properties = normalizedProps;
}
return normalized;
}
getToolNames(): string[] {
return Array.from(this.toolsIndex.keys());
}
hasTool(toolName: string): boolean {
return this.toolsIndex.has(toolName);
}
getToolServer(toolName: string): string | undefined {
return this.toolsIndex.get(toolName);
}
hasPromptsSupport(): boolean {
for (const connection of this.connections.values()) {
if (connection.serverCapabilities?.prompts) {
return true;
}
}
return false;
}
/**
* Check if any enabled server with successful health check supports prompts.
* Uses health check state since servers may not have active connections until
* the user actually sends a message or uses prompts.
* @param perChatOverrides - Per-chat server overrides to filter by enabled servers.
* If provided (even empty array), only checks enabled servers.
* If undefined, checks all servers with successful health checks.
*/
hasPromptsCapability(perChatOverrides?: McpServerOverride[]): boolean {
// If perChatOverrides is provided (even empty array), filter by enabled servers
if (perChatOverrides !== undefined) {
const enabledServerIds = new Set(
perChatOverrides.filter((o) => o.enabled).map((o) => o.serverId)
);
// No enabled servers = no capability
if (enabledServerIds.size === 0) {
return false;
}
// Check health check states for enabled servers with prompts capability
for (const [serverId, state] of Object.entries(this._healthChecks)) {
if (!enabledServerIds.has(serverId)) continue;
if (
state.status === HealthCheckStatus.SUCCESS &&
state.capabilities?.server?.prompts !== undefined
) {
return true;
}
}
// Also check active connections as fallback
for (const [serverName, connection] of this.connections) {
if (!enabledServerIds.has(serverName)) continue;
if (connection.serverCapabilities?.prompts) {
return true;
}
}
return false;
}
// No overrides provided - check all servers (global mode)
for (const state of Object.values(this._healthChecks)) {
if (
state.status === HealthCheckStatus.SUCCESS &&
state.capabilities?.server?.prompts !== undefined
) {
return true;
}
}
for (const connection of this.connections.values()) {
if (connection.serverCapabilities?.prompts) {
return true;
}
}
return false;
}
async getAllPrompts(): Promise<MCPPromptInfo[]> {
const results: MCPPromptInfo[] = [];
for (const [serverName, connection] of this.connections) {
if (!connection.serverCapabilities?.prompts) continue;
const prompts = await MCPService.listPrompts(connection);
for (const prompt of prompts) {
results.push({
name: prompt.name,
description: prompt.description,
title: prompt.title,
serverName,
arguments: prompt.arguments?.map((arg) => ({
name: arg.name,
description: arg.description,
required: arg.required
}))
});
}
}
return results;
}
async getPrompt(
serverName: string,
promptName: string,
args?: Record<string, string>
): Promise<GetPromptResult> {
const connection = this.connections.get(serverName);
if (!connection) throw new Error(`Server "${serverName}" not found for prompt "${promptName}"`);
return MCPService.getPrompt(connection, promptName, args);
}
async executeTool(toolCall: MCPToolCall, signal?: AbortSignal): Promise<ToolExecutionResult> {
const toolName = toolCall.function.name;
const serverName = this.toolsIndex.get(toolName);
if (!serverName) throw new Error(`Unknown tool: ${toolName}`);
const connection = this.connections.get(serverName);
if (!connection) throw new Error(`Server "${serverName}" is not connected`);
const args = this.parseToolArguments(toolCall.function.arguments);
try {
return await MCPService.callTool(connection, { name: toolName, arguments: args }, signal);
} catch (error) {
// Session expired (server restarted) - reconnect and retry once
if (MCPService.isSessionExpiredError(error)) {
await this.reconnectServer(serverName);
const newConnection = this.connections.get(serverName);
if (!newConnection) throw new Error(`Failed to reconnect to "${serverName}"`);
return MCPService.callTool(newConnection, { name: toolName, arguments: args }, signal);
}
throw error;
}
}
async executeToolByName(
toolName: string,
args: Record<string, unknown>,
signal?: AbortSignal
): Promise<ToolExecutionResult> {
const serverName = this.toolsIndex.get(toolName);
if (!serverName) throw new Error(`Unknown tool: ${toolName}`);
const connection = this.connections.get(serverName);
if (!connection) throw new Error(`Server "${serverName}" is not connected`);
try {
return await MCPService.callTool(connection, { name: toolName, arguments: args }, signal);
} catch (error) {
if (MCPService.isSessionExpiredError(error)) {
await this.reconnectServer(serverName);
const newConnection = this.connections.get(serverName);
if (!newConnection) throw new Error(`Failed to reconnect to "${serverName}"`);
return MCPService.callTool(newConnection, { name: toolName, arguments: args }, signal);
}
throw error;
}
}
private parseToolArguments(args: string | Record<string, unknown>): Record<string, unknown> {
if (typeof args === 'string') {
const trimmed = args.trim();
if (trimmed === '') {
return {};
}
try {
const parsed = JSON.parse(trimmed);
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
throw new Error(
`Tool arguments must be an object, got ${Array.isArray(parsed) ? 'array' : typeof parsed}`
);
return parsed as Record<string, unknown>;
} catch (error) {
throw new Error(`Failed to parse tool arguments as JSON: ${(error as Error).message}`);
}
}
if (typeof args === 'object' && args !== null && !Array.isArray(args)) {
return args;
}
throw new Error(`Invalid tool arguments type: ${typeof args}`);
}
async getPromptCompletions(
serverName: string,
promptName: string,
argumentName: string,
argumentValue: string
): Promise<{ values: string[]; total?: number; hasMore?: boolean } | null> {
const connection = this.connections.get(serverName);
if (!connection) {
console.warn(`[MCPStore] Server "${serverName}" is not connected`);
return null;
}
if (!connection.serverCapabilities?.completions) {
return null;
}
return MCPService.complete(
connection,
{ type: MCPRefType.PROMPT, name: promptName },
{ name: argumentName, value: argumentValue }
);
}
/**
* Get completions for a resource template argument.
* Uses the MCP Completion API with ref/resource.
*/
async getResourceCompletions(
serverName: string,
uriTemplate: string,
argumentName: string,
argumentValue: string
): Promise<{ values: string[]; total?: number; hasMore?: boolean } | null> {
const connection = this.connections.get(serverName);
if (!connection) {
console.warn(`[MCPStore] Server "${serverName}" is not connected`);
return null;
}
if (!connection.serverCapabilities?.completions) {
return null;
}
return MCPService.complete(
connection,
{ type: MCPRefType.RESOURCE, uri: uriTemplate },
{ name: argumentName, value: argumentValue }
);
}
/**
* Read a resource by an arbitrary URI (e.g., one expanded from a template).
* Unlike readResource(), this does not require the URI to be in the resources list.
*/
async readResourceByUri(serverName: string, uri: string): Promise<MCPResourceContent[] | null> {
const connection = this.connections.get(serverName);
if (!connection) {
console.error(`[MCPStore] No connection found for server: ${serverName}`);
return null;
}
try {
const result = await MCPService.readResource(connection, uri);
return result.contents;
} catch (error) {
console.error(`[MCPStore] Failed to read resource ${uri}:`, error);
return null;
}
}
private parseHeaders(headersJson?: string): Record<string, string> | undefined {
if (!headersJson?.trim()) {
return undefined;
}
try {
const parsed = JSON.parse(headersJson);
if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed))
return parsed as Record<string, string>;
} catch {
console.warn('[MCPStore] Failed to parse custom headers JSON:', headersJson);
}
return undefined;
}
async runHealthChecksForServers(
servers: {
id: string;
enabled: boolean;
url: string;
requestTimeoutSeconds: number;
headers?: string;
}[],
skipIfChecked = true,
promoteToActive = false
): Promise<void> {
const serversToCheck = skipIfChecked
? servers.filter((s) => !this.hasHealthCheck(s.id) && s.url.trim())
: servers.filter((s) => s.url.trim());
if (serversToCheck.length === 0) {
return;
}
const BATCH_SIZE = 5;
for (let i = 0; i < serversToCheck.length; i += BATCH_SIZE) {
const batch = serversToCheck.slice(i, i + BATCH_SIZE);
await Promise.allSettled(batch.map((server) => this.runHealthCheck(server, promoteToActive)));
}
}
/**
* Check if a server already has an active connection that can be reused.
* Returns the existing connection if available.
*/
getExistingConnection(serverId: string): MCPConnection | undefined {
return this.connections.get(serverId);
}
/**
* Run a health check for a server.
* If the server already has an active connection, reuses it instead of creating a new one.
* If promoteToActive is true and server is enabled, the connection will be kept
* and promoted to an active connection instead of being disconnected.
*/
async runHealthCheck(server: HealthCheckParams, promoteToActive = false): Promise<void> {
// Check if we already have an active connection for this server
const existingConnection = this.connections.get(server.id);
if (existingConnection) {
// Reuse existing connection - just refresh tools list
try {
const tools = await MCPService.listTools(existingConnection);
const capabilities = this.#buildCapabilitiesInfo(
existingConnection.serverCapabilities,
existingConnection.clientCapabilities
);
this.updateHealthCheck(server.id, {
status: HealthCheckStatus.SUCCESS,
tools: tools.map((tool) => ({
name: tool.name,
description: tool.description,
title: tool.title
})),
serverInfo: existingConnection.serverInfo,
capabilities,
transportType: existingConnection.transportType,
protocolVersion: existingConnection.protocolVersion,
instructions: existingConnection.instructions,
connectionTimeMs: existingConnection.connectionTimeMs,
logs: []
});
return;
} catch (error) {
console.warn(
`[MCPStore] Failed to reuse connection for ${server.id}, creating new one:`,
error
);
// Connection may be stale, remove it and create new one
this.connections.delete(server.id);
}
}
const trimmedUrl = server.url.trim();
const logs: MCPConnectionLog[] = [];
let currentPhase: MCPConnectionPhase = MCPConnectionPhase.IDLE;
if (!trimmedUrl) {
this.updateHealthCheck(server.id, {
status: HealthCheckStatus.ERROR,
message: 'Please enter a server URL first.',
logs: []
});
return;
}
this.updateHealthCheck(server.id, {
status: HealthCheckStatus.CONNECTING,
phase: MCPConnectionPhase.TRANSPORT_CREATING,
logs: []
});
const timeoutMs = Math.round(server.requestTimeoutSeconds * 1000);
const headers = this.parseHeaders(server.headers);
try {
const serverConfig: MCPServerConfig = {
url: trimmedUrl,
transport: detectMcpTransportFromUrl(trimmedUrl),
handshakeTimeoutMs: DEFAULT_MCP_CONFIG.connectionTimeoutMs,
requestTimeoutMs: timeoutMs,
headers,
useProxy: server.useProxy
};
// Store config for reconnection
this.serverConfigs.set(server.id, serverConfig);
const connection = await MCPService.connect(
server.id,
serverConfig,
DEFAULT_MCP_CONFIG.clientInfo,
DEFAULT_MCP_CONFIG.capabilities,
(phase, log) => {
currentPhase = phase;
logs.push(log);
this.updateHealthCheck(server.id, {
status: HealthCheckStatus.CONNECTING,
phase,
logs: [...logs]
});
// Handle WebSocket disconnection
if (phase === MCPConnectionPhase.DISCONNECTED && promoteToActive) {
console.log(
`[MCPStore][${server.id}] Connection lost during health check, starting auto-reconnect`
);
this.autoReconnect(server.id);
}
}
);
const tools = connection.tools.map((tool) => ({
name: tool.name,
description: tool.description,
title: tool.title
}));
const capabilities = this.#buildCapabilitiesInfo(
connection.serverCapabilities,
connection.clientCapabilities
);
this.updateHealthCheck(server.id, {
status: HealthCheckStatus.SUCCESS,
tools,
serverInfo: connection.serverInfo,
capabilities,
transportType: connection.transportType,
protocolVersion: connection.protocolVersion,
instructions: connection.instructions,
connectionTimeMs: connection.connectionTimeMs,
logs
});
// Promote to active connection or disconnect
if (promoteToActive && server.enabled) {
this.promoteHealthCheckToConnection(server.id, connection);
} else {
await MCPService.disconnect(connection);
}
} catch (error) {
const message = error instanceof Error ? error.message : 'Unknown error occurred';
logs.push({
timestamp: new Date(),
phase: MCPConnectionPhase.ERROR,
message: `Connection failed: ${message}`,
level: MCPLogLevel.ERROR
});
this.updateHealthCheck(server.id, {
status: HealthCheckStatus.ERROR,
message,
phase: currentPhase,
logs
});
}
}
/**
* Promote a health check connection to an active connection.
* This avoids the need to reconnect when the server is needed for agentic flows.
*/
private promoteHealthCheckToConnection(serverId: string, connection: MCPConnection): void {
// Register tools from the connection
for (const tool of connection.tools) {
if (this.toolsIndex.has(tool.name)) {
console.warn(
`[MCPStore] Tool name conflict during promotion: "${tool.name}" exists in "${this.toolsIndex.get(tool.name)}" and "${serverId}". Using tool from "${serverId}".`
);
}
this.toolsIndex.set(tool.name, serverId);
}
// Add to active connections
this.connections.set(serverId, connection);
// Update state
this.updateState({
toolCount: this.toolsIndex.size,
connectedServers: Array.from(this.connections.keys())
});
}
getServersStatus(): ServerStatus[] {
const statuses: ServerStatus[] = [];
for (const [name, connection] of this.connections) {
statuses.push({
name,
isConnected: true,
toolCount: connection.tools.length,
error: undefined
});
}
return statuses;
}
/**
* Get aggregated server instructions from all connected servers.
* Returns an array of { serverName, serverTitle, instructions } objects.
*/
getServerInstructions(): Array<{
serverName: string;
serverTitle?: string;
instructions: string;
}> {
const results: Array<{ serverName: string; serverTitle?: string; instructions: string }> = [];
for (const [serverName, connection] of this.connections) {
if (connection.instructions) {
results.push({
serverName,
serverTitle: connection.serverInfo?.title || connection.serverInfo?.name,
instructions: connection.instructions
});
}
}
return results;
}
/**
* Get server instructions from health check results (for display before active connection).
* Useful for showing instructions in settings UI.
*/
getHealthCheckInstructions(): Array<{
serverId: string;
serverTitle?: string;
instructions: string;
}> {
const results: Array<{ serverId: string; serverTitle?: string; instructions: string }> = [];
for (const [serverId, state] of Object.entries(this._healthChecks)) {
if (state.status === HealthCheckStatus.SUCCESS && state.instructions) {
results.push({
serverId,
serverTitle: state.serverInfo?.title || state.serverInfo?.name,
instructions: state.instructions
});
}
}
return results;
}
/**
* Check if any connected server has instructions.
*/
hasServerInstructions(): boolean {
for (const connection of this.connections.values()) {
if (connection.instructions) {
return true;
}
}
return false;
}
/**
*
*
* Resources Operations
*
*
*/
/**
* Check if any enabled server with successful health check supports resources.
* Uses health check state since servers may not have active connections until
* the user actually sends a message or uses prompts.
* @param perChatOverrides - Per-chat server overrides to filter by enabled servers.
* If provided (even empty array), only checks enabled servers.
* If undefined, checks all servers with successful health checks.
*/
hasResourcesCapability(perChatOverrides?: McpServerOverride[]): boolean {
// If perChatOverrides is provided (even empty array), filter by enabled servers
if (perChatOverrides !== undefined) {
const enabledServerIds = new Set(
perChatOverrides.filter((o) => o.enabled).map((o) => o.serverId)
);
// No enabled servers = no capability
if (enabledServerIds.size === 0) {
return false;
}
// Check health check states for enabled servers with resources capability
for (const [serverId, state] of Object.entries(this._healthChecks)) {
if (!enabledServerIds.has(serverId)) continue;
if (
state.status === HealthCheckStatus.SUCCESS &&
state.capabilities?.server?.resources !== undefined
) {
return true;
}
}
// Also check active connections as fallback
for (const [serverName, connection] of this.connections) {
if (!enabledServerIds.has(serverName)) continue;
if (MCPService.supportsResources(connection)) {
return true;
}
}
return false;
}
// No overrides provided - check all servers (global mode)
for (const state of Object.values(this._healthChecks)) {
if (
state.status === HealthCheckStatus.SUCCESS &&
state.capabilities?.server?.resources !== undefined
) {
return true;
}
}
for (const connection of this.connections.values()) {
if (MCPService.supportsResources(connection)) {
return true;
}
}
return false;
}
/**
* Get list of servers that support resources.
* Checks active connections first, then health check state as fallback.
*/
getServersWithResources(): string[] {
const servers: string[] = [];
// Check active connections
for (const [name, connection] of this.connections) {
if (MCPService.supportsResources(connection) && !servers.includes(name)) {
servers.push(name);
}
}
// Also check health check states for servers not yet connected
for (const [serverId, state] of Object.entries(this._healthChecks)) {
if (
!servers.includes(serverId) &&
state.status === HealthCheckStatus.SUCCESS &&
state.capabilities?.server?.resources !== undefined
) {
servers.push(serverId);
}
}
return servers;
}
/**
* Fetch resources from all connected servers that support them.
* Updates mcpResourceStore with the results.
* @param forceRefresh - If true, bypass cache and fetch fresh data
*/
async fetchAllResources(forceRefresh: boolean = false): Promise<void> {
const serversWithResources = this.getServersWithResources();
if (serversWithResources.length === 0) {
return;
}
// Check if we have cached resources and they're recent (unless force refresh)
if (!forceRefresh) {
const allServersCached = serversWithResources.every((serverName) => {
const serverRes = mcpResourceStore.getServerResources(serverName);
if (!serverRes || !serverRes.lastFetched) {
return false;
}
// Cache is valid for 5 minutes
const age = Date.now() - serverRes.lastFetched.getTime();
return age < DEFAULT_CACHE_TTL_MS;
});
if (allServersCached) {
console.log('[MCPStore] Using cached resources');
return;
}
}
mcpResourceStore.setLoading(true);
try {
await Promise.all(
serversWithResources.map((serverName) => this.fetchServerResources(serverName))
);
} finally {
mcpResourceStore.setLoading(false);
}
}
/**
* Fetch resources from a specific server.
* Updates mcpResourceStore with the results.
*/
async fetchServerResources(serverName: string): Promise<void> {
const connection = this.connections.get(serverName);
if (!connection) {
console.warn(`[MCPStore] No connection found for server: ${serverName}`);
return;
}
if (!MCPService.supportsResources(connection)) {
return;
}
mcpResourceStore.setServerLoading(serverName, true);
try {
const [resources, templates] = await Promise.all([
MCPService.listAllResources(connection),
MCPService.listAllResourceTemplates(connection)
]);
mcpResourceStore.setServerResources(serverName, resources, templates);
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
mcpResourceStore.setServerError(serverName, message);
console.error(`[MCPStore][${serverName}] Failed to fetch resources:`, error);
}
}
/**
* Read resource content from a server.
* Caches the result in mcpResourceStore.
*/
async readResource(uri: string): Promise<MCPResourceContent[] | null> {
// Check cache first
const cached = mcpResourceStore.getCachedContent(uri);
if (cached) {
return cached.content;
}
// Find which server has this resource
const serverName = mcpResourceStore.findServerForUri(uri);
if (!serverName) {
console.error(`[MCPStore] No server found for resource URI: ${uri}`);
return null;
}
const connection = this.connections.get(serverName);
if (!connection) {
console.error(`[MCPStore] No connection found for server: ${serverName}`);
return null;
}
try {
const result = await MCPService.readResource(connection, uri);
const resourceInfo = mcpResourceStore.findResourceByUri(uri);
if (resourceInfo) {
mcpResourceStore.cacheResourceContent(resourceInfo, result.contents);
}
return result.contents;
} catch (error) {
console.error(`[MCPStore] Failed to read resource ${uri}:`, error);
return null;
}
}
/**
* Subscribe to resource updates.
*/
async subscribeToResource(uri: string): Promise<boolean> {
const serverName = mcpResourceStore.findServerForUri(uri);
if (!serverName) {
console.error(`[MCPStore] No server found for resource URI: ${uri}`);
return false;
}
const connection = this.connections.get(serverName);
if (!connection) {
console.error(`[MCPStore] No connection found for server: ${serverName}`);
return false;
}
if (!MCPService.supportsResourceSubscriptions(connection)) {
return false;
}
try {
await MCPService.subscribeResource(connection, uri);
mcpResourceStore.addSubscription(uri, serverName);
return true;
} catch (error) {
console.error(`[MCPStore] Failed to subscribe to resource ${uri}:`, error);
return false;
}
}
/**
* Unsubscribe from resource updates.
*/
async unsubscribeFromResource(uri: string): Promise<boolean> {
const serverName = mcpResourceStore.findServerForUri(uri);
if (!serverName) {
console.error(`[MCPStore] No server found for resource URI: ${uri}`);
return false;
}
const connection = this.connections.get(serverName);
if (!connection) {
console.error(`[MCPStore] No connection found for server: ${serverName}`);
return false;
}
try {
await MCPService.unsubscribeResource(connection, uri);
mcpResourceStore.removeSubscription(uri);
return true;
} catch (error) {
console.error(`[MCPStore] Failed to unsubscribe from resource ${uri}:`, error);
return false;
}
}
/**
* Add a resource as attachment to chat context.
* Automatically fetches content if not cached.
*/
async attachResource(uri: string): Promise<MCPResourceAttachment | null> {
const resourceInfo = mcpResourceStore.findResourceByUri(uri);
if (!resourceInfo) {
console.error(`[MCPStore] Resource not found: ${uri}`);
return null;
}
// Check if already attached
if (mcpResourceStore.isAttached(uri)) {
return null;
}
// Add attachment (initially loading)
const attachment = mcpResourceStore.addAttachment(resourceInfo);
// Fetch content
try {
const content = await this.readResource(uri);
if (content) {
mcpResourceStore.updateAttachmentContent(attachment.id, content);
} else {
mcpResourceStore.updateAttachmentError(attachment.id, 'Failed to read resource');
}
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
mcpResourceStore.updateAttachmentError(attachment.id, message);
}
return mcpResourceStore.getAttachment(attachment.id) ?? null;
}
/**
* Remove a resource attachment from chat context.
*/
removeResourceAttachment(attachmentId: string): void {
mcpResourceStore.removeAttachment(attachmentId);
}
/**
* Clear all resource attachments.
*/
clearResourceAttachments(): void {
mcpResourceStore.clearAttachments();
}
/**
* Get formatted resource context for chat.
*/
getResourceContextForChat(): string {
return mcpResourceStore.formatAttachmentsForContext();
}
/**
* Convert current resource attachments to DatabaseMessageExtra[] and clear them.
* Called during message send to persist resources with the user message.
*/
consumeResourceAttachmentsAsExtras(): DatabaseMessageExtraMcpResource[] {
const extras = mcpResourceStore.toMessageExtras();
if (extras.length > 0) {
mcpResourceStore.clearAttachments();
}
return extras;
}
}
export const mcpStore = new MCPStore();
export const mcpIsInitializing = () => mcpStore.isInitializing;
export const mcpIsInitialized = () => mcpStore.isInitialized;
export const mcpError = () => mcpStore.error;
export const mcpIsEnabled = () => mcpStore.isEnabled;
export const mcpIsProxyAvailable = () => mcpStore.isProxyAvailable;
export const mcpAvailableTools = () => mcpStore.availableTools;
export const mcpConnectedServerCount = () => mcpStore.connectedServerCount;
export const mcpConnectedServerNames = () => mcpStore.connectedServerNames;
export const mcpToolCount = () => mcpStore.toolCount;
export const mcpServerInstructions = () => mcpStore.getServerInstructions();
export const mcpHasServerInstructions = () => mcpStore.hasServerInstructions();
// Resources exports
export const mcpHasResourcesCapability = () => mcpStore.hasResourcesCapability();
export const mcpServersWithResources = () => mcpStore.getServersWithResources();
export const mcpResourceContext = () => mcpStore.getResourceContextForChat();
|