imcp 0.0.13 → 0.0.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (157) hide show
  1. package/dist/core/ConfigurationProvider.d.ts +1 -0
  2. package/dist/core/ConfigurationProvider.js +15 -0
  3. package/dist/core/InstallationService.js +2 -7
  4. package/dist/core/MCPManager.d.ts +11 -2
  5. package/dist/core/MCPManager.js +24 -1
  6. package/dist/core/RequirementService.js +2 -8
  7. package/dist/core/installers/clients/BaseClientInstaller.d.ts +51 -0
  8. package/dist/core/installers/clients/BaseClientInstaller.js +160 -0
  9. package/dist/core/installers/clients/ClientInstaller.d.ts +16 -8
  10. package/dist/core/installers/clients/ClientInstaller.js +77 -504
  11. package/dist/core/installers/clients/ClientInstallerFactory.d.ts +19 -0
  12. package/dist/core/installers/clients/ClientInstallerFactory.js +41 -0
  13. package/dist/core/installers/clients/ClineInstaller.d.ts +18 -0
  14. package/dist/core/installers/clients/ClineInstaller.js +124 -0
  15. package/dist/core/installers/clients/GithubCopilotInstaller.d.ts +34 -0
  16. package/dist/core/installers/clients/GithubCopilotInstaller.js +162 -0
  17. package/dist/core/installers/clients/MSRooCodeInstaller.d.ts +15 -0
  18. package/dist/core/installers/clients/MSRooCodeInstaller.js +122 -0
  19. package/dist/core/installers/requirements/BaseInstaller.d.ts +11 -34
  20. package/dist/core/installers/requirements/BaseInstaller.js +5 -116
  21. package/dist/core/installers/requirements/CommandInstaller.d.ts +6 -1
  22. package/dist/core/installers/requirements/CommandInstaller.js +7 -0
  23. package/dist/core/installers/requirements/GeneralInstaller.d.ts +6 -1
  24. package/dist/core/installers/requirements/GeneralInstaller.js +9 -4
  25. package/dist/core/installers/requirements/NpmInstaller.d.ts +46 -7
  26. package/dist/core/installers/requirements/NpmInstaller.js +150 -58
  27. package/dist/core/installers/requirements/PipInstaller.d.ts +9 -0
  28. package/dist/core/installers/requirements/PipInstaller.js +66 -28
  29. package/dist/core/onboard/FeedOnboardService.d.ts +72 -0
  30. package/dist/core/onboard/FeedOnboardService.js +312 -0
  31. package/dist/core/onboard/OnboardProcessor.d.ts +79 -0
  32. package/dist/core/onboard/OnboardProcessor.js +290 -0
  33. package/dist/core/onboard/OnboardStatus.d.ts +49 -0
  34. package/dist/core/onboard/OnboardStatus.js +10 -0
  35. package/dist/core/onboard/OnboardStatusManager.d.ts +57 -0
  36. package/dist/core/onboard/OnboardStatusManager.js +176 -0
  37. package/dist/core/types.d.ts +6 -6
  38. package/dist/core/validators/FeedValidator.d.ts +20 -0
  39. package/dist/core/validators/FeedValidator.js +80 -0
  40. package/dist/core/validators/IServerValidator.d.ts +19 -0
  41. package/dist/core/validators/IServerValidator.js +2 -0
  42. package/dist/core/validators/SSEServerValidator.d.ts +15 -0
  43. package/dist/core/validators/SSEServerValidator.js +39 -0
  44. package/dist/core/validators/ServerValidatorFactory.d.ts +24 -0
  45. package/dist/core/validators/ServerValidatorFactory.js +45 -0
  46. package/dist/core/validators/StdioServerValidator.d.ts +46 -0
  47. package/dist/core/validators/StdioServerValidator.js +229 -0
  48. package/dist/services/InstallRequestValidator.d.ts +1 -1
  49. package/dist/services/ServerService.d.ts +9 -6
  50. package/dist/services/ServerService.js +18 -7
  51. package/dist/utils/adoUtils.d.ts +29 -0
  52. package/dist/utils/adoUtils.js +252 -0
  53. package/dist/utils/clientUtils.d.ts +0 -7
  54. package/dist/utils/clientUtils.js +0 -42
  55. package/dist/utils/githubUtils.d.ts +10 -0
  56. package/dist/utils/githubUtils.js +22 -0
  57. package/dist/utils/macroExpressionUtils.d.ts +38 -0
  58. package/dist/utils/macroExpressionUtils.js +116 -0
  59. package/dist/utils/osUtils.d.ts +4 -20
  60. package/dist/utils/osUtils.js +78 -23
  61. package/dist/web/contract/serverContract.d.ts +66 -0
  62. package/dist/web/contract/serverContract.js +2 -0
  63. package/dist/web/public/css/notifications.css +48 -17
  64. package/dist/web/public/css/onboard.css +107 -0
  65. package/dist/web/public/index.html +90 -18
  66. package/dist/web/public/js/api.js +3 -6
  67. package/dist/web/public/js/flights/flights.js +127 -0
  68. package/dist/web/public/js/modal/index.js +58 -0
  69. package/dist/web/public/js/modal/installHandler.js +227 -0
  70. package/dist/web/public/js/modal/installModal.js +163 -0
  71. package/dist/web/public/js/modal/installation.js +281 -0
  72. package/dist/web/public/js/modal/loadingModal.js +52 -0
  73. package/dist/web/public/js/modal/loadingUI.js +74 -0
  74. package/dist/web/public/js/modal/messageQueue.js +112 -0
  75. package/dist/web/public/js/modal/modalSetup.js +513 -0
  76. package/dist/web/public/js/modal/modalUI.js +214 -0
  77. package/dist/web/public/js/modal/modalUtils.js +49 -0
  78. package/dist/web/public/js/modal/version.js +20 -0
  79. package/dist/web/public/js/modal/versionUtils.js +20 -0
  80. package/dist/web/public/js/modal.js +25 -1041
  81. package/dist/web/public/js/notifications.js +66 -27
  82. package/dist/web/public/js/onboard/ONBOARDING_PAGE_DESIGN.md +338 -0
  83. package/dist/web/public/js/onboard/formProcessor.js +864 -0
  84. package/dist/web/public/js/onboard/index.js +374 -0
  85. package/dist/web/public/js/onboard/publishHandler.js +132 -0
  86. package/dist/web/public/js/onboard/state.js +76 -0
  87. package/dist/web/public/js/onboard/templates.js +343 -0
  88. package/dist/web/public/js/onboard/uiHandlers.js +758 -0
  89. package/dist/web/public/js/onboard/validationHandlers.js +378 -0
  90. package/dist/web/public/js/serverCategoryDetails.js +43 -17
  91. package/dist/web/public/js/serverCategoryList.js +15 -2
  92. package/dist/web/public/onboard.html +296 -0
  93. package/dist/web/public/styles.css +91 -1
  94. package/dist/web/server.d.ts +0 -10
  95. package/dist/web/server.js +131 -22
  96. package/package.json +2 -2
  97. package/src/core/ConfigurationProvider.ts +15 -0
  98. package/src/core/InstallationService.ts +2 -7
  99. package/src/core/MCPManager.ts +26 -1
  100. package/src/core/RequirementService.ts +2 -9
  101. package/src/core/installers/clients/BaseClientInstaller.ts +196 -0
  102. package/src/core/installers/clients/ClientInstaller.ts +97 -589
  103. package/src/core/installers/clients/ClientInstallerFactory.ts +46 -0
  104. package/src/core/installers/clients/ClineInstaller.ts +135 -0
  105. package/src/core/installers/clients/GithubCopilotInstaller.ts +179 -0
  106. package/src/core/installers/clients/MSRooCodeInstaller.ts +133 -0
  107. package/src/core/installers/requirements/BaseInstaller.ts +13 -136
  108. package/src/core/installers/requirements/CommandInstaller.ts +9 -1
  109. package/src/core/installers/requirements/GeneralInstaller.ts +11 -4
  110. package/src/core/installers/requirements/NpmInstaller.ts +178 -61
  111. package/src/core/installers/requirements/PipInstaller.ts +68 -29
  112. package/src/core/onboard/FeedOnboardService.ts +346 -0
  113. package/src/core/onboard/OnboardProcessor.ts +305 -0
  114. package/src/core/onboard/OnboardStatus.ts +55 -0
  115. package/src/core/onboard/OnboardStatusManager.ts +188 -0
  116. package/src/core/types.ts +6 -6
  117. package/src/core/validators/FeedValidator.ts +79 -0
  118. package/src/core/validators/IServerValidator.ts +21 -0
  119. package/src/core/validators/SSEServerValidator.ts +43 -0
  120. package/src/core/validators/ServerValidatorFactory.ts +51 -0
  121. package/src/core/validators/StdioServerValidator.ts +259 -0
  122. package/src/services/InstallRequestValidator.ts +1 -1
  123. package/src/services/ServerService.ts +22 -7
  124. package/src/utils/adoUtils.ts +291 -0
  125. package/src/utils/clientUtils.ts +0 -44
  126. package/src/utils/githubUtils.ts +24 -0
  127. package/src/utils/macroExpressionUtils.ts +121 -0
  128. package/src/utils/osUtils.ts +89 -24
  129. package/src/web/contract/serverContract.ts +74 -0
  130. package/src/web/public/css/notifications.css +48 -17
  131. package/src/web/public/css/onboard.css +107 -0
  132. package/src/web/public/index.html +90 -18
  133. package/src/web/public/js/api.js +3 -6
  134. package/src/web/public/js/flights/flights.js +127 -0
  135. package/src/web/public/js/modal/index.js +58 -0
  136. package/src/web/public/js/modal/installModal.js +163 -0
  137. package/src/web/public/js/modal/installation.js +281 -0
  138. package/src/web/public/js/modal/loadingModal.js +52 -0
  139. package/src/web/public/js/modal/messageQueue.js +112 -0
  140. package/src/web/public/js/modal/modalSetup.js +513 -0
  141. package/src/web/public/js/modal/modalUtils.js +49 -0
  142. package/src/web/public/js/modal/versionUtils.js +20 -0
  143. package/src/web/public/js/modal.js +25 -1041
  144. package/src/web/public/js/notifications.js +66 -27
  145. package/src/web/public/js/onboard/ONBOARDING_PAGE_DESIGN.md +338 -0
  146. package/src/web/public/js/onboard/formProcessor.js +864 -0
  147. package/src/web/public/js/onboard/index.js +374 -0
  148. package/src/web/public/js/onboard/publishHandler.js +132 -0
  149. package/src/web/public/js/onboard/state.js +76 -0
  150. package/src/web/public/js/onboard/templates.js +343 -0
  151. package/src/web/public/js/onboard/uiHandlers.js +758 -0
  152. package/src/web/public/js/onboard/validationHandlers.js +378 -0
  153. package/src/web/public/js/serverCategoryDetails.js +43 -17
  154. package/src/web/public/js/serverCategoryList.js +15 -2
  155. package/src/web/public/onboard.html +296 -0
  156. package/src/web/public/styles.css +91 -1
  157. package/src/web/server.ts +167 -58
@@ -1,33 +1,68 @@
1
- // Function to show a Bootstrap alert notification
1
+ // Function to show a toast notification
2
2
  function showToast(message, type = 'success') {
3
3
  const alertContainer = document.querySelector('.alert-container');
4
+ if (!alertContainer) {
5
+ console.error('Alert container not found. Notifications will not be displayed.');
6
+ return;
7
+ }
4
8
  const alertId = `alert-${Date.now()}`;
5
-
9
+
10
+ let iconHtml = '';
11
+ switch (type) {
12
+ case 'success':
13
+ iconHtml = '<i class="bi bi-check-circle-fill alert-icon"></i>';
14
+ break;
15
+ case 'error':
16
+ iconHtml = '<i class="bi bi-x-octagon-fill alert-icon"></i>'; // Changed icon for error
17
+ break;
18
+ case 'info':
19
+ iconHtml = '<i class="bi bi-info-circle-fill alert-icon"></i>';
20
+ break;
21
+ case 'warning':
22
+ iconHtml = '<i class="bi bi-exclamation-triangle-fill alert-icon"></i>';
23
+ break;
24
+ default:
25
+ iconHtml = '<i class="bi bi-bell-fill alert-icon"></i>'; // Default icon
26
+ }
27
+
6
28
  const alertHtml = `
7
- <div id="${alertId}" class="alert alert-${type} alert-dismissible fade show" role="alert">
8
- ${type === 'success' ?
9
- '<i class="bi bi-check-circle-fill me-2"></i>' :
10
- '<i class="bi bi-exclamation-triangle-fill me-2"></i>'
11
- }
12
- ${message}
13
- <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
29
+ <div id="${alertId}" class="alert alert-${type}" role="alert">
30
+ ${iconHtml}
31
+ <span>${message}</span>
32
+ <button type="button" class="btn-close" aria-label="Close"></button>
14
33
  </div>
15
34
  `;
16
-
35
+
17
36
  alertContainer.insertAdjacentHTML('beforeend', alertHtml);
18
-
37
+
19
38
  const alertElement = document.getElementById(alertId);
20
-
21
- // Remove the alert after 5 seconds
22
- setTimeout(() => {
23
- const bsAlert = new bootstrap.Alert(alertElement);
24
- bsAlert.close();
25
- }, 3000); // Reduced to 3 seconds
26
-
27
- // Remove the element after animation
28
- alertElement.addEventListener('closed.bs.alert', () => {
29
- alertElement.remove();
39
+ if (!alertElement) return;
40
+
41
+ // Trigger the slide-in animation
42
+ // Adding a slight delay to ensure the element is in the DOM before adding the 'show' class
43
+ requestAnimationFrame(() => {
44
+ requestAnimationFrame(() => { // Double requestAnimationFrame for more reliable transition start
45
+ alertElement.classList.add('show');
46
+ });
30
47
  });
48
+
49
+
50
+ const closeButton = alertElement.querySelector('.btn-close');
51
+
52
+ const dismissAlert = () => {
53
+ alertElement.classList.remove('show'); // Trigger slide-out animation
54
+ // Wait for fade out animation to complete before removing
55
+ alertElement.addEventListener('transitionend', () => {
56
+ alertElement.remove();
57
+ }, { once: true }); // Ensure event listener is removed after execution
58
+ };
59
+
60
+ if (closeButton) {
61
+ closeButton.addEventListener('click', dismissAlert);
62
+ }
63
+
64
+ // Auto-dismiss after 5 seconds (increased from 3)
65
+ setTimeout(dismissAlert, 5000);
31
66
  }
32
67
 
33
68
  // Function to show a confirmation dialog using custom modal system
@@ -35,7 +70,7 @@ function showConfirm(title, message) {
35
70
  return new Promise((resolve) => {
36
71
  const modalId = `confirm-modal-${Date.now()}`;
37
72
  const modalHtml = `
38
- <div id="${modalId}" class="modal">
73
+ <div id="${modalId}" class="modal" style="display: none;">
39
74
  <div class="modal-content" style="max-width: 400px; margin: 15% auto;">
40
75
  <div class="modal-header">
41
76
  <h3 class="text-lg font-semibold text-gray-700">${title}</h3>
@@ -54,19 +89,23 @@ function showConfirm(title, message) {
54
89
  </div>
55
90
  </div>
56
91
  `;
57
-
92
+
58
93
  document.body.insertAdjacentHTML('beforeend', modalHtml);
59
-
94
+
60
95
  const modalElement = document.getElementById(modalId);
61
- modalElement.style.display = 'block';
62
-
96
+ // Trigger display after a short delay to allow CSS transitions if any are added later for modals
97
+ requestAnimationFrame(() => {
98
+ modalElement.style.display = 'block';
99
+ });
100
+
101
+
63
102
  // Handle confirm button click
64
103
  modalElement.querySelector('.confirm-button').addEventListener('click', () => {
65
104
  modalElement.style.display = 'none';
66
105
  modalElement.remove();
67
106
  resolve(true);
68
107
  });
69
-
108
+
70
109
  // Handle cancel button click
71
110
  modalElement.querySelector('.cancel-button').addEventListener('click', () => {
72
111
  modalElement.style.display = 'none';
@@ -0,0 +1,338 @@
1
+ # Onboarding Page: JavaScript Design and Implementation
2
+
3
+ This document outlines the JavaScript architecture and key implementation details for the dynamic onboarding page.
4
+
5
+ ---
6
+
7
+ ## 1. File Structure and Roles
8
+
9
+ The JavaScript logic is modularized into several files within `src/web/public/js/onboard/`:
10
+
11
+ - **`index.js`**: Main entry point. Handles page initialization, event listeners for primary actions (form submission, tab switching), loading existing data, and orchestrates calls to other modules for more complex UI interactions like view toggling and validation.
12
+ - **`formProcessor.js`**: Handles conversion between the HTML form and the `FeedConfiguration` JSON object. Contains logic for `formDataToFeedConfiguration` (Form → JSON), `populateForm` (JSON → Form), and `resetOnboardFormDynamicContent`. Also includes the `submitForm` handler.
13
+ - **`uiHandlers.js`**: Manages dynamic UI manipulations, such as adding/removing server sections, environment variables, and server-specific requirements. Includes re-indexing logic, handlers for collapsible sections, view mode toggling (`toggleViewMode`), JSON data saving (`saveJsonData`), and clipboard operations (`copyJsonToClipboard`).
14
+ - **`validationHandlers.js`**: Manages the validation process, including initiating validation requests (`handleValidation`). It also provides shared utility functions for polling operation status (`pollOperationStatus`) and updating the UI with operation results (`updateOperationDisplay`), which are used by both validation and publishing flows.
15
+ - **`publishHandler.js`**: Manages the publishing process. This includes initiating publish requests (`handlePublish`), and utilizing shared functions from `validationHandlers.js` for polling status and displaying results.
16
+ - **`templates.js`**: Contains HTML string templates for dynamically generated form sections (e.g., server items, environment variables, requirements).
17
+ - **`state.js`**: Manages client-side state, primarily counters for dynamically added elements (servers, env vars per server, requirements per server).
18
+ - **`templates.js`**: Contains HTML string templates for dynamically generated form sections (e.g., server items, environment variables, requirements).
19
+ - **`state.js`**: Manages client-side state, primarily counters for dynamically added elements (servers, env vars per server, requirements per server).
20
+
21
+ ---
22
+
23
+ ## 2. Core Data Model: `FeedConfiguration`
24
+
25
+ The central data structure is `FeedConfiguration` (defined in `src/core/types.ts`). This object represents the entire configuration for a new server category.
26
+
27
+ **Key aspects:**
28
+
29
+ - `name`, `displayName`, `description`, `repository`: Basic category information.
30
+ - `mcpServers: McpConfig[]`: Array of server configurations. Each `McpConfig` includes:
31
+ - `name`, `mode`, `description`, `schemas`, `repository`
32
+ - `installation`: Contains `command`, `args`, and `env` (an object mapping environment variable names to their configurations).
33
+ - `dependencies`: Contains `requirements: Array<{ name: string; version: string; order?: number; }>` (references to full requirement definitions).
34
+ - `requirements: RequirementConfig[]`: Top-level array of unique, fully defined requirements. Each includes:
35
+ - `name`, `type` (npm, pip, command, etc.), `version`
36
+ - Optional: `alias` (for command type)
37
+ - Optional: `registry` (for private/custom registries like GitHub, Artifactory, local)
38
+
39
+ ---
40
+
41
+ ## 3. Form to JSON Conversion (`formDataToFeedConfiguration`)
42
+
43
+ Located in `formProcessor.js`, this function converts data from the HTML form into a `FeedConfiguration` object.
44
+
45
+ **Process:**
46
+
47
+ - **Parsing Strategy:** Iterates through `FormData` entries. Uses regex to identify and group fields belonging to specific servers, environment variables, and requirements based on their name attributes (e.g., `servers[0].name`, `servers[0].repository`, `servers[0].installation.env[0].name`).
48
+ - **Server Processing:**
49
+ - Collects all fields for each server into a temporary map.
50
+ - Converts collected data into `McpConfig` objects.
51
+ - Environment variables are transformed from an array of objects into the `installation.env` object structure (key-value pairs).
52
+ - **Requirement Processing:**
53
+ - For each server, its requirements are processed.
54
+ - **Server-Specific Dependencies:** An array of `{ name, version, order }` objects is created for `mcpServer.dependencies.requirements`.
55
+ - **Global Requirements List:** Full `RequirementConfig` objects (including type, alias, registry details) are constructed for each requirement defined in the form. These are added to a temporary map (`globalRequirementsMap`) to ensure uniqueness.
56
+ - **De-duplication Key:** The key `${type}|${name}|${version}` ensures requirements differing in type, name, or version are treated as distinct entries in the top-level `feedConfiguration.requirements` array.
57
+ - **Output:** Returns a complete `FeedConfiguration` object.
58
+
59
+ ---
60
+
61
+ ## 4. JSON to Form Conversion (`populateForm`)
62
+
63
+ Located in `formProcessor.js`, this function populates the HTML form using a `FeedConfiguration` object. This is crucial when loading an existing category for editing or when switching from the JSON view back to the form view.
64
+
65
+ **Process:**
66
+
67
+ - **Form Reset:** Before populating, `resetOnboardFormDynamicContent()` (now part of `formProcessor.js` and called by `populateForm` itself) is invoked to clear existing dynamic elements and reset relevant state counters.
68
+ - **Basic Fields:** Populates top-level category fields (`name`, `displayName`, etc.).
69
+ - **Server Population:**
70
+ - Iterates through `feedConfig.mcpServers`.
71
+ - For each server, `window.addServer()` (from `uiHandlers.js`) is called to create the basic server UI block.
72
+ - Server-specific fields (`name`, `mode`, `description`, `repository`, `schema`, `installation` command/args) are populated.
73
+ - **Environment Variables:** Iterates `server.installation.env`, calls `window.addEnvVariable()` for each, and populates its fields.
74
+ - **Package Dependencies:**
75
+ - Iterates through `server.dependencies.requirements` (which are `{name, version, order}` objects, referred to as `depReq`).
76
+ - For each `depReq`, searches the top-level `feedConfig.requirements` array to find the corresponding full `RequirementConfig` object (`fullReq`) by matching `fullReq.name === depReq.name` AND `fullReq.version === depReq.version`.
77
+ - If `fullReq` is found, `window.addServerRequirement()` is called to create the UI block for this requirement within the server.
78
+ - All fields of the requirement (`type`, `version`, `alias`, `registry` details) are then populated using data from `fullReq` and `depReq.order`.
79
+ - Conditional UI elements (alias field, specific registry config sections) are toggled based on the requirement's type and selected registry.
80
+
81
+ ---
82
+
83
+ ## 5. Dynamic UI Handling (`uiHandlers.js`, `templates.js`)
84
+
85
+ - **`templates.js`**: Provides HTML string template functions (`serverTemplate`, `envVariableTemplate`, `serverRequirementTemplate`) that generate the necessary HTML for dynamic sections. This includes correct indices for name attributes, `onclick` handlers, and structures for collapsible sections with toggle icons.
86
+ - The `serverTemplate` structures each server item with collapsible sub-sections for "Package Dependencies" (which includes an "Add Dependency" button), "Startup Configuration", and "Environment Variables", in that order. It also includes a `server-content-scrollable` class on the main server content `div` for vertical scrolling.
87
+ - The `serverRequirementTemplate` (used within "Package Dependencies") includes a registry type dropdown that defaults to "Public Registry" and omits the "Local Registry" and placeholder options.
88
+ - Icon-only buttons with tooltips are used (e.g., the "Remove Server" button).
89
+ - **`uiHandlers.js`**:
90
+ - **Adding Elements:**
91
+ - `addServer()`: Determines the new server's index. Inserts HTML using `serverTemplate` (which includes a collapsible server structure with sub-sections). Initializes state counters. Attaches an `onchange` event listener to the new server's mode `<select>` element, which calls `renderInstallationConfig`. Calls `renderInstallationConfig` to display the initial UI for the "Startup Configuration" section (defaulting to `stdio` fields). The server header is clickable to toggle its content visibility.
92
+ - `addEnvVariable(serverIndex)`, `addServerRequirement(serverIndex)`: Get current counter for the specific server, insert HTML using respective templates, and increment the counter.
93
+ - **Rendering Startup Configuration:**
94
+ - `renderInstallationConfig(serverIndex)`: This function is called when a server is added or its mode is changed. It populates the "Startup Configuration" section based on the server's current mode:
95
+ - If `sse`: Clears the startup configuration container (e.g., `installation-config-${serverIndex}`) and inserts an input field for `installation.url`. Hides the "Environment Variables" block.
96
+ - If `stdio` (or other): Clears the startup configuration container and inserts input fields for `installation.command` and `installation.args`. Shows the "Environment Variables" block.
97
+ - **Removing Elements:**
98
+ - `removeServer(serverIndexToRemove)`: Removes the server item from the DOM, then calls `reindexServers()`.
99
+ - `removeEnvVariable(serverIndex, envIndex)`, `removeServerRequirement(serverIndex, reqIndex)`: Remove the specific item. (Re-indexing of these sub-items happens within `reindexServers` when a parent server is re-indexed.)
100
+ - **Re-indexing:**
101
+ - `reindexServers()`: Called after a server is removed.
102
+ - Iterates through all remaining server items in the DOM.
103
+ - For each server item and its new sequential index (`newServerIndex`):
104
+ - Updates its `data-index` attribute.
105
+ - Updates its displayed title (e.g., "MCP Server #1").
106
+ - Updates name attributes of all form elements within it to reflect `newServerIndex`.
107
+ - Updates `onclick` handlers for all relevant buttons (remove server, add env var, add requirement, etc.) to use `newServerIndex`.
108
+ - Updates IDs of dynamically generated elements (e.g., `schema-path-`, `envVarsContainer_`, `server-requirements-list-`).
109
+ - Recursively re-indexes nested environment variables and server-specific requirements:
110
+ - Updates their `data-env-index`/`data-req-index`.
111
+ - Updates their input name attributes (e.g., `servers[newServerIndex].installation.env[newEnvIndex]...`).
112
+ - Updates their `onclick` and `onchange` handlers with new indices.
113
+ - Updates their dynamic IDs.
114
+ - After re-indexing all servers and their children, it rebuilds/updates `state.envCounters` and `state.serverRequirementCounters` and sets `state.serverCounter` to the new total.
115
+ - **Toggling Fields:**
116
+ - `toggleServerAliasField()`: Shows/hides the alias input based on requirement type (`command`).
117
+ - `toggleServerRegistryConfig()`: Shows/hides specific registry configuration sections based on the selected registry type.
118
+ - `browseLocalSchema()`: Uses File System Access API (with fallback) to allow users to select a local schema file, populating its name into the input field.
119
+ - `toggleSectionContent(contentId, iconElement)`: Generic handler to toggle the visibility of a content element (identified by `contentId`) and update an associated icon's state (e.g., chevron up/down). Used for all collapsible sections.
120
+ - `toggleViewMode(isJsonView)`: Handles switching between the form view and the JSON editor view. Manages data conversion and panel visibility.
121
+ - `saveJsonData()`: Handles submitting the data from the JSON editor.
122
+ - `copyJsonToClipboard()`: Copies the content of the JSON editor to the clipboard.
123
+
124
+ ---
125
+
126
+ ## 6. State Management (`state.js`)
127
+
128
+ Provides a simple client-side state store.
129
+
130
+ - `state.serverCounter`: Tracks the total number of server sections. Managed by `setServerCounter()`, which is updated by `addServer()` and `reindexServers()`.
131
+ - `state.envCounters` (`Map`): `serverIndex` → count for environment variables within each server.
132
+ - `state.serverRequirementCounters` (`Map`): `serverIndex` → count for requirements within each server.
133
+
134
+ These maps are updated by their respective add... functions and fully rebuilt by `reindexServers()` to ensure consistency after deletions and re-indexing.
135
+
136
+ ---
137
+
138
+ ## 7. View Toggling (Form vs. JSON Editor — `uiHandlers.js` & `formProcessor.js`)
139
+
140
+ A toggle switch allows users to switch between the standard form view and a raw JSON editor view.
141
+
142
+ - **Switching to JSON View:**
143
+ - `getFormData(currentForm)` (from `formProcessor.js`) is called, which internally uses `formDataToFeedConfiguration` to get the `FeedConfiguration` object.
144
+ - This object is `JSON.stringify`-ed and displayed in a `<textarea>`.
145
+ - The form panel is hidden, and the JSON editor panel is shown.
146
+ - **Switching back to Form View (from JSON):**
147
+ - The JSON content is read from `jsonEditorTextarea` and parsed.
148
+ - `resetOnboardFormDynamicContent()` (from `formProcessor.js`) is called by `populateForm` (also from `formProcessor.js`):
149
+ - Clears the `serversList` container in the DOM.
150
+ - Resets the main form (`onboardForm.reset()`).
151
+ - Resets state counters (`setServerCounter(0)`, `state.envCounters.clear()`, `state.serverRequirementCounters.clear()`) using imported functions/objects from `state.js`.
152
+ - `populateForm(parsedJsonData)` (from `formProcessor.js`) is called to reconstruct the form from the (potentially edited) JSON.
153
+ - If parsing or populating the form fails:
154
+ - An error notification is shown using `showToast()`.
155
+ - The view remains in JSON mode.
156
+ - The view mode toggle switch is ensured to be in the "JSON View" state.
157
+ - If successful, the JSON editor panel is hidden, and the form panel is shown.
158
+
159
+ > The `toggleViewMode` function in `uiHandlers.js` orchestrates this. Application of JSON to the form (via `populateForm` in `formProcessor.js`) is automatic upon switching back to the form view. If it fails, the user stays in JSON view.
160
+
161
+ ---
162
+
163
+ ## 8. Other Key Features (`index.js`, `formProcessor.js`, `validationHandlers.js`, `publishHandler.js`, `uiHandlers.js`)
164
+
165
+ - **Loading Existing Category (`loadExistingCategory` in `index.js`)**: If a `?category=categoryName` URL parameter is present, fetches the category data from `/api/categories/:categoryName`, and then uses `populateForm()` (from `formProcessor.js`) to fill the form for editing. Errors are reported using `showToast()`.
166
+ - **Publishing (`handlePublish` in `publishHandler.js`)**:
167
+ - Triggered by the "Publish" button.
168
+ - Calls `getFormData()` (from `formProcessor.js`) to get the current form data as `FeedConfiguration`.
169
+ - Sends an initial POST request to `/api/categories/onboard` with the `FeedConfiguration` object and an `isUpdate` flag.
170
+ - The "Publish" button shows a spinning loader icon and its text changes to "Publishing...". Both "Validate" and "Publish" buttons are disabled.
171
+ - **Polling for Status**: If the initial publish request is successful and the operation is not immediately completed or failed, `handlePublish` initiates polling using the shared `pollOperationStatus` function (from `validationHandlers.js`). This function periodically calls `GET /api/categories/:categoryName/onboard/status`.
172
+ - **Displaying Results**: The shared `updateOperationDisplay` function (from `validationHandlers.js`) formats and displays the results from both the initial publish call and subsequent status polls in the relevant status panel. It shows overall status, messages, PR info (if available), and detailed validation results if included in the publish response.
173
+ - **Completion/Failure**: Polling stops when the status is 'COMPLETED', 'FAILED', or 'succeeded'. Upon completion or failure, the "Publish" button reverts to its original state, and both "Validate" and "Publish" buttons are re-enabled. Success and error messages are displayed using `showToast()`.
174
+ - **Validation (`handleValidation` in `validationHandlers.js`)**:
175
+ - **Validation (`handleValidation` in `validationHandlers.js`)**:
176
+ - The `validationStatusPanel` (unique per tab) is located under the "MCP Servers" section (or equivalent) and above the main action buttons ("Validate", "Publish"). It is a foldable panel.
177
+ - When the "Validate" button is clicked:
178
+ - Calls `getFormData()` (from `formProcessor.js`) to get the current form data as `FeedConfiguration`.
179
+ - Sends an initial POST request to `/api/categories/onboard/validate`.
180
+ - The "Validate" button shows a spinning loader icon and its text changes to "Validating...". Both "Validate" and "Publish" buttons are disabled.
181
+ - **Polling for Status**:
182
+ - If the initial validation request is successful and the operation is not immediately completed or failed, `handleValidation` initiates polling using the shared `pollOperationStatus` function (from `validationHandlers.js`).
183
+ - This function uses the `onboardingId` (category name) from the validation response to periodically call `GET /api/categories/:categoryName/onboard/status`.
184
+ - **Displaying Results**:
185
+ - The shared `updateOperationDisplay` function (from `validationHandlers.js`) formats and displays the results from both the initial validation call and subsequent status polls in the relevant status panel.
186
+ - It handles different structures of the `validationStatus` object in the response, including displaying overall status, messages, and detailed results for each server if `validationStatus.serverResults` is present.
187
+ - **Completion/Failure**:
188
+ - Polling stops when the status is 'COMPLETED', 'FAILED', or 'succeeded'.
189
+ - Upon completion or failure, the "Validate" button reverts to its original state ("Validate" text and icon), and both "Validate" and "Publish" buttons are re-enabled.
190
+ - **Copy JSON (`copyJsonToClipboard` in `uiHandlers.js`)**: Copies the content of `jsonEditorTextarea` to the clipboard. Uses `showToast()` for feedback.
191
+ - **Global Function Exposure**: Necessary UI handler functions (like `addServer`, `removeServer`, `toggleSectionContent`, etc.) are attached to the `window` object so they can be called from `onclick` attributes in the HTML templates.
192
+ - **Custom Notifications**: Standard browser `alert()` calls have been replaced with a custom toast notification system (`showToast()` from `../notifications.js`). This system requires an `.alert-container` div in the host HTML (`onboard.html`) and uses CSS from `css/notifications.css` for styling. The `notifications.js` module handles the creation, display, and dismissal (manual and automatic) of these toasts without relying on Bootstrap's JavaScript.
193
+
194
+ ---
195
+
196
+ This summary covers the main design patterns and implementation choices made for the onboarding page's frontend logic.
197
+
198
+ ---
199
+
200
+ ## 9. Recent Fixes and Changes (May 2025)
201
+
202
+ This section documents significant fixes and behavior changes implemented recently.
203
+
204
+ - **Visibility of Existing Category Servers:**
205
+
206
+ - **Issue:** When selecting an existing category in the "Create Server in Existing Category" tab, the container holding the list of existing MCP servers (`existingCategoryMcpServersContainer`) and the servers themselves were not becoming visible, even though the data was being fetched and `populateForm` was called.
207
+ - **Root Cause Analysis:** Extensive logging revealed that `existingCategoryMcpServersContainer` was being correctly unhidden before `populateForm` was called. However, immediately after `populateForm` completed, the container was found to be hidden again. The exact mechanism causing this re-hiding was elusive but seemed to occur synchronously within or immediately after `populateForm`'s execution, despite `populateForm` itself not directly hiding the container. Standard form reset (`form.reset()`) was ruled out as the cause.
208
+ - **Solution:**
209
+ 1. In `templates.js`, the `serverTemplate` was modified to ensure that the main content `div` of a server item (`server-content-${serverIndex}`) includes the `hidden` class by default. This allows the `toggleSectionContent` function to correctly manage its visibility.
210
+ 2. In `uiHandlers.js`, within the `addServer` function, if a server is being rendered as `isReadOnly` (i.e., an existing server), its content section (`#server-content-${newServerIndex}`) is explicitly made visible by removing the `hidden` class. This ensures that existing servers are expanded by default when displayed.
211
+ 3. **Crucially**, in `index.js`, within the `handleExistingCategorySelection` function, after `populateForm` is called to display the existing servers, a line was added to explicitly call `mcpServersContainer.classList.remove('hidden');`. This ensures that the main container for these servers is visible, overriding whatever was causing it to become hidden.
212
+ - **Outcome:** Existing servers for a selected category are now correctly displayed and visible.
213
+
214
+ - **Requirement Lookup in `populateForm`:**
215
+
216
+ - **Issue:** The logic in `formProcessor.js` (`populateForm`) for finding the full `RequirementConfig` for a server's dependency was matching on both `name` and `version`.
217
+ - **Change Request:** The lookup should only be based on the requirement `name`, ignoring the `version` specified in the server's dependency list when matching against the global `feedConfig.requirements`.
218
+ - **Solution:** In `formProcessor.js`, the line:
219
+ `const fullReq = (feedConfig.requirements || []).find(r => r.name === depReq.name && r.version === depReq.version);`
220
+ was changed to:
221
+ `const fullReq = (feedConfig.requirements || []).find(r => r.name === depReq.name);`
222
+ The associated warning message was also updated to reflect this change in lookup behavior.
223
+
224
+ - **Code Cleanup:**
225
+
226
+ - All diagnostic `console.log` statements added during the debugging of the visibility issue were removed from `index.js`, `formProcessor.js`, and `uiHandlers.js`.
227
+ - The experimental `requestAnimationFrame` logic for forcing a reflow in `formProcessor.js` was removed as it was not the solution to the visibility problem.
228
+
229
+ - **Tab Switching and View Mode Toggling Enhancements:**
230
+
231
+ - **Context:** A series of changes were made to improve the user experience related to switching between the main onboarding tabs ("Create New Category", "Create Server in Existing Category") and toggling between the Form view and JSON editor view.
232
+ - **Issues Addressed & Solutions:**
233
+ 1. **JSON View Buttons Hidden (`uiHandlers.js`):**
234
+ - **Problem:** Buttons like "Cancel" and "Publish JSON" were visible in the JSON editor view, which was not desired.
235
+ - **Solution:** The `toggleViewMode` function in `uiHandlers.js` was updated to explicitly hide the `jsonEditorActionsContainer` when switching to JSON view.
236
+ 2. **JSON View Content Preservation (`uiHandlers.js`):**
237
+ - **Problem:** Clicking the JSON view toggle switch again while already in JSON view would cause the editor's content to be re-processed or cleared.
238
+ - **Solution:** The `toggleViewMode` function in `uiHandlers.js` now checks if the target view (Form or JSON) is already active. If so, it returns early, preventing unnecessary re-rendering and preserving the current content.
239
+ 3. \*\*Tab Switching Logic Improvements (`index.js`):
240
+ - **Problem 1:** Clicking on a main navigation tab that was already active would still trigger tab switching logic, potentially causing unnecessary view updates.
241
+ - **Solution 1:** The `switchTab` function in `index.js` now checks if the `targetTab` is the same as the `activeTab`. If so, it returns immediately.
242
+ - **Problem 2:** When switching away from the "Create New Category" tab and then back to it (without being in an edit-category scenario), any entered form data was lost due to an automatic form reset.
243
+ - **Solution 2:** The automatic call to `resetOnboardFormDynamicContent('onboardForm')` within `switchTab` for the "Create New Category" tab (in non-edit scenarios) was removed. This allows form data to be preserved when tabbing away and back.
244
+ - **Problem 3:** If the JSON view was active and a user clicked on a different main navigation tab, the new tab's form content could render on top of or alongside the still-visible JSON editor.
245
+ - **Solution 3:** The `switchTab` function in `index.js` was updated. If the JSON view is active when a tab switch is initiated, it now first calls `toggleViewMode(false, ...)` to programmatically switch back to the Form view (for the currently active tab) before proceeding to display the content of the newly selected tab. This ensures a clean transition from JSON view to the new tab's form view.
246
+ - **Outcome:** These changes provide a more stable, predictable, and user-friendly experience when navigating between tabs and view modes. Data entered by the user is better preserved, and UI rendering artifacts during transitions are avoided.
247
+
248
+ - **Dropdown Reset, Form Disappearance, and Misplaced Validation (May 2025 - Current Session):**
249
+ - **Context:** A series of interconnected issues were addressed to improve the stability and correctness of the "Create New Server in Existing Category" tab and its interaction with view toggling and validation.
250
+ - **Issues Addressed & Solutions:**
251
+ 1. **Existing Category Dropdown Reset (`formProcessor.js`):**
252
+ - **Problem:** After selecting a category from the `existingCategorySelect` dropdown on the "Create New Server in Existing Category" tab, the dropdown would immediately reset to its default "Select a category" or "Loading..." state.
253
+ - **Root Cause:** The `populateForm` function, called upon category selection, invoked `resetOnboardFormDynamicContent`. Inside `resetOnboardFormDynamicContent`, the line `formToReset.reset()` was being called for the `onboardServerForm` (the form containing the dropdown). This `HTMLFormElement.reset()` method reverts all form controls to their initial HTML values.
254
+ - **Solution:** The `resetOnboardFormDynamicContent` function in `formProcessor.js` was modified. The `formToReset.reset()` call is now conditional: it is skipped if `formId` is `'onboardServerForm'`, thus preserving the dropdown's selected value. Other dynamic content clearing (server list, counters) within the function remains active.
255
+ 2. **Form Disappearance on JSON Toggle (Existing Category Tab - `formProcessor.js`):**
256
+ - **Problem:** On the "Create New Server in Existing Category" tab, if a category was selected (displaying its basic info and servers), then the view was toggled to JSON and back to Form view, the displayed category information would vanish.
257
+ - **Root Cause:** When `toggleViewMode` (in `uiHandlers.js`) switched from JSON back to Form view, it called `populateForm`. However, `populateForm` lacked specific logic to re-populate the basic category information fields (name, display name, description, repository) for the `onboardServerForm`. Additionally, the containers for this basic info (`existingCategoryBasicInfoContainer`) and the MCP servers (`existingCategoryMcpServersContainer`) were not being explicitly made visible again after `resetOnboardFormDynamicContent` (called by `populateForm`) might have hidden them or cleared their content.
258
+ - **Solution:**
259
+ - An `else if (formId === 'onboardServerForm' && feedConfig)` block was added to `populateForm` in `formProcessor.js`. This block now explicitly populates the read-only basic category information fields using the `feedConfig` data.
260
+ - Within this new block, `existingCategoryBasicInfoContainer.classList.remove('hidden')` and `existingCategoryMcpServersContainer.classList.remove('hidden')` are called to ensure these sections are visible.
261
+ 3. **Validation Results on Wrong Tab (Multiple Files):**
262
+ - **Problem:** Clicking the "Validate" button on the "Create New Server in Existing Category" tab would display the validation results in the validation panel of the "Create New Category" tab.
263
+ - **Root Cause:** Validation panels, content areas, and buttons on both tabs shared common HTML IDs (e.g., `validationStatusPanel`, `validateButton`). JavaScript's `getElementById` would typically find the first matching element in the DOM, leading to the incorrect panel being targeted.
264
+ - **Solution (Multi-file update):**
265
+ - **HTML (`onboard.html`):** All relevant validation-related element IDs were made unique for each tab (e.g., `validationStatusPanelNewCategory`, `validateButtonNewCategory`, `validationStatusPanelExistingCategory`, `validateButtonExistingCategory`).
266
+ - **Event Listeners (`index.js`):** Event listeners for the "Validate" buttons were updated to target these new unique IDs.
267
+ - **Validation Logic (`validationHandlers.js`):**
268
+ - The `handleValidation` function was updated to accept `activeTab` and `currentSelectedCategoryData` as parameters. It now dynamically determines the correct, unique element IDs for the panel, content area, form, validate button, and publish button based on the `activeTab`.
269
+ - The `pollValidationStatus` function was modified to accept these dynamic element IDs as parameters, ensuring it updates the UI on the correct tab during polling.
270
+ - The call to `getFormData` within `handleValidation` was adjusted to pass the `forExistingCategoryTab` flag and `currentSelectedCategoryData` when validating for the "Create Server in Existing Category" tab.
271
+ - **Form Reset Logic (`formProcessor.js`):**
272
+ - The `resetOnboardFormDynamicContent` function was updated. When resetting validation panels, it now determines the correct unique panel ID and content ID based on the `formId` parameter, ensuring it hides and clears the appropriate panel for the active tab.
273
+ - **Outcome:** These fixes ensure that the "Create New Server in Existing Category" tab functions correctly with respect to category selection, view toggling, and validation display, providing a more robust and intuitive user experience.
274
+
275
+ - **API Data Integrity and UI State for "Create Server" Tab (May 2025 - Current Session):**
276
+ - **Context:** Two issues were addressed related to the "Create Server in Existing Category" tab's interaction with backend APIs and UI feedback during operations.
277
+ - **Issues Addressed & Solutions:**
278
+ 1. **Incomplete Data Sent to API:**
279
+ - **Problem:** When using the "Validate" or "Publish" buttons on the "Create Server in Existing Category" tab, only the data for the newly added server(s) was being sent to the backend, omitting the data of the existing category to which they were being added.
280
+ - **Solution:**
281
+ - The `handleValidation` function in `validationHandlers.js` was updated. It now retrieves the new server data using `getFormData` and then merges it with the `currentSelectedCategoryData` (the full data of the existing category) before sending the combined `FeedConfiguration` to the `/api/categories/onboard/validate` endpoint.
282
+ - Similarly, the `handlePublish` function in `publishHandler.js` was updated to perform the same merge of new server data with `currentSelectedCategoryData` before sending the complete payload to the `/api/categories/onboard` endpoint.
283
+ - **Outcome:** The backend now receives the full, correct `FeedConfiguration` when a new server is validated or published within an existing category.
284
+ 2. **Persistent Spinner on Publish Failure:**
285
+ - **Problem:** If a publish operation failed (e.g., backend returns a "FAILED" status), the "Publish" button would remain in its loading state (displaying a spinner icon) instead of reverting to its active state.
286
+ - **Root Cause:** The status check within the `pollOperationStatus` function (in `validationHandlers.js`) was case-sensitive when comparing the received status string (e.g., "failed") against expected terminal states (e.g., "FAILED"). If the casing didn't match, the logic to reset button states wasn't triggered.
287
+ - **Solution:**
288
+ - The `pollOperationStatus` function in `validationHandlers.js` was modified to convert the received status string to uppercase before comparing it against 'COMPLETED', 'FAILED', or 'SUCCEEDED'. This makes the check case-insensitive.
289
+ - Additionally, the direct error/failure handling paths within `handlePublish` (in `publishHandler.js`) were enhanced to ensure both "Publish" and "Validate" buttons are comprehensively reset (disabling, innerHTML, and opacity classes) if the initial publish call itself fails or returns a terminal status immediately.
290
+ - **Outcome:** The "Publish" and "Validate" buttons now reliably revert to their default active states when an operation (validation or publish) concludes with a failure, regardless of the casing of the status string from the backend or whether the failure occurs immediately or during polling.
291
+ - **Overall Outcome:** These changes improve the reliability of data submission and provide more accurate UI feedback for asynchronous operations on the "Create Server in Existing Category" tab.
292
+
293
+ ---
294
+
295
+ ## 10. Server Validation System
296
+
297
+ The server validation system consists of multiple components that work together to validate MCP server configurations. This ensures that servers are properly configured before they can be deployed.
298
+
299
+ ### Server Validator Architecture
300
+
301
+ - **`IServerValidator` Interface**: Defines the common validation contract for all server validators:
302
+ - `validateServer(server: McpConfig, config: FeedConfiguration): Promise<boolean>`
303
+ - Implementations throw errors with descriptive messages when validation fails
304
+
305
+ - **`ServerValidatorFactory`**: Factory class managing validator instances
306
+ - Maintains a singleton map of validators by type ('stdio' | 'sse')
307
+ - Provides methods to get appropriate validator for server mode
308
+ - Initializes validators on construction
309
+
310
+ ### Validator Implementations
311
+
312
+ 1. **StdioServerValidator**:
313
+ - Validates stdio-mode MCP server configurations
314
+ - Key validation steps:
315
+ - Verifies installation command exists and is executable
316
+ - Validates required environment variables
317
+ - Validates and installs dependencies using installer factory
318
+ - Tests server startup with path resolution for:
319
+ - Node commands: Resolves `${NPMPATH}` in arguments
320
+ - Python commands: Resolves `${PYTHON_PACKAGE}` in arguments
321
+ - Uses timeout-based server startup testing with output monitoring
322
+ - Comprehensive error handling and logging
323
+
324
+ 2. **SSEServerValidator**:
325
+ - Validates SSE-mode MCP server configurations
326
+ - Key validation steps:
327
+ - Verifies installation URL is present and valid
328
+ - Validates server mode is 'sse'
329
+ - Extensible design for additional SSE-specific validation
330
+
331
+ ### Error Handling
332
+
333
+ - All validators provide detailed error messages through Error objects
334
+ - Errors include specific validation failure reasons (e.g., missing command, invalid URL)
335
+ - Logging is implemented throughout the validation process
336
+ - Error messages propagate to the UI for user feedback
337
+
338
+ This validation system ensures that server configurations are complete and functional before deployment, reducing runtime issues and improving reliability.