@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
@@ -0,0 +1,277 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The native `mcp.json` mapping and write contract.
8
+ *
9
+ * Pinned because each decides on untrusted or hand-written input:
10
+ * - `nativeToServerItem` maps a native entry to Kabmo shape; a wrong transport
11
+ * or a dropped field makes the UI edit a server it cannot describe.
12
+ * - `writeUserMcpServer` must preserve credentials the browser redacted, record
13
+ * enablement in the same place omp reads it, and reject a name outside the
14
+ * file's key grammar.
15
+ */
16
+
17
+ import { afterAll, describe, expect, test } from 'bun:test';
18
+ import fs from 'fs';
19
+ import { tmpdir } from 'os';
20
+ import { join } from 'path';
21
+
22
+ import {
23
+ MCP_FILENAMES,
24
+ nativeToServerItem,
25
+ readProjectMcpConfig,
26
+ readUserMcpConfig,
27
+ redactEnvVars,
28
+ resolveProjectMcpConfig,
29
+ } from '@/server/lib/omp/config/mcp';
30
+ import { deleteUserMcpServer, writeUserMcpServer } from '@/server/lib/omp/config/mcp-write';
31
+
32
+ const roots: string[] = [];
33
+
34
+ async function tempDir(): Promise<string> {
35
+ const dir = await fs.promises.mkdtemp(join(tmpdir(), 'omp-mcp-config-'));
36
+ roots.push(dir);
37
+ return dir;
38
+ }
39
+
40
+ afterAll(async () => {
41
+ for (const root of roots) await fs.promises.rm(root, { recursive: true, force: true });
42
+ });
43
+
44
+ describe('nativeToServerItem', () => {
45
+ test('a command server becomes a stdio item with split args', () => {
46
+ const item = nativeToServerItem('fs', { command: 'npx', args: ['-y', '@mcp/fs'] }, 2, true);
47
+ expect(item).toEqual({
48
+ id: 'omp-user-fs',
49
+ name: 'fs',
50
+ scope: 'every-project',
51
+ enabled: true,
52
+ transport: 'stdio',
53
+ commandArgs: ['npx', '-y', '@mcp/fs'],
54
+ linkUrl: undefined,
55
+ envVars: [],
56
+ headers: [],
57
+ status: undefined,
58
+ });
59
+ });
60
+
61
+ test('a url server becomes an http item and its env vars are stringified', () => {
62
+ const item = nativeToServerItem('web', { url: 'https://mcp.example/sse', env: { A: 1, B: 'two' } }, 0, false);
63
+ expect(item.transport).toBe('http');
64
+ expect(item.linkUrl).toBe('https://mcp.example/sse');
65
+ expect(item.commandArgs).toEqual(['https://mcp.example/sse']);
66
+ expect(item.envVars).toEqual([
67
+ { id: 'env-0-0', key: 'A', value: '1' },
68
+ { id: 'env-0-1', key: 'B', value: 'two' },
69
+ ]);
70
+ });
71
+
72
+ test('every schema field survives the mapping', () => {
73
+ const item = nativeToServerItem(
74
+ 'legacy',
75
+ {
76
+ type: 'sse',
77
+ url: 'https://x/sse',
78
+ headers: { Authorization: 'Bearer x' },
79
+ timeout: 5000,
80
+ requestIdFormat: 'string',
81
+ instructions: false,
82
+ auth: { type: 'oauth', credentialId: 'c1' },
83
+ oauth: { scope: 'read' },
84
+ },
85
+ 0,
86
+ true,
87
+ );
88
+ expect(item.transport).toBe('sse');
89
+ expect(item.headers).toEqual([{ id: 'header-0-0', key: 'Authorization', value: 'Bearer x' }]);
90
+ expect(item.timeout).toBe(5000);
91
+ expect(item.requestIdFormat).toBe('string');
92
+ expect(item.instructions).toBe(false);
93
+ expect(item.auth).toEqual({ type: 'oauth', credentialId: 'c1' });
94
+ expect(item.oauth).toEqual({ scope: 'read' });
95
+ });
96
+
97
+ test('a project-scoped item carries the project id and path', () => {
98
+ const item = nativeToServerItem('fs', { command: 'x' }, 1, true, { path: '/proj' });
99
+ expect(item.id).toBe('omp-project-fs');
100
+ expect(item.scope).toBe('this-project');
101
+ expect(item.projectPath).toBe('/proj');
102
+ });
103
+
104
+ test('an empty command yields no args rather than a blank entry', () => {
105
+ expect(nativeToServerItem('blank', {}, 0, true).commandArgs).toEqual([]);
106
+ });
107
+ });
108
+
109
+ describe('redactEnvVars', () => {
110
+ test('values whose key looks sensitive are masked; others are untouched', () => {
111
+ const vars = [
112
+ { key: 'API_KEY', value: 'sk-secret' },
113
+ { key: 'authToken', value: 'tok' },
114
+ { key: 'db_password', value: 'pw' },
115
+ { key: 'PLAIN', value: 'visible' },
116
+ ];
117
+ const out = redactEnvVars(vars);
118
+ expect(out.map((v) => v.value)).toEqual(['••••••••', '••••••••', '••••••••', 'visible']);
119
+ // Non-sensitive rows keep their identity (no needless copies).
120
+ expect(out[3]).toBe(vars[3]);
121
+ });
122
+ });
123
+
124
+ describe('mcp file read/write', () => {
125
+ test('readUserMcpConfig on a missing file is empty and does not throw', async () => {
126
+ const path = join(await tempDir(), 'mcp.json');
127
+ expect(await readUserMcpConfig(path)).toEqual({ path, servers: [], disabledServers: [], enabledServers: [] });
128
+ });
129
+
130
+ test('readUserMcpConfig sorts servers by name and keeps only string disables', async () => {
131
+ const path = join(await tempDir(), 'mcp.json');
132
+ await Bun.write(path, JSON.stringify({
133
+ mcpServers: { zeta: { command: 'z' }, alpha: { url: 'https://a' } },
134
+ disabledServers: ['zeta', 7, null],
135
+ }));
136
+ const config = await readUserMcpConfig(path);
137
+ expect(config.servers.map((s) => s.name)).toEqual(['alpha', 'zeta']);
138
+ expect(config.disabledServers).toEqual(['zeta']);
139
+ });
140
+
141
+ test('readUserMcpConfig reports malformed content as an error field', async () => {
142
+ const path = join(await tempDir(), 'mcp.json');
143
+ await Bun.write(path, '[1,2,3]');
144
+ expect((await readUserMcpConfig(path)).error).toBe('configuration must contain a JSON object');
145
+
146
+ await Bun.write(path, '{"mcpServers": 5}');
147
+ expect((await readUserMcpConfig(path)).error).toBe('mcpServers must be an object');
148
+
149
+ await Bun.write(path, '{not json');
150
+ expect((await readUserMcpConfig(path)).error).toBeTruthy();
151
+ });
152
+
153
+ test('resolveProjectMcpConfig picks the first existing candidate, else the default', async () => {
154
+ const dir = await tempDir();
155
+ expect((await resolveProjectMcpConfig(dir)).path).toBe(join(dir, MCP_FILENAMES[0]));
156
+
157
+ await Bun.write(join(dir, 'mcp.json'), '{}');
158
+ expect((await resolveProjectMcpConfig(dir)).path).toBe(join(dir, 'mcp.json'));
159
+
160
+ await fs.promises.mkdir(join(dir, '.omp'), { recursive: true });
161
+ await Bun.write(join(dir, '.omp', 'mcp.json'), '{}');
162
+ expect((await resolveProjectMcpConfig(dir)).path).toBe(join(dir, '.omp', 'mcp.json'));
163
+ });
164
+
165
+ test('readProjectMcpConfig reads the resolved project file', async () => {
166
+ const dir = await tempDir();
167
+ await fs.promises.mkdir(join(dir, '.omp'), { recursive: true });
168
+ await Bun.write(join(dir, '.omp', 'mcp.json'), '{"mcpServers":{"p":{"command":"x"}}}');
169
+ expect((await readProjectMcpConfig(dir)).servers.map((s) => s.name)).toEqual(['p']);
170
+ });
171
+
172
+ test('both project candidates are read, first name wins', async () => {
173
+ const dir = await tempDir();
174
+ await fs.promises.mkdir(join(dir, '.omp'), { recursive: true });
175
+ await Bun.write(join(dir, '.omp', 'mcp.json'), '{"mcpServers":{"shared":{"command":"primary"}}}');
176
+ await Bun.write(join(dir, '.omp', '.mcp.json'), '{"mcpServers":{"shared":{"command":"secondary"},"extra":{"command":"y"}}}');
177
+
178
+ const config = await readProjectMcpConfig(dir);
179
+ expect(config.servers.map((s) => s.name)).toEqual(['extra', 'shared']);
180
+ expect(config.servers.find((s) => s.name === 'shared')?.config.command).toBe('primary');
181
+ });
182
+
183
+ test('the user-scope dot-file is read alongside mcp.json', async () => {
184
+ const dir = await tempDir();
185
+ await Bun.write(join(dir, 'mcp.json'), '{"mcpServers":{"main":{"command":"a"}}}');
186
+ await Bun.write(join(dir, '.mcp.json'), '{"mcpServers":{"dot":{"url":"https://dot"}}}');
187
+
188
+ const config = await readUserMcpConfig(join(dir, 'mcp.json'));
189
+ expect(config.servers.map((s) => s.name)).toEqual(['dot', 'main']);
190
+ });
191
+
192
+ test('writeUserMcpServer rejects a name outside the grammar and a non-object', async () => {
193
+ const path = join(await tempDir(), 'mcp.json');
194
+ await expect(writeUserMcpServer('bad name', { command: 'x' }, path)).rejects.toThrow('Invalid server name');
195
+ await expect(writeUserMcpServer('ok', 'not an object' as unknown as Record<string, unknown>, path)).rejects.toThrow(
196
+ 'Server configuration must be an object',
197
+ );
198
+ });
199
+
200
+ test('writeUserMcpServer preserves redacted env/headers the payload omitted', async () => {
201
+ const path = join(await tempDir(), 'mcp.json');
202
+ await Bun.write(path, JSON.stringify({
203
+ mcpServers: { srv: { command: 'old', env: { KEY: 'sk-secret' }, headers: { Auth: 'Bearer x' } } },
204
+ }));
205
+ await writeUserMcpServer('srv', { command: 'new' }, path);
206
+
207
+ const raw = JSON.parse(await fs.promises.readFile(path, 'utf8'));
208
+ expect(raw.mcpServers.srv).toEqual({
209
+ command: 'new',
210
+ env: { KEY: 'sk-secret' },
211
+ headers: { Auth: 'Bearer x' },
212
+ });
213
+ });
214
+
215
+ test('writeUserMcpServer rename moves the entry and keeps its credentials', async () => {
216
+ const path = join(await tempDir(), 'mcp.json');
217
+ await Bun.write(path, JSON.stringify({ mcpServers: { old: { command: 'x', env: { K: 'v' } } } }));
218
+ await writeUserMcpServer('new', { command: 'x' }, path, 'old');
219
+
220
+ const raw = JSON.parse(await fs.promises.readFile(path, 'utf8'));
221
+ expect(Object.keys(raw.mcpServers)).toEqual(['new']);
222
+ expect(raw.mcpServers.new.env).toEqual({ K: 'v' });
223
+ });
224
+
225
+ test('a credential block merges per field instead of erasing the secret', async () => {
226
+ const path = join(await tempDir(), 'mcp.json');
227
+ await Bun.write(path, JSON.stringify({
228
+ mcpServers: { srv: { type: 'http', url: 'https://x', oauth: { clientId: 'id', clientSecret: 'shh' } } },
229
+ }));
230
+ await writeUserMcpServer('srv', { type: 'http', url: 'https://x', oauth: { scope: 'read' } }, path);
231
+
232
+ const raw = JSON.parse(await fs.promises.readFile(path, 'utf8'));
233
+ expect(raw.mcpServers.srv.oauth).toEqual({ clientId: 'id', clientSecret: 'shh', scope: 'read' });
234
+ });
235
+
236
+ test('a disabled write records enabled:false AND the user denylist', async () => {
237
+ const path = join(await tempDir(), 'mcp.json');
238
+ await writeUserMcpServer('srv', { command: 'x', enabled: false }, path);
239
+
240
+ const raw = JSON.parse(await fs.promises.readFile(path, 'utf8'));
241
+ expect(raw.mcpServers.srv).toEqual({ command: 'x', enabled: false });
242
+ expect(raw.disabledServers).toEqual(['srv']);
243
+
244
+ // Re-enabling clears both, so the checkbox cannot flip back on reload.
245
+ await writeUserMcpServer('srv', { command: 'x' }, path);
246
+ const after = JSON.parse(await fs.promises.readFile(path, 'utf8'));
247
+ expect(after.mcpServers.srv).toEqual({ command: 'x' });
248
+ expect(after.disabledServers).toBeUndefined();
249
+ });
250
+
251
+ test('a remote entry keeps type/url/headers', async () => {
252
+ const path = join(await tempDir(), 'mcp.json');
253
+ await writeUserMcpServer(
254
+ 'remote',
255
+ { type: 'sse', url: 'https://x/sse', headers: { Authorization: 'Bearer t' }, timeout: 1000 },
256
+ path,
257
+ );
258
+ const raw = JSON.parse(await fs.promises.readFile(path, 'utf8'));
259
+ expect(raw.mcpServers.remote).toEqual({
260
+ type: 'sse',
261
+ url: 'https://x/sse',
262
+ headers: { Authorization: 'Bearer t' },
263
+ timeout: 1000,
264
+ });
265
+ });
266
+
267
+ test('deleteUserMcpServer removes an entry and refuses a missing one', async () => {
268
+ const path = join(await tempDir(), 'mcp.json');
269
+ await Bun.write(path, JSON.stringify({ mcpServers: { a: { command: 'x' } } }));
270
+ await deleteUserMcpServer('a', path);
271
+ expect(JSON.parse(await fs.promises.readFile(path, 'utf8')).mcpServers).toEqual({});
272
+
273
+ await expect(deleteUserMcpServer('ghost', path)).rejects.toThrow('MCP server was not found');
274
+ const missing = join(await tempDir(), 'nope.json');
275
+ await expect(deleteUserMcpServer('a', missing)).rejects.toThrow('MCP server was not found');
276
+ });
277
+ });
@@ -0,0 +1,36 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The pieces both halves of the native MCP config module need: the file shape,
8
+ * the name grammar, the user-scope path, and the string-list reader. Split out
9
+ * so the reader (`mcp.ts`) and the writer (`mcp-write.ts`) depend on one
10
+ * definition instead of on each other.
11
+ */
12
+
13
+ import { join } from 'path';
14
+ import { getAgentDir } from '@/server/lib/omp/core/paths';
15
+
16
+ export const MAX_MCP_CONFIG_BYTES = 512 * 1024;
17
+
18
+ /** omp's own server-name grammar; a name outside it is refused by the CLI too. */
19
+ export const SERVER_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/;
20
+
21
+ export type McpServer = Record<string, unknown>;
22
+ export type McpFile = Record<string, unknown> & {
23
+ mcpServers?: Record<string, McpServer>;
24
+ disabledServers?: string[];
25
+ enabledServers?: string[];
26
+ };
27
+
28
+ /** The user-scope file omp reads: `~/.omp/agent/mcp.json`. */
29
+ export function userMcpConfigPath(): string {
30
+ return join(getAgentDir(), 'mcp.json');
31
+ }
32
+
33
+ /** The string members of a list-shaped value, ignoring everything else. */
34
+ export function stringsIn(value: unknown): string[] {
35
+ return Array.isArray(value) ? value.filter((item): item is string => typeof item === 'string') : [];
36
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The MCP handshake's own vocabulary: the initialize frame, the protocol
8
+ * version this client speaks, and the readers for both reply shapes (a plain
9
+ * JSON body and an SSE frame).
10
+ *
11
+ * Shared so the stdio and remote probes cannot drift into asking different
12
+ * questions or reading different answers.
13
+ */
14
+
15
+ import { isRecord } from '@/shared/lib/util/guards';
16
+ import type { McpTransport } from '@/shared/types';
17
+
18
+ export const PROTOCOL_VERSION = '2025-06-18';
19
+ export const CLIENT_INFO = { name: 'kabmo', version: '0.0.1' };
20
+
21
+ /** The answer the settings pane renders for one connection test. */
22
+ export interface McpTestResult {
23
+ ok: boolean;
24
+ transport: McpTransport;
25
+ protocolVersion?: string;
26
+ serverInfo?: { name?: string; version?: string };
27
+ toolCount?: number;
28
+ durationMs: number;
29
+ error?: string;
30
+ }
31
+
32
+ export interface HandshakeOutcome {
33
+ protocolVersion?: string;
34
+ serverInfo?: { name?: string; version?: string };
35
+ toolCount?: number;
36
+ }
37
+
38
+ export function parseServerInfo(value: unknown): { name?: string; version?: string } | undefined {
39
+ if (!isRecord(value)) return undefined;
40
+ const info: { name?: string; version?: string } = {};
41
+ if (typeof value.name === 'string') info.name = value.name;
42
+ if (typeof value.version === 'string') info.version = value.version;
43
+ return info.name !== undefined || info.version !== undefined ? info : undefined;
44
+ }
45
+
46
+ export function describeError(value: unknown): string {
47
+ if (typeof value === 'string' && value.length > 0) return value;
48
+ if (isRecord(value) && typeof value.message === 'string') return value.message;
49
+ try {
50
+ return JSON.stringify(value);
51
+ } catch {
52
+ return 'Unknown error';
53
+ }
54
+ }
55
+
56
+ export function initializeRequest(): Record<string, unknown> {
57
+ return {
58
+ jsonrpc: '2.0',
59
+ id: 1,
60
+ method: 'initialize',
61
+ params: { protocolVersion: PROTOCOL_VERSION, capabilities: {}, clientInfo: CLIENT_INFO },
62
+ };
63
+ }
64
+
65
+ /** The `initialize` result, whether the server wrapped it in a JSON-RPC envelope or not. */
66
+ export function extractInitializeOutcome(payload: unknown): HandshakeOutcome {
67
+ const result = isRecord(payload) && isRecord(payload.result) ? payload.result : payload;
68
+ if (!isRecord(result)) return {};
69
+ return {
70
+ protocolVersion: typeof result.protocolVersion === 'string' ? result.protocolVersion : undefined,
71
+ serverInfo: parseServerInfo(result.serverInfo),
72
+ };
73
+ }
74
+
75
+ /** The first parseable `data:` line of an SSE body. */
76
+ export function extractSseData(text: string): unknown {
77
+ for (const rawLine of text.split(/\r?\n/)) {
78
+ const line = rawLine.trim();
79
+ if (!line.startsWith('data:')) continue;
80
+ const data = line.slice(5).trim();
81
+ if (!data || data === '[DONE]') continue;
82
+ try {
83
+ return JSON.parse(data);
84
+ } catch {
85
+ // skip malformed frames; keep scanning for the first parseable data line
86
+ }
87
+ }
88
+ return undefined;
89
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * @license
3
+ * SPDX-License-Identifier: MIT
4
+ */
5
+
6
+ /**
7
+ * The remote half of the MCP connection test: streamable HTTP and legacy SSE.
8
+ *
9
+ * They are separate probes because they are separate handshakes. HTTP POSTs
10
+ * `initialize` and reads the answer from the response; SSE opens a stream, waits
11
+ * for the server to announce a POST endpoint, sends `initialize` there, and
12
+ * reads the answer back off the same stream. Sending an HTTP POST to an SSE
13
+ * endpoint — the previous behaviour — cannot succeed.
14
+ */
15
+
16
+ import type { McpTestResult } from '@/server/lib/omp/config/mcp-test-protocol';
17
+ import {
18
+ describeError,
19
+ extractInitializeOutcome,
20
+ extractSseData,
21
+ initializeRequest,
22
+ type HandshakeOutcome,
23
+ } from '@/server/lib/omp/config/mcp-test-protocol';
24
+ import { isRecord } from '@/shared/lib/util/guards';
25
+
26
+ const LINK_TIMEOUT_MS = 10_000;
27
+
28
+ export async function runLinkTest(url: string, headers: Record<string, string>): Promise<McpTestResult> {
29
+ const startedAt = Date.now();
30
+ try {
31
+ const response = await fetch(url, {
32
+ method: 'POST',
33
+ headers: { ...headers, 'Content-Type': 'application/json', Accept: 'application/json, text/event-stream' },
34
+ body: JSON.stringify(initializeRequest()),
35
+ signal: AbortSignal.timeout(LINK_TIMEOUT_MS),
36
+ });
37
+ if (!response.ok) {
38
+ return {
39
+ ok: false,
40
+ transport: 'http',
41
+ durationMs: Date.now() - startedAt,
42
+ error: `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`,
43
+ };
44
+ }
45
+ const contentType = (response.headers.get('content-type') ?? '').toLowerCase();
46
+ const payload = contentType.includes('text/event-stream')
47
+ ? extractSseData(await response.text())
48
+ : await response.json();
49
+ const outcome = extractInitializeOutcome(payload);
50
+ return {
51
+ ok: true,
52
+ transport: 'http',
53
+ protocolVersion: outcome.protocolVersion,
54
+ serverInfo: outcome.serverInfo,
55
+ durationMs: Date.now() - startedAt,
56
+ };
57
+ } catch (error) {
58
+ return {
59
+ ok: false,
60
+ transport: 'http',
61
+ durationMs: Date.now() - startedAt,
62
+ error: error instanceof Error ? error.message : 'Connection failed',
63
+ };
64
+ }
65
+ }
66
+
67
+ interface SseFrame {
68
+ event: string;
69
+ data: string;
70
+ }
71
+
72
+ function parseSseFrame(frame: string): SseFrame {
73
+ let event = 'message';
74
+ const data: string[] = [];
75
+ for (const line of frame.split(/\r?\n/)) {
76
+ if (line.startsWith('event:')) event = line.slice(6).trim();
77
+ else if (line.startsWith('data:')) data.push(line.slice(5).trim());
78
+ }
79
+ return { event, data: data.join('\n') };
80
+ }
81
+
82
+ export async function runSseTest(url: string, headers: Record<string, string>): Promise<McpTestResult> {
83
+ const startedAt = Date.now();
84
+ const controller = new AbortController();
85
+ const timer = setTimeout(() => controller.abort(), LINK_TIMEOUT_MS);
86
+ try {
87
+ const response = await fetch(url, { headers: { ...headers, Accept: 'text/event-stream' }, signal: controller.signal });
88
+ if (!response.ok || !response.body) {
89
+ return {
90
+ ok: false,
91
+ transport: 'sse',
92
+ durationMs: Date.now() - startedAt,
93
+ error: `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ''}`,
94
+ };
95
+ }
96
+ const reader = response.body.getReader();
97
+ const decoder = new TextDecoder();
98
+ let buffer = '';
99
+ let endpoint: string | null = null;
100
+ let outcome: HandshakeOutcome | null = null;
101
+ while (!outcome) {
102
+ const { value, done } = await reader.read();
103
+ if (done) break;
104
+ buffer += decoder.decode(value, { stream: true });
105
+ let boundary = buffer.indexOf('\n\n');
106
+ while (boundary >= 0) {
107
+ const frame = parseSseFrame(buffer.slice(0, boundary));
108
+ buffer = buffer.slice(boundary + 2);
109
+ if (frame.event === 'endpoint' && frame.data) {
110
+ endpoint = new URL(frame.data, url).toString();
111
+ void fetch(endpoint, {
112
+ method: 'POST',
113
+ headers: { ...headers, 'Content-Type': 'application/json' },
114
+ body: JSON.stringify(initializeRequest()),
115
+ signal: controller.signal,
116
+ }).catch(() => undefined);
117
+ } else if (frame.data) {
118
+ let payload: unknown;
119
+ try {
120
+ payload = JSON.parse(frame.data);
121
+ } catch {
122
+ payload = undefined;
123
+ }
124
+ if (isRecord(payload) && (payload.id === 1 || payload.id === '1')) {
125
+ if (payload.error !== undefined) {
126
+ return {
127
+ ok: false,
128
+ transport: 'sse',
129
+ durationMs: Date.now() - startedAt,
130
+ error: `MCP initialize failed: ${describeError(payload.error)}`,
131
+ };
132
+ }
133
+ outcome = extractInitializeOutcome(payload);
134
+ }
135
+ }
136
+ boundary = buffer.indexOf('\n\n');
137
+ }
138
+ }
139
+ if (!outcome) {
140
+ return {
141
+ ok: false,
142
+ transport: 'sse',
143
+ durationMs: Date.now() - startedAt,
144
+ error: endpoint
145
+ ? 'The SSE stream closed before initialize answered'
146
+ : 'The SSE stream did not announce a POST endpoint',
147
+ };
148
+ }
149
+ return {
150
+ ok: true,
151
+ transport: 'sse',
152
+ protocolVersion: outcome.protocolVersion,
153
+ serverInfo: outcome.serverInfo,
154
+ durationMs: Date.now() - startedAt,
155
+ };
156
+ } catch (error) {
157
+ return {
158
+ ok: false,
159
+ transport: 'sse',
160
+ durationMs: Date.now() - startedAt,
161
+ error: error instanceof Error ? error.message : 'Connection failed',
162
+ };
163
+ } finally {
164
+ clearTimeout(timer);
165
+ controller.abort();
166
+ }
167
+ }