@kabmo-labs/kabmo 0.30.1 → 0.31.0

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 (107) hide show
  1. package/README.md +79 -21
  2. package/dist/client/index.html +1 -1
  3. package/dist/client/index.js +481 -462
  4. package/dist/client/static/js/{index-bwhhehnh.js → index-r3bhgvkt.js} +772 -773
  5. package/marketplace/plugins/stats/package.json +2 -2
  6. package/marketplace/plugins/stats/src/format.test.ts +7 -1
  7. package/package.json +2 -2
  8. package/src/client/components/common/context-usage-button/McpSection.tsx +133 -0
  9. package/src/client/components/common/context-usage-button/Ring.tsx +12 -6
  10. package/src/client/components/common/context-usage-button/index.test.tsx +24 -13
  11. package/src/client/components/common/context-usage-button/index.tsx +32 -34
  12. package/src/client/components/common/session-row/TrailingSlot.tsx +6 -2
  13. package/src/client/components/common/session-row/session-row.test.tsx +13 -0
  14. package/src/client/components/layout/desktop-layout/index.tsx +5 -1
  15. package/src/client/components/mobile/RightSidebar.tsx +2 -1
  16. package/src/client/components/settings/categories/McpSettings.tsx +10 -3
  17. package/src/client/components/settings/categories/mcp-settings/AdvancedSection.tsx +244 -0
  18. package/src/client/components/settings/categories/mcp-settings/ConnectionTest.tsx +3 -3
  19. package/src/client/components/settings/categories/mcp-settings/DetailPane.tsx +55 -97
  20. package/src/client/components/settings/categories/mcp-settings/ImportModal.tsx +12 -64
  21. package/src/client/components/settings/categories/mcp-settings/{EnvVarsSection.tsx → KeyValueSection.tsx} +42 -24
  22. package/src/client/components/settings/categories/mcp-settings/SidebarList.tsx +1 -1
  23. package/src/client/components/settings/categories/mcp-settings/TransportSection.tsx +101 -0
  24. package/src/client/components/workspace/browser-panel/EngineNotice.test.tsx +109 -0
  25. package/src/client/components/workspace/browser-panel/EngineNotice.tsx +112 -0
  26. package/src/client/components/workspace/browser-panel/index.tsx +45 -12
  27. package/src/client/components/workspace/chat-timeline/chat-input/AccessDropdown.test.ts +63 -0
  28. package/src/client/components/workspace/chat-timeline/chat-input/AccessDropdown.tsx +18 -6
  29. package/src/client/components/workspace/chat-timeline/chat-input/Toolbar.tsx +3 -1
  30. package/src/client/components/workspace/chat-timeline/chat-input/access-levels.ts +39 -1
  31. package/src/client/components/workspace/chat-timeline/tool-renderers/panels/Eval.test.tsx +13 -7
  32. package/src/client/components/workspace/editor/plugin-rail.test.tsx +6 -1
  33. package/src/client/components/workspace/terminal-panel/scroll-hold.test.ts +20 -5
  34. package/src/client/data/settings/mcp.ts +4 -2
  35. package/src/client/data/settings/omp-schema.json +22 -2
  36. package/src/client/hooks/browser/use-browser-engine.ts +99 -0
  37. package/src/client/hooks/chat/context/mcp.ts +159 -0
  38. package/src/client/hooks/chat/timeline/access-mode.ts +45 -15
  39. package/src/client/hooks/chat/timeline/index.ts +7 -3
  40. package/src/client/hooks/chat/timeline/timeline-mode-state.test.ts +33 -4
  41. package/src/client/hooks/ui/ui-listeners.test.ts +13 -18
  42. package/src/server/lib/browser/engine.test.ts +118 -0
  43. package/src/server/lib/browser/engine.ts +102 -0
  44. package/src/server/lib/db/schema.ts +4 -0
  45. package/src/server/lib/fs/toolchain-path.test.ts +87 -0
  46. package/src/server/lib/fs/toolchain-path.ts +49 -0
  47. package/src/server/lib/harness/acp/protocol.ts +9 -1
  48. package/src/server/lib/harness/auto-probe.server.ts +3 -2
  49. package/src/server/lib/harness/launch-table.ts +3 -2
  50. package/src/server/lib/harness/spawn.server.ts +5 -1
  51. package/src/server/lib/harness/update-queue.server.ts +2 -1
  52. package/src/server/lib/harness/update-state.server.ts +6 -2
  53. package/src/server/lib/mcp/probe.server.ts +71 -0
  54. package/src/server/lib/mcp/registry.server.ts +195 -46
  55. package/src/server/lib/mcp/registry.test.ts +76 -4
  56. package/src/server/lib/mcp/schema.server.ts +35 -0
  57. package/src/server/lib/mcp/session-mcp.test.ts +164 -0
  58. package/src/server/lib/mcp/session-overlay.server.ts +152 -0
  59. package/src/server/lib/mcp/session-state.server.ts +75 -0
  60. package/src/server/lib/mcp/store.server.ts +6 -1
  61. package/src/server/lib/omp/config/config-cli.ts +4 -0
  62. package/src/server/lib/omp/config/mcp-and-cli.test.ts +12 -183
  63. package/src/server/lib/omp/config/mcp-config.test.ts +277 -0
  64. package/src/server/lib/omp/config/mcp-shared.ts +36 -0
  65. package/src/server/lib/omp/config/mcp-test-protocol.ts +89 -0
  66. package/src/server/lib/omp/config/mcp-test-remote.ts +167 -0
  67. package/src/server/lib/omp/config/mcp-test.ts +21 -123
  68. package/src/server/lib/omp/config/mcp-write.ts +179 -0
  69. package/src/server/lib/omp/config/mcp.ts +138 -118
  70. package/src/server/lib/omp/core/cli.ts +4 -14
  71. package/src/server/lib/omp/rpc/manager.ts +12 -17
  72. package/src/server/lib/omp/rpc/reload-mcp.ts +39 -0
  73. package/src/server/lib/omp/rpc/session-registry.ts +6 -2
  74. package/src/server/lib/omp/rpc/spawn-mcp.ts +43 -0
  75. package/src/server/lib/omp/session/delete.server.ts +7 -0
  76. package/src/server/lib/plugins/mcp.server.ts +2 -2
  77. package/src/server/lib/realtime/topics/workspace.server.test.ts +44 -0
  78. package/src/server/lib/realtime/topics/workspace.server.ts +3 -2
  79. package/src/server/routes/browser/engine.test.ts +70 -0
  80. package/src/server/routes/browser/engine.ts +51 -0
  81. package/src/server/routes/browser/index.ts +5 -0
  82. package/src/server/routes/fs/git.ts +4 -3
  83. package/src/server/routes/harness/versions.test.ts +5 -0
  84. package/src/server/routes/sessions/index.ts +7 -0
  85. package/src/server/routes/sessions/mcp.test.ts +154 -0
  86. package/src/server/routes/sessions/mcp.ts +202 -0
  87. package/src/server/routes/settings/mcp-test.ts +5 -4
  88. package/src/server/routes/settings/mcp.test.ts +42 -1
  89. package/src/server/routes/settings/mcp.ts +80 -24
  90. package/src/shared/lib/code/highlight-memo.test.ts +18 -0
  91. package/src/shared/lib/code/highlight-memo.ts +46 -17
  92. package/src/shared/lib/mcp/import.ts +112 -0
  93. package/src/shared/lib/mcp/item.ts +61 -0
  94. package/src/shared/lib/mcp/key-value.ts +37 -0
  95. package/src/shared/lib/mcp/mcp-lib.test.ts +119 -0
  96. package/src/shared/lib/mcp/status.test.ts +36 -0
  97. package/src/shared/lib/mcp/status.ts +38 -0
  98. package/src/shared/lib/models/client.ts +27 -6
  99. package/src/shared/lib/models/provider/models.test.ts +31 -0
  100. package/src/shared/lib/omp/config/access-mode.test.ts +73 -0
  101. package/src/shared/lib/omp/config/access-mode.ts +49 -0
  102. package/src/shared/lib/workspace/right-panels.ts +13 -0
  103. package/src/shared/lib/workspace/workspace-modules.test.ts +3 -1
  104. package/src/shared/types/browser.ts +21 -0
  105. package/src/shared/types/settings/mcp.ts +73 -4
  106. package/src/test-support/pristine-globals.test.ts +53 -0
  107. package/src/test-support/pristine-globals.ts +6 -1
@@ -7,7 +7,22 @@ import { isMockMode } from '@/server/mock.server';
7
7
  import { mcpStore, readCustomMcpServers, writeCustomMcpServers } from '@/server/lib/mcp/store.server';
8
8
  import { resolveRoot } from '@/server/lib/fs/root';
9
9
  import type { McpServerItem } from '@/shared/types';
10
- import { deleteProjectMcpServer, deleteUserMcpServer, nativeToServerItem, readProjectMcpConfig, readUserMcpConfig, redactEnvVars, writeProjectMcpServer, writeUserMcpServer } from '@/server/lib/omp/config/mcp';
10
+ import { isRecord } from '@/shared/lib/util/guards';
11
+ import { rowsToRecord, REDACTED_SENTINEL } from '@/shared/lib/mcp/key-value';
12
+ import {
13
+ isProjectMcpConfigEnabled,
14
+ isServerEnabled,
15
+ nativeToServerItem,
16
+ readProjectMcpConfig,
17
+ readUserMcpConfig,
18
+ redactServerItem,
19
+ } from '@/server/lib/omp/config/mcp';
20
+ import {
21
+ deleteProjectMcpServer,
22
+ deleteUserMcpServer,
23
+ writeProjectMcpServer,
24
+ writeUserMcpServer,
25
+ } from '@/server/lib/omp/config/mcp-write';
11
26
 
12
27
  const NATIVE_USER_PREFIX = 'omp-user-';
13
28
  const NATIVE_PROJECT_PREFIX = 'omp-project-';
@@ -38,17 +53,28 @@ function customForProject(custom: McpServerItem[], projectPath?: string): McpSer
38
53
  async function mergeServers(custom: McpServerItem[], projectPath?: string): Promise<McpServerItem[]> {
39
54
  const user = await readUserMcpConfig();
40
55
  const userItems: McpServerItem[] = user.servers.map((entry, index) =>
41
- nativeToServerItem(entry.name, entry.config, index, !user.disabledServers.includes(entry.name)),
56
+ nativeToServerItem(
57
+ entry.name,
58
+ entry.config,
59
+ index,
60
+ isServerEnabled(entry.name, entry.config, user.disabledServers, user.enabledServers),
61
+ ),
42
62
  );
43
- const project = projectPath ? await readProjectMcpConfig(projectPath) : undefined;
63
+ const project = projectPath && (await isProjectMcpConfigEnabled())
64
+ ? await readProjectMcpConfig(projectPath)
65
+ : undefined;
44
66
  const projectItems: McpServerItem[] = projectPath && project
45
67
  ? project.servers.map((entry, index) =>
46
- nativeToServerItem(entry.name, entry.config, index, !project.disabledServers.includes(entry.name), {
47
- path: projectPath,
48
- }),
68
+ nativeToServerItem(
69
+ entry.name,
70
+ entry.config,
71
+ index,
72
+ isServerEnabled(entry.name, entry.config, user.disabledServers, user.enabledServers),
73
+ { path: projectPath },
74
+ ),
49
75
  )
50
76
  : [];
51
- const natives = [...userItems, ...projectItems].map((item) => ({ ...item, envVars: redactEnvVars(item.envVars) }));
77
+ const natives = [...userItems, ...projectItems].map(redactServerItem);
52
78
  const nativeNames = new Set(natives.map((item) => item.name.toLowerCase()));
53
79
  return [
54
80
  ...natives,
@@ -56,29 +82,58 @@ async function mergeServers(custom: McpServerItem[], projectPath?: string): Prom
56
82
  ];
57
83
  }
58
84
 
85
+ /** The browser payload for one server; every field is untrusted. */
59
86
  interface McpNativePayloadSource {
60
- reachType?: unknown;
87
+ transport?: unknown;
61
88
  linkUrl?: unknown;
62
89
  commandArgs?: unknown;
63
90
  envVars?: unknown;
91
+ headers?: unknown;
92
+ cwd?: unknown;
93
+ timeout?: unknown;
94
+ requestIdFormat?: unknown;
95
+ instructions?: unknown;
96
+ auth?: unknown;
97
+ oauth?: unknown;
98
+ enabled?: unknown;
99
+ }
100
+
101
+ /** A credential block without the form's blanks and redaction placeholders. */
102
+ function credentialBlock(value: unknown): Record<string, unknown> | undefined {
103
+ if (!isRecord(value)) return undefined;
104
+ const entries = Object.entries(value).filter(
105
+ ([, entry]) => entry !== undefined && entry !== null && entry !== '' && entry !== REDACTED_SENTINEL,
106
+ );
107
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined;
64
108
  }
65
109
 
66
110
  /** Convert a browser McpServerItem payload into native omp mcp.json shape. */
67
111
  function toNativeServer(ui: McpNativePayloadSource): Record<string, unknown> {
68
112
  const commandArgs = Array.isArray(ui.commandArgs) ? ui.commandArgs.map(String) : [];
69
- const isLink = ui.reachType === 'link' || typeof ui.linkUrl === 'string';
70
- const nativeServer: Record<string, unknown> = isLink
71
- ? { url: String(ui.linkUrl ?? commandArgs[0] ?? '') }
72
- : { command: commandArgs[0] ?? '', ...(commandArgs.length > 1 ? { args: commandArgs.slice(1) } : {}) };
73
- if (Array.isArray(ui.envVars) && ui.envVars.length > 0) {
74
- const env: Record<string, string> = {};
75
- for (const item of ui.envVars) {
76
- if (item && typeof item.key === 'string' && typeof item.value === 'string' && item.value !== '••••••••') {
77
- env[item.key] = item.value;
78
- }
79
- }
80
- if (Object.keys(env).length > 0) nativeServer.env = env;
113
+ const transport = ui.transport === 'sse' ? 'sse' : ui.transport === 'http' || typeof ui.linkUrl === 'string' ? 'http' : 'stdio';
114
+ const nativeServer: Record<string, unknown> = {};
115
+ if (transport === 'stdio') {
116
+ nativeServer.command = commandArgs[0] ?? '';
117
+ if (commandArgs.length > 1) nativeServer.args = commandArgs.slice(1);
118
+ const env = rowsToRecord(Array.isArray(ui.envVars) ? (ui.envVars as McpServerItem['envVars']) : []);
119
+ if (env) nativeServer.env = env;
120
+ if (typeof ui.cwd === 'string' && ui.cwd.trim()) nativeServer.cwd = ui.cwd.trim();
121
+ } else {
122
+ // `type` is required by omp's schema for both remote transports; omitting it
123
+ // makes an SSE endpoint silently load as streamable HTTP.
124
+ nativeServer.type = transport;
125
+ nativeServer.url = String(ui.linkUrl ?? commandArgs[0] ?? '');
126
+ const headers = rowsToRecord(Array.isArray(ui.headers) ? (ui.headers as McpServerItem['headers']) : []);
127
+ if (headers) nativeServer.headers = headers;
81
128
  }
129
+ if (typeof ui.timeout === 'number' && Number.isFinite(ui.timeout) && ui.timeout >= 0) nativeServer.timeout = ui.timeout;
130
+ if (ui.requestIdFormat === 'string' || ui.requestIdFormat === 'number') nativeServer.requestIdFormat = ui.requestIdFormat;
131
+ if (typeof ui.instructions === 'boolean') nativeServer.instructions = ui.instructions;
132
+ const auth = credentialBlock(ui.auth);
133
+ if (auth) nativeServer.auth = auth;
134
+ const oauth = credentialBlock(ui.oauth);
135
+ if (oauth) nativeServer.oauth = oauth;
136
+ if (ui.enabled === false) nativeServer.enabled = false;
82
137
  return nativeServer;
83
138
  }
84
139
 
@@ -121,9 +176,10 @@ export async function loader({ request }: LoaderFunctionArgs) {
121
176
  nativePath: includeNative ? (await readUserMcpConfig()).path : undefined,
122
177
  projectPath: projectPath ?? undefined,
123
178
  });
124
- } catch (error: any) {
179
+ } catch (error) {
125
180
  const mock = isMockMode();
126
- return json({ error: error.message, servers: mock ? DEFAULT_MCP_SERVERS : [], isMock: mock }, { status: 500 });
181
+ const message = error instanceof Error ? error.message : String(error);
182
+ return json({ error: message, servers: mock ? DEFAULT_MCP_SERVERS : [], isMock: mock }, { status: 500 });
127
183
  }
128
184
  }
129
185
 
@@ -246,7 +302,7 @@ export async function action({ request, params }: ActionFunctionArgs) {
246
302
  }
247
303
 
248
304
  return methodNotAllowed({ request, params });
249
- } catch (error: any) {
250
- return json({ error: error.message }, { status: 500 });
305
+ } catch (error) {
306
+ return json({ error: error instanceof Error ? error.message : String(error) }, { status: 500 });
251
307
  }
252
308
  }
@@ -100,4 +100,22 @@ describe('highlightBlockLines', () => {
100
100
  const again = highlightBlockLines('const a = 1;\nconst b = 2;', 'typescript');
101
101
  expect(again).toEqual(lines);
102
102
  });
103
+
104
+ test('a block cached first does not shorten the line path', () => {
105
+ // The two shapes share a key but not a shape: `highlightCode` answers ONE
106
+ // inline string, `highlightLines` one fragment per line. Splitting the
107
+ // block's string gave the line path a single row for a 7-line block, so
108
+ // `NumberedCode` drew seven numbers beside one line — measured on the
109
+ // Ubuntu gate as `Expected length: 7, Received length: 1` in the eval
110
+ // card, whose JSON is drawn by both paths.
111
+ const code = '{\n "a": 1,\n "b": [\n 2,\n 3\n ]\n}';
112
+ const block = highlightBlock(code, 'json');
113
+ expect(block).not.toContain('\n');
114
+
115
+ const lines = highlightBlockLines(code, 'json');
116
+ expect(lines).toHaveLength(7);
117
+ // And the block path still answers its own shape from the same entry.
118
+ expect(highlightBlock(code, 'json')).toBe(block);
119
+ expect(highlightMemoSize()).toBe(1);
120
+ });
103
121
  });
@@ -35,58 +35,83 @@
35
35
  import { isLanguageReady } from '@/shared/lib/code/highlighter-lazy';
36
36
  import { highlightCode, highlightLines, type HighlightLinesOptions } from '@/shared/lib/code/syntax-highlight';
37
37
 
38
+ /**
39
+ * One `(language, code)` entry, holding whichever SHAPES have been asked for.
40
+ *
41
+ * The two callers want different markup for the same code: `highlightCode`
42
+ * answers ONE inline string (`structure: 'inline'`, no newlines), while
43
+ * `highlightLines` answers one fragment per source line. Storing them in one
44
+ * slot made the second reader split the first reader's string — a 7-line JSON
45
+ * block that had already been drawn as a block came back from the line path as
46
+ * a SINGLE row, so `NumberedCode` drew seven numbers beside one line of code.
47
+ * Measured on the Ubuntu gate as `Expected length: 7, Received length: 1` in
48
+ * `Eval.test.tsx`, and it is a real card: the same JSON is drawn by
49
+ * `JsonCodeBlock` (block) and by the eval result (lines).
50
+ */
51
+ interface MemoEntry {
52
+ /** `highlightCode`'s markup: one string, inline structure. */
53
+ block?: string;
54
+ /** `highlightLines`' markup: one fragment per source line. */
55
+ lines?: string[];
56
+ }
57
+
38
58
  /** Per language: a transcript page's worth of distinct blocks. */
39
59
  const MAX_BLOCKS_PER_LANGUAGE = 24;
40
60
  /** Across every language, so a long session cannot grow without bound. */
41
61
  const MAX_CACHED_CHARS = 512 * 1024;
42
62
 
43
- const blocks = new Map<string, Map<string, string>>();
63
+ const blocks = new Map<string, Map<string, MemoEntry>>();
44
64
  let cachedChars = 0;
45
65
 
46
- function bucket(language: string): Map<string, string> {
66
+ function bucket(language: string): Map<string, MemoEntry> {
47
67
  const existing = blocks.get(language);
48
68
  if (existing) return existing;
49
- const created = new Map<string, string>();
69
+ const created = new Map<string, MemoEntry>();
50
70
  blocks.set(language, created);
51
71
  return created;
52
72
  }
53
73
 
74
+ /** What one entry costs against the character budget. */
75
+ function entrySize(entry: MemoEntry | undefined): number {
76
+ if (!entry) return 0;
77
+ return (entry.block?.length ?? 0) + (entry.lines ? entry.lines.join('\n').length : 0);
78
+ }
79
+
54
80
  /** Drop the oldest entry of the first language that has one. */
55
81
  function evictOne(): boolean {
56
82
  for (const entries of blocks.values()) {
57
83
  const oldest = entries.keys().next();
58
84
  if (oldest.done) continue;
59
- const value = entries.get(oldest.value) ?? '';
85
+ cachedChars -= entrySize(entries.get(oldest.value));
60
86
  entries.delete(oldest.value);
61
- cachedChars -= value.length;
62
87
  return true;
63
88
  }
64
89
  return false;
65
90
  }
66
91
 
67
- function remember(language: string, code: string, html: string): void {
92
+ function remember(language: string, code: string, patch: MemoEntry): void {
68
93
  const entries = bucket(language);
69
94
  const previous = entries.get(code);
70
95
  if (previous !== undefined) {
71
96
  entries.delete(code);
72
- cachedChars -= previous.length;
97
+ cachedChars -= entrySize(previous);
73
98
  }
74
- entries.set(code, html);
75
- cachedChars += html.length;
99
+ const merged: MemoEntry = { ...previous, ...patch };
100
+ entries.set(code, merged);
101
+ cachedChars += entrySize(merged);
76
102
  while (entries.size > MAX_BLOCKS_PER_LANGUAGE) {
77
103
  const oldest = entries.keys().next();
78
104
  if (oldest.done) break;
79
- const value = entries.get(oldest.value) ?? '';
105
+ cachedChars -= entrySize(entries.get(oldest.value));
80
106
  entries.delete(oldest.value);
81
- cachedChars -= value.length;
82
107
  }
83
108
  while (cachedChars > MAX_CACHED_CHARS && evictOne()) {
84
109
  // Keep dropping until the budget holds or nothing is left to drop.
85
110
  }
86
111
  }
87
112
 
88
- /** The cached markup for `(language, code)`, or `undefined`. */
89
- export function cachedHighlightBlock(code: string, language: string): string | undefined {
113
+ /** The cached entry for `(language, code)`, moved to the most-recently-used end. */
114
+ function touch(code: string, language: string): MemoEntry | undefined {
90
115
  const entries = blocks.get(language);
91
116
  if (!entries) return undefined;
92
117
  const hit = entries.get(code);
@@ -97,10 +122,14 @@ export function cachedHighlightBlock(code: string, language: string): string | u
97
122
  return hit;
98
123
  }
99
124
 
125
+ /** The cached block markup for `(language, code)`, or `undefined`. */
126
+ export function cachedHighlightBlock(code: string, language: string): string | undefined {
127
+ return touch(code, language)?.block;
128
+ }
129
+
100
130
  /** The cached per-line markup, or `undefined`. */
101
131
  export function cachedHighlightBlockLines(code: string, language: string): string[] | undefined {
102
- const hit = cachedHighlightBlock(code, language);
103
- return hit === undefined ? undefined : hit.split('\n');
132
+ return touch(code, language)?.lines;
104
133
  }
105
134
 
106
135
  function cacheable(language: string, options: HighlightLinesOptions): boolean {
@@ -116,7 +145,7 @@ export function highlightBlock(code: string, language: string, options: Highligh
116
145
  const cached = options.marks?.length ? undefined : cachedHighlightBlock(code, language);
117
146
  if (cached !== undefined) return cached;
118
147
  const html = highlightCode(code, language, options);
119
- if (cacheable(language, options)) remember(language, code, html);
148
+ if (cacheable(language, options)) remember(language, code, { block: html });
120
149
  return html;
121
150
  }
122
151
 
@@ -130,7 +159,7 @@ export function highlightBlockLines(
130
159
  const cached = options.marks?.length ? undefined : cachedHighlightBlockLines(code, language);
131
160
  if (cached !== undefined) return cached;
132
161
  const lines = highlightLines(code, language, options);
133
- if (cacheable(language, options)) remember(language, code, lines.join('\n'));
162
+ if (cacheable(language, options)) remember(language, code, { lines });
134
163
  return lines;
135
164
  }
136
165
 
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Importing MCP server definitions pasted from another tool.
8
+ *
9
+ * Every shape below is a real file format, not a guess:
10
+ * - `{ mcpServers: {...} }` — omp, Claude Code, Claude Desktop, Gemini
11
+ * (`httpUrl` instead of `url` for remote servers);
12
+ * - `{ servers: {...} }` — VS Code `.vscode/mcp.json` (`type: stdio|http|sse`);
13
+ * - `{ mcp: {...} }` — OpenCode (`type: local|remote`, `command` as an array,
14
+ * `environment` instead of `env`).
15
+ *
16
+ * ALL servers in the snippet are imported, not the first one: a pasted file
17
+ * with five servers silently keeping one was the previous behaviour.
18
+ */
19
+
20
+ import type { McpAuthConfig, McpKeyValue, McpOAuthConfig, McpServerItem, McpTransport } from '@/shared/types';
21
+ import { isRecord } from '@/shared/lib/util/guards';
22
+
23
+ function rows(value: unknown, prefix: string): McpKeyValue[] {
24
+ if (!isRecord(value)) return [];
25
+ return Object.entries(value).map(([key, entry], index) => ({
26
+ id: `${prefix}-${index}`,
27
+ key,
28
+ value: typeof entry === 'string' ? entry : String(entry),
29
+ }));
30
+ }
31
+
32
+ function strings(value: unknown): string[] {
33
+ return Array.isArray(value) ? value.map(String) : [];
34
+ }
35
+
36
+ /** The `serverConfig` shape shared by every format, mapped field by field. */
37
+ function toItem(name: string, config: Record<string, unknown>, index: number): McpServerItem {
38
+ const url = typeof config.url === 'string'
39
+ ? config.url
40
+ : typeof config.httpUrl === 'string'
41
+ ? config.httpUrl
42
+ : undefined;
43
+ const declared = typeof config.type === 'string' ? config.type : '';
44
+ const transport: McpTransport = declared === 'sse'
45
+ ? 'sse'
46
+ : declared === 'http' || declared === 'remote' || (url && declared !== 'stdio' && declared !== 'local')
47
+ ? 'http'
48
+ : 'stdio';
49
+
50
+ const commandArgs = Array.isArray(config.command)
51
+ ? config.command.map(String)
52
+ : typeof config.command === 'string'
53
+ ? [config.command, ...strings(config.args)]
54
+ : [];
55
+
56
+ const item: McpServerItem = {
57
+ id: `import-${index}-${name}`,
58
+ name,
59
+ scope: 'every-project',
60
+ enabled: config.enabled !== false,
61
+ transport,
62
+ commandArgs: transport === 'stdio' ? commandArgs : [url ?? ''],
63
+ ...(transport === 'stdio' ? {} : { linkUrl: url ?? '' }),
64
+ envVars: rows(config.env ?? config.environment, `env-${index}`),
65
+ headers: rows(config.headers, `header-${index}`),
66
+ status: 'active',
67
+ };
68
+ if (typeof config.cwd === 'string') item.cwd = config.cwd;
69
+ if (typeof config.timeout === 'number') item.timeout = config.timeout;
70
+ if (typeof config.instructions === 'boolean') item.instructions = config.instructions;
71
+ if (isRecord(config.auth)) item.auth = config.auth as unknown as McpAuthConfig;
72
+ if (isRecord(config.oauth)) item.oauth = config.oauth as unknown as McpOAuthConfig;
73
+ return item;
74
+ }
75
+
76
+ /** The map of server definitions inside a snippet, whatever envelope it uses. */
77
+ function serverMap(parsed: Record<string, unknown>): Record<string, unknown> | null {
78
+ for (const key of ['mcpServers', 'servers', 'mcp']) {
79
+ const value = parsed[key];
80
+ if (isRecord(value)) return value;
81
+ }
82
+ return null;
83
+ }
84
+
85
+ /**
86
+ * Parse a pasted JSON snippet into server rows. Throws with a sentence the
87
+ * dialog shows verbatim; an envelope with no entries is an error, not an empty
88
+ * import that looks like it worked.
89
+ */
90
+ export function parseMcpImport(text: string): McpServerItem[] {
91
+ let parsed: unknown;
92
+ try {
93
+ parsed = JSON.parse(text);
94
+ } catch {
95
+ throw new Error('That is not valid JSON.');
96
+ }
97
+ if (!isRecord(parsed)) throw new Error('Paste a JSON object, not a list or a bare value.');
98
+
99
+ const map = serverMap(parsed);
100
+ if (map) {
101
+ const entries = Object.entries(map).filter((entry): entry is [string, Record<string, unknown>] => isRecord(entry[1]));
102
+ if (entries.length === 0) throw new Error('No server definitions found in that snippet.');
103
+ return entries.map(([name, config], index) => toItem(name, config, index));
104
+ }
105
+
106
+ // A single bare definition: { name?, command } or { name?, url }.
107
+ if (typeof parsed.command !== 'string' && typeof parsed.url !== 'string' && typeof parsed.httpUrl !== 'string') {
108
+ throw new Error('No server definitions found in that snippet.');
109
+ }
110
+ const name = typeof parsed.name === 'string' && parsed.name ? parsed.name : 'imported-mcp-server';
111
+ return [toItem(name, parsed, 0)];
112
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Normalizing one stored MCP row.
8
+ *
9
+ * Rows written before the transport field existed carry `reachType: 'link'`
10
+ * and no `headers`, and a few carry neither list. Reading is the one place
11
+ * that boundary can be absorbed, so every consumer — the settings pane, the
12
+ * session registry, the connection test — sees the same complete shape and no
13
+ * caller has to special-case an old row.
14
+ */
15
+
16
+ import type { McpKeyValue, McpScope, McpServerItem, McpTransport } from '@/shared/types';
17
+ import { isRecord } from '@/shared/lib/util/guards';
18
+
19
+ function rows(value: unknown): McpKeyValue[] {
20
+ if (!Array.isArray(value)) return [];
21
+ return value.flatMap((entry, index) => {
22
+ if (!isRecord(entry)) return [];
23
+ const key = typeof entry.key === 'string' ? entry.key : '';
24
+ const item = typeof entry.id === 'string' ? entry.id : `row-${index}`;
25
+ return [{ id: item, key, value: typeof entry.value === 'string' ? entry.value : String(entry.value ?? '') }];
26
+ });
27
+ }
28
+
29
+ /** Fill every field a form or a transport writer reads; drop the legacy alias. */
30
+ export function normalizeMcpItem(row: unknown): McpServerItem | null {
31
+ if (!isRecord(row)) return null;
32
+ if (typeof row.id !== 'string' || typeof row.name !== 'string' || !row.name) return null;
33
+ const scope: McpScope = row.scope === 'this-project' ? 'this-project' : 'every-project';
34
+ const linkUrl = typeof row.linkUrl === 'string' ? row.linkUrl : undefined;
35
+ const transport: McpTransport =
36
+ row.transport === 'sse' || row.transport === 'http' || row.transport === 'stdio'
37
+ ? row.transport
38
+ : row.reachType === 'link' || linkUrl
39
+ ? 'http'
40
+ : 'stdio';
41
+ const item: McpServerItem = {
42
+ id: row.id,
43
+ name: row.name,
44
+ scope,
45
+ enabled: row.enabled !== false,
46
+ transport,
47
+ commandArgs: Array.isArray(row.commandArgs) ? row.commandArgs.map(String) : [],
48
+ envVars: rows(row.envVars),
49
+ headers: rows(row.headers),
50
+ };
51
+ if (typeof row.projectPath === 'string') item.projectPath = row.projectPath;
52
+ if (linkUrl) item.linkUrl = linkUrl;
53
+ if (typeof row.cwd === 'string') item.cwd = row.cwd;
54
+ if (typeof row.timeout === 'number') item.timeout = row.timeout;
55
+ if (row.requestIdFormat === 'string' || row.requestIdFormat === 'number') item.requestIdFormat = row.requestIdFormat;
56
+ if (typeof row.instructions === 'boolean') item.instructions = row.instructions;
57
+ if (isRecord(row.auth)) item.auth = row.auth as unknown as McpServerItem['auth'];
58
+ if (isRecord(row.oauth)) item.oauth = row.oauth as unknown as McpServerItem['oauth'];
59
+ if (row.status === 'active' || row.status === 'inactive' || row.status === 'error') item.status = row.status;
60
+ return item;
61
+ }
@@ -0,0 +1,37 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The key/value rows the MCP form edits (env vars, HTTP headers) and the
8
+ * `Record<string, string>` omp's `mcp.json` stores. One conversion pair, so the
9
+ * form, the writer and the session registry cannot disagree about which rows
10
+ * are real: a blank key is a half-typed row, and the redaction sentinel is a
11
+ * display placeholder that must never be written or injected.
12
+ */
13
+
14
+ import type { McpKeyValue } from '@/shared/types';
15
+
16
+ /** The value the server sends instead of a credential it will not disclose. */
17
+ export const REDACTED_SENTINEL = '••••••••';
18
+
19
+ /** Rows → a record, dropping blank keys and the redaction sentinel. */
20
+ export function rowsToRecord(rows: readonly McpKeyValue[] | undefined): Record<string, string> | undefined {
21
+ const record: Record<string, string> = {};
22
+ for (const row of rows ?? []) {
23
+ const key = row?.key?.trim();
24
+ if (!key || !row.value || row.value === REDACTED_SENTINEL) continue;
25
+ record[key] = row.value;
26
+ }
27
+ return Object.keys(record).length > 0 ? record : undefined;
28
+ }
29
+
30
+ /** A native record → rows, stringifying non-string values the way omp does. */
31
+ export function recordToRows(record: Record<string, unknown>, prefix: string): McpKeyValue[] {
32
+ return Object.entries(record).map(([key, value], index) => ({
33
+ id: `${prefix}-${index}`,
34
+ key,
35
+ value: typeof value === 'string' ? value : String(value),
36
+ }));
37
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * Import + normalizer contracts.
8
+ *
9
+ * The import parser decides what a pasted snippet becomes, and every other tool
10
+ * writes a different envelope: keeping only the first server, or dropping a
11
+ * remote entry's `type`, is the difference between a working import and one the
12
+ * user has to repair by hand. The normalizer is the read boundary for rows
13
+ * written before `transport` existed.
14
+ */
15
+
16
+ import { describe, expect, test } from 'bun:test';
17
+ import { parseMcpImport } from '@/shared/lib/mcp/import';
18
+ import { normalizeMcpItem } from '@/shared/lib/mcp/item';
19
+ import { recordToRows, rowsToRecord } from '@/shared/lib/mcp/key-value';
20
+
21
+ describe('parseMcpImport', () => {
22
+ test('every server in an mcpServers block is imported', () => {
23
+ const servers = parseMcpImport(JSON.stringify({
24
+ mcpServers: {
25
+ one: { command: 'a', args: ['x'] },
26
+ two: { command: 'b' },
27
+ },
28
+ }));
29
+ expect(servers.map((server) => server.name)).toEqual(['one', 'two']);
30
+ expect(servers[0]).toMatchObject({ transport: 'stdio', commandArgs: ['a', 'x'] });
31
+ });
32
+
33
+ test('VS Code `.vscode/mcp.json` (`servers`, typed transports) is understood', () => {
34
+ const servers = parseMcpImport(JSON.stringify({
35
+ servers: {
36
+ local: { type: 'stdio', command: 'npx', args: ['-y', 'x'], env: { K: 'V' } },
37
+ remote: { type: 'http', url: 'https://x/mcp', headers: { Authorization: 'Bearer t' } },
38
+ legacy: { type: 'sse', url: 'https://y/sse' },
39
+ },
40
+ }));
41
+ expect(servers.map((server) => server.transport)).toEqual(['stdio', 'http', 'sse']);
42
+ expect(servers[1]).toMatchObject({
43
+ linkUrl: 'https://x/mcp',
44
+ headers: [{ id: 'header-1-0', key: 'Authorization', value: 'Bearer t' }],
45
+ });
46
+ });
47
+
48
+ test('OpenCode (`mcp`, `type: local|remote`, command array, environment) is understood', () => {
49
+ const servers = parseMcpImport(JSON.stringify({
50
+ mcp: {
51
+ local: { type: 'local', command: ['bunx', 'server'], environment: { TOKEN: 't' } },
52
+ remote: { type: 'remote', url: 'https://z/mcp' },
53
+ },
54
+ }));
55
+ expect(servers[0]).toMatchObject({
56
+ transport: 'stdio',
57
+ commandArgs: ['bunx', 'server'],
58
+ envVars: [{ id: 'env-0-0', key: 'TOKEN', value: 't' }],
59
+ });
60
+ expect(servers[1]).toMatchObject({ transport: 'http', linkUrl: 'https://z/mcp' });
61
+ });
62
+
63
+ test('Gemini `httpUrl` is read as a remote URL', () => {
64
+ const servers = parseMcpImport(JSON.stringify({
65
+ mcpServers: { g: { httpUrl: 'https://gemini/mcp' } },
66
+ }));
67
+ expect(servers[0]).toMatchObject({ transport: 'http', linkUrl: 'https://gemini/mcp' });
68
+ });
69
+
70
+ test('a bare definition is one server; a blank envelope and bad JSON are errors', () => {
71
+ expect(parseMcpImport(JSON.stringify({ name: 'solo', command: 'x' }))).toHaveLength(1);
72
+ expect(() => parseMcpImport(JSON.stringify({ mcpServers: {} }))).toThrow('No server definitions found');
73
+ expect(() => parseMcpImport('{nope')).toThrow('That is not valid JSON.');
74
+ expect(() => parseMcpImport('[1]')).toThrow('Paste a JSON object');
75
+ });
76
+ });
77
+
78
+ describe('normalizeMcpItem', () => {
79
+ test('a legacy reachType row becomes an explicit transport with empty lists', () => {
80
+ expect(normalizeMcpItem({ id: 'a', name: 'a', scope: 'every-project', reachType: 'link', linkUrl: 'https://x' }))
81
+ .toMatchObject({ transport: 'http', enabled: true, headers: [], envVars: [], commandArgs: [] });
82
+ expect(normalizeMcpItem({ id: 'b', name: 'b', reachType: 'command' })).toMatchObject({ transport: 'stdio' });
83
+ });
84
+
85
+ test('a malformed row is dropped rather than guessed at', () => {
86
+ expect(normalizeMcpItem({ name: 'x' })).toBeNull();
87
+ expect(normalizeMcpItem({ id: 'x' })).toBeNull();
88
+ expect(normalizeMcpItem(null)).toBeNull();
89
+ });
90
+
91
+ test('credential blocks and schema fields survive normalization', () => {
92
+ expect(normalizeMcpItem({
93
+ id: 'c',
94
+ name: 'c',
95
+ transport: 'sse',
96
+ timeout: 10,
97
+ instructions: false,
98
+ auth: { type: 'oauth' },
99
+ })).toMatchObject({ transport: 'sse', timeout: 10, instructions: false, auth: { type: 'oauth' } });
100
+ });
101
+ });
102
+
103
+ describe('key/value rows', () => {
104
+ test('blank keys and the redaction sentinel are never written', () => {
105
+ expect(rowsToRecord([
106
+ { id: '1', key: ' ', value: 'x' },
107
+ { id: '2', key: 'TOKEN', value: '••••••••' },
108
+ { id: '3', key: 'OK', value: 'v' },
109
+ ])).toEqual({ OK: 'v' });
110
+ expect(rowsToRecord([])).toBeUndefined();
111
+ });
112
+
113
+ test('a native record becomes rows with stable ids', () => {
114
+ expect(recordToRows({ A: 1, B: 'two' }, 'env-0')).toEqual([
115
+ { id: 'env-0-0', key: 'A', value: '1' },
116
+ { id: 'env-0-1', key: 'B', value: 'two' },
117
+ ]);
118
+ });
119
+ });