@lobu/gateway 2.8.0 → 3.0.6

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 (175) hide show
  1. package/package.json +2 -2
  2. package/src/__tests__/agent-config-routes.test.ts +254 -0
  3. package/src/__tests__/agent-history-routes.test.ts +72 -0
  4. package/src/__tests__/agent-routes.test.ts +68 -0
  5. package/src/__tests__/agent-schedules-routes.test.ts +59 -0
  6. package/src/__tests__/agent-settings-store.test.ts +323 -0
  7. package/src/__tests__/chat-instance-manager-slack.test.ts +204 -0
  8. package/src/__tests__/chat-response-bridge.test.ts +131 -0
  9. package/src/__tests__/config-memory-plugins.test.ts +92 -0
  10. package/src/__tests__/config-request-store.test.ts +127 -0
  11. package/src/__tests__/connection-routes.test.ts +144 -0
  12. package/src/__tests__/core-services-store-selection.test.ts +92 -0
  13. package/src/__tests__/docker-deployment.test.ts +1211 -0
  14. package/src/__tests__/embedded-deployment.test.ts +342 -0
  15. package/src/__tests__/grant-store.test.ts +148 -0
  16. package/src/__tests__/http-proxy.test.ts +281 -0
  17. package/src/__tests__/instruction-service.test.ts +37 -0
  18. package/src/__tests__/link-buttons.test.ts +112 -0
  19. package/src/__tests__/lobu.test.ts +32 -0
  20. package/src/__tests__/mcp-config-service.test.ts +347 -0
  21. package/src/__tests__/mcp-proxy.test.ts +696 -0
  22. package/src/__tests__/message-handler-bridge.test.ts +17 -0
  23. package/src/__tests__/model-selection.test.ts +172 -0
  24. package/src/__tests__/oauth-templates.test.ts +39 -0
  25. package/src/__tests__/platform-adapter-slack-send.test.ts +114 -0
  26. package/src/__tests__/platform-helpers-model-resolution.test.ts +253 -0
  27. package/src/__tests__/provider-inheritance.test.ts +212 -0
  28. package/src/__tests__/routes/cli-auth.test.ts +337 -0
  29. package/src/__tests__/routes/interactions.test.ts +121 -0
  30. package/src/__tests__/secret-proxy.test.ts +85 -0
  31. package/src/__tests__/session-manager.test.ts +572 -0
  32. package/src/__tests__/setup.ts +133 -0
  33. package/src/__tests__/skill-and-mcp-registry.test.ts +203 -0
  34. package/src/__tests__/slack-routes.test.ts +161 -0
  35. package/src/__tests__/system-config-resolver.test.ts +75 -0
  36. package/src/__tests__/system-message-limiter.test.ts +89 -0
  37. package/src/__tests__/system-skills-service.test.ts +362 -0
  38. package/src/__tests__/transcription-service.test.ts +222 -0
  39. package/src/__tests__/utils/rate-limiter.test.ts +102 -0
  40. package/src/__tests__/worker-connection-manager.test.ts +497 -0
  41. package/src/__tests__/worker-job-router.test.ts +722 -0
  42. package/src/api/index.ts +1 -0
  43. package/src/api/platform.ts +292 -0
  44. package/src/api/response-renderer.ts +157 -0
  45. package/src/auth/agent-metadata-store.ts +168 -0
  46. package/src/auth/api-auth-middleware.ts +69 -0
  47. package/src/auth/api-key-provider-module.ts +213 -0
  48. package/src/auth/base-provider-module.ts +201 -0
  49. package/src/auth/chatgpt/chatgpt-oauth-module.ts +185 -0
  50. package/src/auth/chatgpt/device-code-client.ts +218 -0
  51. package/src/auth/chatgpt/index.ts +1 -0
  52. package/src/auth/claude/oauth-module.ts +280 -0
  53. package/src/auth/cli/token-service.ts +249 -0
  54. package/src/auth/external/client.ts +560 -0
  55. package/src/auth/external/device-code-client.ts +225 -0
  56. package/src/auth/mcp/config-service.ts +392 -0
  57. package/src/auth/mcp/proxy.ts +1088 -0
  58. package/src/auth/mcp/string-substitution.ts +17 -0
  59. package/src/auth/mcp/tool-cache.ts +90 -0
  60. package/src/auth/oauth/base-client.ts +267 -0
  61. package/src/auth/oauth/client.ts +153 -0
  62. package/src/auth/oauth/credentials.ts +7 -0
  63. package/src/auth/oauth/providers.ts +69 -0
  64. package/src/auth/oauth/state-store.ts +150 -0
  65. package/src/auth/oauth-templates.ts +179 -0
  66. package/src/auth/provider-catalog.ts +220 -0
  67. package/src/auth/provider-model-options.ts +41 -0
  68. package/src/auth/settings/agent-settings-store.ts +565 -0
  69. package/src/auth/settings/auth-profiles-manager.ts +216 -0
  70. package/src/auth/settings/index.ts +12 -0
  71. package/src/auth/settings/model-preference-store.ts +52 -0
  72. package/src/auth/settings/model-selection.ts +135 -0
  73. package/src/auth/settings/resolved-settings-view.ts +298 -0
  74. package/src/auth/settings/template-utils.ts +44 -0
  75. package/src/auth/settings/token-service.ts +88 -0
  76. package/src/auth/system-env-store.ts +98 -0
  77. package/src/auth/user-agents-store.ts +68 -0
  78. package/src/channels/binding-service.ts +214 -0
  79. package/src/channels/index.ts +4 -0
  80. package/src/cli/gateway.ts +1304 -0
  81. package/src/cli/index.ts +74 -0
  82. package/src/commands/built-in-commands.ts +80 -0
  83. package/src/commands/command-dispatcher.ts +94 -0
  84. package/src/commands/command-reply-adapters.ts +27 -0
  85. package/src/config/file-loader.ts +618 -0
  86. package/src/config/index.ts +588 -0
  87. package/src/config/network-allowlist.ts +71 -0
  88. package/src/connections/chat-instance-manager.ts +1284 -0
  89. package/src/connections/chat-response-bridge.ts +618 -0
  90. package/src/connections/index.ts +7 -0
  91. package/src/connections/interaction-bridge.ts +831 -0
  92. package/src/connections/message-handler-bridge.ts +415 -0
  93. package/src/connections/platform-auth-methods.ts +15 -0
  94. package/src/connections/types.ts +84 -0
  95. package/src/gateway/connection-manager.ts +291 -0
  96. package/src/gateway/index.ts +700 -0
  97. package/src/gateway/job-router.ts +201 -0
  98. package/src/gateway-main.ts +200 -0
  99. package/src/index.ts +41 -0
  100. package/src/infrastructure/queue/index.ts +12 -0
  101. package/src/infrastructure/queue/queue-producer.ts +148 -0
  102. package/src/infrastructure/queue/redis-queue.ts +361 -0
  103. package/src/infrastructure/queue/types.ts +133 -0
  104. package/src/infrastructure/redis/system-message-limiter.ts +94 -0
  105. package/src/interactions/config-request-store.ts +198 -0
  106. package/src/interactions.ts +363 -0
  107. package/src/lobu.ts +311 -0
  108. package/src/metrics/prometheus.ts +159 -0
  109. package/src/modules/module-system.ts +179 -0
  110. package/src/orchestration/base-deployment-manager.ts +900 -0
  111. package/src/orchestration/deployment-utils.ts +98 -0
  112. package/src/orchestration/impl/docker-deployment.ts +620 -0
  113. package/src/orchestration/impl/embedded-deployment.ts +268 -0
  114. package/src/orchestration/impl/index.ts +8 -0
  115. package/src/orchestration/impl/k8s/deployment.ts +1061 -0
  116. package/src/orchestration/impl/k8s/helpers.ts +610 -0
  117. package/src/orchestration/impl/k8s/index.ts +1 -0
  118. package/src/orchestration/index.ts +333 -0
  119. package/src/orchestration/message-consumer.ts +584 -0
  120. package/src/orchestration/scheduled-wakeup.ts +704 -0
  121. package/src/permissions/approval-policy.ts +36 -0
  122. package/src/permissions/grant-store.ts +219 -0
  123. package/src/platform/file-handler.ts +66 -0
  124. package/src/platform/link-buttons.ts +57 -0
  125. package/src/platform/renderer-utils.ts +44 -0
  126. package/src/platform/response-renderer.ts +84 -0
  127. package/src/platform/unified-thread-consumer.ts +187 -0
  128. package/src/platform.ts +318 -0
  129. package/src/proxy/http-proxy.ts +752 -0
  130. package/src/proxy/proxy-manager.ts +81 -0
  131. package/src/proxy/secret-proxy.ts +402 -0
  132. package/src/proxy/token-refresh-job.ts +143 -0
  133. package/src/routes/internal/audio.ts +141 -0
  134. package/src/routes/internal/device-auth.ts +566 -0
  135. package/src/routes/internal/files.ts +226 -0
  136. package/src/routes/internal/history.ts +69 -0
  137. package/src/routes/internal/images.ts +127 -0
  138. package/src/routes/internal/interactions.ts +84 -0
  139. package/src/routes/internal/middleware.ts +23 -0
  140. package/src/routes/internal/schedule.ts +226 -0
  141. package/src/routes/internal/types.ts +22 -0
  142. package/src/routes/openapi-auto.ts +239 -0
  143. package/src/routes/public/agent-access.ts +23 -0
  144. package/src/routes/public/agent-config.ts +675 -0
  145. package/src/routes/public/agent-history.ts +422 -0
  146. package/src/routes/public/agent-schedules.ts +296 -0
  147. package/src/routes/public/agent.ts +1086 -0
  148. package/src/routes/public/agents.ts +373 -0
  149. package/src/routes/public/channels.ts +191 -0
  150. package/src/routes/public/cli-auth.ts +883 -0
  151. package/src/routes/public/connections.ts +574 -0
  152. package/src/routes/public/landing.ts +16 -0
  153. package/src/routes/public/oauth.ts +147 -0
  154. package/src/routes/public/settings-auth.ts +104 -0
  155. package/src/routes/public/slack.ts +173 -0
  156. package/src/routes/shared/agent-ownership.ts +101 -0
  157. package/src/routes/shared/token-verifier.ts +34 -0
  158. package/src/services/core-services.ts +1053 -0
  159. package/src/services/image-generation-service.ts +257 -0
  160. package/src/services/instruction-service.ts +318 -0
  161. package/src/services/mcp-registry.ts +94 -0
  162. package/src/services/platform-helpers.ts +287 -0
  163. package/src/services/session-manager.ts +262 -0
  164. package/src/services/settings-resolver.ts +74 -0
  165. package/src/services/system-config-resolver.ts +90 -0
  166. package/src/services/system-skills-service.ts +229 -0
  167. package/src/services/transcription-service.ts +684 -0
  168. package/src/session.ts +110 -0
  169. package/src/spaces/index.ts +1 -0
  170. package/src/spaces/space-resolver.ts +17 -0
  171. package/src/stores/in-memory-agent-store.ts +403 -0
  172. package/src/stores/redis-agent-store.ts +279 -0
  173. package/src/utils/public-url.ts +44 -0
  174. package/src/utils/rate-limiter.ts +94 -0
  175. package/tsconfig.json +33 -0
@@ -0,0 +1,696 @@
1
+ import {
2
+ afterAll,
3
+ beforeAll,
4
+ beforeEach,
5
+ describe,
6
+ expect,
7
+ test,
8
+ } from "bun:test";
9
+ import { generateWorkerToken } from "@lobu/core";
10
+ import { MockMessageQueue } from "@lobu/core/testing";
11
+ import { McpProxy } from "../auth/mcp/proxy";
12
+ import { McpToolCache } from "../auth/mcp/tool-cache";
13
+ import { GrantStore } from "../permissions/grant-store";
14
+
15
+ const TEST_ENCRYPTION_KEY =
16
+ "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
17
+
18
+ interface HttpMcpServerConfig {
19
+ id: string;
20
+ upstreamUrl: string;
21
+ oauth?: unknown;
22
+ inputs?: unknown[];
23
+ headers?: Record<string, string>;
24
+ loginUrl?: string;
25
+ resource?: string;
26
+ }
27
+
28
+ interface McpConfigSource {
29
+ getHttpServer(
30
+ id: string,
31
+ agentId?: string
32
+ ): Promise<HttpMcpServerConfig | undefined>;
33
+ getAllHttpServers(
34
+ agentId?: string
35
+ ): Promise<Map<string, HttpMcpServerConfig>>;
36
+ }
37
+
38
+ function createMockConfigSource(
39
+ servers: Record<string, HttpMcpServerConfig>
40
+ ): McpConfigSource {
41
+ return {
42
+ getHttpServer: async (id) => servers[id],
43
+ getAllHttpServers: async () => new Map(Object.entries(servers)),
44
+ };
45
+ }
46
+
47
+ function mockUpstreamFetch(responseData: any) {
48
+ globalThis.fetch = async () => {
49
+ return new Response(JSON.stringify(responseData), {
50
+ status: 200,
51
+ headers: { "Content-Type": "application/json" },
52
+ });
53
+ };
54
+ }
55
+
56
+ const TEST_SERVER: HttpMcpServerConfig = {
57
+ id: "test-mcp",
58
+ upstreamUrl: "http://upstream:9000/mcp",
59
+ };
60
+
61
+ let originalEnv: string | undefined;
62
+ let validToken: string;
63
+ let originalFetch: typeof fetch;
64
+
65
+ beforeAll(() => {
66
+ originalEnv = process.env.ENCRYPTION_KEY;
67
+ process.env.ENCRYPTION_KEY = TEST_ENCRYPTION_KEY;
68
+ validToken = generateWorkerToken("user1", "conv1", "deploy1", {
69
+ channelId: "ch1",
70
+ agentId: "agent1",
71
+ });
72
+ originalFetch = globalThis.fetch;
73
+ });
74
+
75
+ afterAll(() => {
76
+ if (originalEnv !== undefined) process.env.ENCRYPTION_KEY = originalEnv;
77
+ else delete process.env.ENCRYPTION_KEY;
78
+ globalThis.fetch = originalFetch;
79
+ });
80
+
81
+ describe("McpProxy", () => {
82
+ let queue: MockMessageQueue;
83
+
84
+ beforeEach(() => {
85
+ queue = new MockMessageQueue();
86
+ globalThis.fetch = originalFetch;
87
+ });
88
+
89
+ // ---------- Auth tests ----------
90
+
91
+ describe("authentication", () => {
92
+ test("rejects missing token", async () => {
93
+ const configSource = createMockConfigSource({
94
+ "test-mcp": TEST_SERVER,
95
+ });
96
+ const proxy = new McpProxy(configSource, queue as any);
97
+ const app = proxy.getApp();
98
+
99
+ const res = await app.request("/test-mcp/tools", { method: "GET" });
100
+ expect(res.status).toBe(401);
101
+ const body = await res.json();
102
+ expect(body.error).toContain("Invalid authentication token");
103
+ });
104
+
105
+ test("rejects invalid token", async () => {
106
+ const configSource = createMockConfigSource({
107
+ "test-mcp": TEST_SERVER,
108
+ });
109
+ const proxy = new McpProxy(configSource, queue as any);
110
+ const app = proxy.getApp();
111
+
112
+ const res = await app.request("/test-mcp/tools", {
113
+ method: "GET",
114
+ headers: { Authorization: "Bearer invalid-garbage" },
115
+ });
116
+ expect(res.status).toBe(401);
117
+ });
118
+
119
+ test("accepts Bearer header", async () => {
120
+ const configSource = createMockConfigSource({
121
+ "test-mcp": TEST_SERVER,
122
+ });
123
+ const proxy = new McpProxy(configSource, queue as any);
124
+ const app = proxy.getApp();
125
+
126
+ mockUpstreamFetch({
127
+ jsonrpc: "2.0",
128
+ id: 1,
129
+ result: { tools: [{ name: "tool1" }] },
130
+ });
131
+
132
+ const res = await app.request("/test-mcp/tools", {
133
+ method: "GET",
134
+ headers: { Authorization: `Bearer ${validToken}` },
135
+ });
136
+ expect(res.status).toBe(200);
137
+ });
138
+
139
+ test("accepts workerToken query param", async () => {
140
+ const configSource = createMockConfigSource({
141
+ "test-mcp": TEST_SERVER,
142
+ });
143
+ const proxy = new McpProxy(configSource, queue as any);
144
+ const app = proxy.getApp();
145
+
146
+ mockUpstreamFetch({
147
+ jsonrpc: "2.0",
148
+ id: 1,
149
+ result: { tools: [{ name: "tool1" }] },
150
+ });
151
+
152
+ const res = await app.request(
153
+ `/test-mcp/tools?workerToken=${validToken}`,
154
+ { method: "GET" }
155
+ );
156
+ expect(res.status).toBe(200);
157
+ });
158
+ });
159
+
160
+ // ---------- GET /:mcpId/tools ----------
161
+
162
+ describe("GET /:mcpId/tools", () => {
163
+ test("returns tools from upstream", async () => {
164
+ const configSource = createMockConfigSource({
165
+ "test-mcp": TEST_SERVER,
166
+ });
167
+ const proxy = new McpProxy(configSource, queue as any);
168
+ const app = proxy.getApp();
169
+
170
+ const tools = [
171
+ { name: "read_file", description: "Read a file" },
172
+ { name: "write_file", description: "Write a file" },
173
+ ];
174
+ mockUpstreamFetch({
175
+ jsonrpc: "2.0",
176
+ id: 1,
177
+ result: { tools },
178
+ });
179
+
180
+ const res = await app.request("/test-mcp/tools", {
181
+ method: "GET",
182
+ headers: { Authorization: `Bearer ${validToken}` },
183
+ });
184
+ expect(res.status).toBe(200);
185
+ const body = await res.json();
186
+ expect(body.tools).toHaveLength(2);
187
+ expect(body.tools[0].name).toBe("read_file");
188
+ expect(body.tools[1].name).toBe("write_file");
189
+ });
190
+
191
+ test("returns 404 for unknown MCP", async () => {
192
+ const configSource = createMockConfigSource({});
193
+ const proxy = new McpProxy(configSource, queue as any);
194
+ const app = proxy.getApp();
195
+
196
+ const res = await app.request("/nonexistent/tools", {
197
+ method: "GET",
198
+ headers: { Authorization: `Bearer ${validToken}` },
199
+ });
200
+ expect(res.status).toBe(404);
201
+ const body = await res.json();
202
+ expect(body.error).toContain("not found");
203
+ });
204
+
205
+ test("returns 502 on upstream error", async () => {
206
+ const configSource = createMockConfigSource({
207
+ "test-mcp": TEST_SERVER,
208
+ });
209
+ const proxy = new McpProxy(configSource, queue as any);
210
+ const app = proxy.getApp();
211
+
212
+ globalThis.fetch = async () => {
213
+ throw new Error("Connection refused");
214
+ };
215
+
216
+ const res = await app.request("/test-mcp/tools", {
217
+ method: "GET",
218
+ headers: { Authorization: `Bearer ${validToken}` },
219
+ });
220
+ expect(res.status).toBe(502);
221
+ const body = await res.json();
222
+ expect(body.error).toContain("Failed to connect");
223
+ });
224
+
225
+ test("caches tools on second request", async () => {
226
+ const configSource = createMockConfigSource({
227
+ "test-mcp": TEST_SERVER,
228
+ });
229
+ const toolCache = new McpToolCache(queue.getRedisClient());
230
+ const proxy = new McpProxy(configSource, queue as any, toolCache);
231
+ const app = proxy.getApp();
232
+
233
+ let fetchCount = 0;
234
+ globalThis.fetch = async () => {
235
+ fetchCount++;
236
+ return new Response(
237
+ JSON.stringify({
238
+ jsonrpc: "2.0",
239
+ id: 1,
240
+ result: { tools: [{ name: "cached_tool" }] },
241
+ }),
242
+ { status: 200, headers: { "Content-Type": "application/json" } }
243
+ );
244
+ };
245
+
246
+ // First request fetches from upstream
247
+ const res1 = await app.request("/test-mcp/tools", {
248
+ method: "GET",
249
+ headers: { Authorization: `Bearer ${validToken}` },
250
+ });
251
+ expect(res1.status).toBe(200);
252
+ const firstFetchCount = fetchCount;
253
+
254
+ // Second request should use cache
255
+ const res2 = await app.request("/test-mcp/tools", {
256
+ method: "GET",
257
+ headers: { Authorization: `Bearer ${validToken}` },
258
+ });
259
+ expect(res2.status).toBe(200);
260
+ const body = await res2.json();
261
+ expect(body.tools[0].name).toBe("cached_tool");
262
+ // fetch should NOT have been called again
263
+ expect(fetchCount).toBe(firstFetchCount);
264
+ });
265
+ });
266
+
267
+ // ---------- POST /:mcpId/tools/:toolName ----------
268
+
269
+ describe("POST /:mcpId/tools/:toolName", () => {
270
+ test("forwards call and returns result", async () => {
271
+ const configSource = createMockConfigSource({
272
+ "test-mcp": TEST_SERVER,
273
+ });
274
+ const proxy = new McpProxy(configSource, queue as any);
275
+ const app = proxy.getApp();
276
+
277
+ mockUpstreamFetch({
278
+ jsonrpc: "2.0",
279
+ id: 1,
280
+ result: {
281
+ content: [{ type: "text", text: "Hello world" }],
282
+ isError: false,
283
+ },
284
+ });
285
+
286
+ const res = await app.request("/test-mcp/tools/my_tool", {
287
+ method: "POST",
288
+ headers: {
289
+ Authorization: `Bearer ${validToken}`,
290
+ "Content-Type": "application/json",
291
+ },
292
+ body: JSON.stringify({ arg1: "value1" }),
293
+ });
294
+ expect(res.status).toBe(200);
295
+ const body = await res.json();
296
+ expect(body.content).toHaveLength(1);
297
+ expect(body.content[0].text).toBe("Hello world");
298
+ expect(body.isError).toBe(false);
299
+ });
300
+
301
+ test("returns 400 for invalid JSON body", async () => {
302
+ const configSource = createMockConfigSource({
303
+ "test-mcp": TEST_SERVER,
304
+ });
305
+ const proxy = new McpProxy(configSource, queue as any);
306
+ const app = proxy.getApp();
307
+
308
+ const res = await app.request("/test-mcp/tools/my_tool", {
309
+ method: "POST",
310
+ headers: {
311
+ Authorization: `Bearer ${validToken}`,
312
+ "Content-Type": "application/json",
313
+ },
314
+ body: "not valid json {{{",
315
+ });
316
+ expect(res.status).toBe(400);
317
+ const body = await res.json();
318
+ expect(body.error).toContain("Invalid JSON");
319
+ });
320
+
321
+ test("returns 404 for unknown MCP", async () => {
322
+ const configSource = createMockConfigSource({});
323
+ const proxy = new McpProxy(configSource, queue as any);
324
+ const app = proxy.getApp();
325
+
326
+ const res = await app.request("/nonexistent/tools/my_tool", {
327
+ method: "POST",
328
+ headers: {
329
+ Authorization: `Bearer ${validToken}`,
330
+ "Content-Type": "application/json",
331
+ },
332
+ body: JSON.stringify({}),
333
+ });
334
+ expect(res.status).toBe(404);
335
+ });
336
+
337
+ test("returns 502 on upstream error", async () => {
338
+ const configSource = createMockConfigSource({
339
+ "test-mcp": TEST_SERVER,
340
+ });
341
+ const proxy = new McpProxy(configSource, queue as any);
342
+ const app = proxy.getApp();
343
+
344
+ globalThis.fetch = async () => {
345
+ throw new Error("Connection refused");
346
+ };
347
+
348
+ const res = await app.request("/test-mcp/tools/my_tool", {
349
+ method: "POST",
350
+ headers: {
351
+ Authorization: `Bearer ${validToken}`,
352
+ "Content-Type": "application/json",
353
+ },
354
+ body: JSON.stringify({}),
355
+ });
356
+ expect(res.status).toBe(502);
357
+ const body = await res.json();
358
+ expect(body.error).toContain("Failed to connect");
359
+ });
360
+ });
361
+
362
+ // ---------- Session re-init ----------
363
+
364
+ describe("session re-initialization", () => {
365
+ test("retries on 'Server not initialized' error", async () => {
366
+ const configSource = createMockConfigSource({
367
+ "test-mcp": TEST_SERVER,
368
+ });
369
+ const proxy = new McpProxy(configSource, queue as any);
370
+ const app = proxy.getApp();
371
+
372
+ let callCount = 0;
373
+ globalThis.fetch = async () => {
374
+ callCount++;
375
+ // The first call is the tool call that triggers the error.
376
+ // After that, reinitializeSession sends initialize + notifications/initialized (2 calls).
377
+ // Then the retry tool call is the 4th call.
378
+ if (callCount === 1) {
379
+ return new Response(
380
+ JSON.stringify({
381
+ jsonrpc: "2.0",
382
+ id: 1,
383
+ error: { code: -32000, message: "Server not initialized" },
384
+ }),
385
+ { status: 200, headers: { "Content-Type": "application/json" } }
386
+ );
387
+ }
388
+ // Re-init calls (initialize + notifications/initialized) and retry
389
+ return new Response(
390
+ JSON.stringify({
391
+ jsonrpc: "2.0",
392
+ id: 1,
393
+ result: {
394
+ content: [{ type: "text", text: "Success after re-init" }],
395
+ },
396
+ }),
397
+ { status: 200, headers: { "Content-Type": "application/json" } }
398
+ );
399
+ };
400
+
401
+ const res = await app.request("/test-mcp/tools/my_tool", {
402
+ method: "POST",
403
+ headers: {
404
+ Authorization: `Bearer ${validToken}`,
405
+ "Content-Type": "application/json",
406
+ },
407
+ body: JSON.stringify({}),
408
+ });
409
+ expect(res.status).toBe(200);
410
+ const body = await res.json();
411
+ expect(body.content[0].text).toBe("Success after re-init");
412
+ // At least 4 fetch calls: original + initialize + notify + retry
413
+ expect(callCount).toBeGreaterThanOrEqual(4);
414
+ });
415
+ });
416
+
417
+ // ---------- Tool approval ----------
418
+
419
+ describe("tool approval", () => {
420
+ function createProxyWithGrants(
421
+ servers: Record<string, HttpMcpServerConfig>
422
+ ) {
423
+ const configSource = createMockConfigSource(servers);
424
+ const toolCache = new McpToolCache(queue.getRedisClient());
425
+ const grantStore = new GrantStore(queue.getRedisClient());
426
+ const proxy = new McpProxy(
427
+ configSource,
428
+ queue as any,
429
+ toolCache,
430
+ grantStore
431
+ );
432
+ return { proxy, toolCache, grantStore, configSource };
433
+ }
434
+
435
+ test("blocks destructive tool without grant", async () => {
436
+ const { proxy, toolCache } = createProxyWithGrants({
437
+ "test-mcp": TEST_SERVER,
438
+ });
439
+ const app = proxy.getApp();
440
+
441
+ // Pre-populate cache with a tool that has no annotations (default destructive)
442
+ await toolCache.set("test-mcp", [{ name: "dangerous_tool" }], "agent1");
443
+
444
+ const res = await app.request("/test-mcp/tools/dangerous_tool", {
445
+ method: "POST",
446
+ headers: {
447
+ Authorization: `Bearer ${validToken}`,
448
+ "Content-Type": "application/json",
449
+ },
450
+ body: JSON.stringify({}),
451
+ });
452
+ expect(res.status).toBe(403);
453
+ const body = await res.json();
454
+ expect(body.isError).toBe(true);
455
+ expect(body.content[0].text).toContain("requires approval");
456
+ });
457
+
458
+ test("allows with grant", async () => {
459
+ const { proxy, toolCache, grantStore } = createProxyWithGrants({
460
+ "test-mcp": TEST_SERVER,
461
+ });
462
+ const app = proxy.getApp();
463
+
464
+ // Pre-populate cache with a tool that has no annotations (default destructive)
465
+ await toolCache.set("test-mcp", [{ name: "dangerous_tool" }], "agent1");
466
+
467
+ // Grant access
468
+ await grantStore.grant(
469
+ "agent1",
470
+ "/mcp/test-mcp/tools/dangerous_tool",
471
+ null
472
+ );
473
+
474
+ mockUpstreamFetch({
475
+ jsonrpc: "2.0",
476
+ id: 1,
477
+ result: {
478
+ content: [{ type: "text", text: "Executed" }],
479
+ isError: false,
480
+ },
481
+ });
482
+
483
+ const res = await app.request("/test-mcp/tools/dangerous_tool", {
484
+ method: "POST",
485
+ headers: {
486
+ Authorization: `Bearer ${validToken}`,
487
+ "Content-Type": "application/json",
488
+ },
489
+ body: JSON.stringify({}),
490
+ });
491
+ expect(res.status).toBe(200);
492
+ const body = await res.json();
493
+ expect(body.content[0].text).toBe("Executed");
494
+ });
495
+
496
+ test("allows readOnlyHint=true without grant", async () => {
497
+ const { proxy, toolCache } = createProxyWithGrants({
498
+ "test-mcp": TEST_SERVER,
499
+ });
500
+ const app = proxy.getApp();
501
+
502
+ // Pre-populate cache with a read-only tool
503
+ await toolCache.set(
504
+ "test-mcp",
505
+ [{ name: "read_tool", annotations: { readOnlyHint: true } }],
506
+ "agent1"
507
+ );
508
+
509
+ mockUpstreamFetch({
510
+ jsonrpc: "2.0",
511
+ id: 1,
512
+ result: {
513
+ content: [{ type: "text", text: "Read data" }],
514
+ isError: false,
515
+ },
516
+ });
517
+
518
+ const res = await app.request("/test-mcp/tools/read_tool", {
519
+ method: "POST",
520
+ headers: {
521
+ Authorization: `Bearer ${validToken}`,
522
+ "Content-Type": "application/json",
523
+ },
524
+ body: JSON.stringify({}),
525
+ });
526
+ expect(res.status).toBe(200);
527
+ });
528
+
529
+ test("allows destructiveHint=false without grant", async () => {
530
+ const { proxy, toolCache } = createProxyWithGrants({
531
+ "test-mcp": TEST_SERVER,
532
+ });
533
+ const app = proxy.getApp();
534
+
535
+ // Pre-populate cache with a non-destructive tool
536
+ await toolCache.set(
537
+ "test-mcp",
538
+ [{ name: "safe_tool", annotations: { destructiveHint: false } }],
539
+ "agent1"
540
+ );
541
+
542
+ mockUpstreamFetch({
543
+ jsonrpc: "2.0",
544
+ id: 1,
545
+ result: {
546
+ content: [{ type: "text", text: "Safe result" }],
547
+ isError: false,
548
+ },
549
+ });
550
+
551
+ const res = await app.request("/test-mcp/tools/safe_tool", {
552
+ method: "POST",
553
+ headers: {
554
+ Authorization: `Bearer ${validToken}`,
555
+ "Content-Type": "application/json",
556
+ },
557
+ body: JSON.stringify({}),
558
+ });
559
+ expect(res.status).toBe(200);
560
+ });
561
+ });
562
+
563
+ // ---------- GET /tools (list all) ----------
564
+
565
+ describe("GET /tools", () => {
566
+ test("lists tools from all MCPs", async () => {
567
+ const configSource = createMockConfigSource({
568
+ mcp1: {
569
+ id: "mcp1",
570
+ upstreamUrl: "http://upstream1:9000/mcp",
571
+ },
572
+ mcp2: {
573
+ id: "mcp2",
574
+ upstreamUrl: "http://upstream2:9000/mcp",
575
+ },
576
+ });
577
+ const proxy = new McpProxy(configSource, queue as any);
578
+ const app = proxy.getApp();
579
+
580
+ globalThis.fetch = async (url: string | URL | Request) => {
581
+ const urlStr =
582
+ typeof url === "string"
583
+ ? url
584
+ : url instanceof URL
585
+ ? url.href
586
+ : url.url;
587
+ const tools = urlStr.includes("upstream1")
588
+ ? [{ name: "tool_a" }]
589
+ : [{ name: "tool_b" }];
590
+ return new Response(
591
+ JSON.stringify({
592
+ jsonrpc: "2.0",
593
+ id: 1,
594
+ result: { tools },
595
+ }),
596
+ { status: 200, headers: { "Content-Type": "application/json" } }
597
+ );
598
+ };
599
+
600
+ const res = await app.request("/tools", {
601
+ method: "GET",
602
+ headers: { Authorization: `Bearer ${validToken}` },
603
+ });
604
+ expect(res.status).toBe(200);
605
+ const body = await res.json();
606
+ expect(body.mcpServers.mcp1.tools[0].name).toBe("tool_a");
607
+ expect(body.mcpServers.mcp2.tools[0].name).toBe("tool_b");
608
+ });
609
+
610
+ test("tolerates individual MCP failures", async () => {
611
+ const configSource = createMockConfigSource({
612
+ good: {
613
+ id: "good",
614
+ upstreamUrl: "http://good-upstream:9000/mcp",
615
+ },
616
+ bad: {
617
+ id: "bad",
618
+ upstreamUrl: "http://bad-upstream:9000/mcp",
619
+ },
620
+ });
621
+ const proxy = new McpProxy(configSource, queue as any);
622
+ const app = proxy.getApp();
623
+
624
+ globalThis.fetch = async (url: string | URL | Request) => {
625
+ const urlStr =
626
+ typeof url === "string"
627
+ ? url
628
+ : url instanceof URL
629
+ ? url.href
630
+ : url.url;
631
+ if (urlStr.includes("bad-upstream")) {
632
+ throw new Error("Connection refused");
633
+ }
634
+ return new Response(
635
+ JSON.stringify({
636
+ jsonrpc: "2.0",
637
+ id: 1,
638
+ result: { tools: [{ name: "working_tool" }] },
639
+ }),
640
+ { status: 200, headers: { "Content-Type": "application/json" } }
641
+ );
642
+ };
643
+
644
+ const res = await app.request("/tools", {
645
+ method: "GET",
646
+ headers: { Authorization: `Bearer ${validToken}` },
647
+ });
648
+ expect(res.status).toBe(200);
649
+ const body = await res.json();
650
+ // The "good" MCP should still have its tools
651
+ expect(body.mcpServers.good.tools[0].name).toBe("working_tool");
652
+ // The "bad" MCP should be absent (empty tools are filtered out)
653
+ expect(body.mcpServers.bad).toBeUndefined();
654
+ });
655
+ });
656
+
657
+ // ---------- isMcpRequest ----------
658
+
659
+ describe("isMcpRequest", () => {
660
+ test("returns true with x-mcp-id header", async () => {
661
+ const configSource = createMockConfigSource({});
662
+ const proxy = new McpProxy(configSource, queue as any);
663
+
664
+ // Use a wrapper Hono app to get a real Context object
665
+ const { Hono } = await import("hono");
666
+ const wrapper = new Hono();
667
+ let result = false;
668
+ wrapper.all("/*", (c) => {
669
+ result = proxy.isMcpRequest(c);
670
+ return c.json({ result });
671
+ });
672
+
673
+ await wrapper.request("/anything", {
674
+ method: "GET",
675
+ headers: { "x-mcp-id": "some-mcp" },
676
+ });
677
+ expect(result).toBe(true);
678
+ });
679
+
680
+ test("returns false without x-mcp-id header", async () => {
681
+ const configSource = createMockConfigSource({});
682
+ const proxy = new McpProxy(configSource, queue as any);
683
+
684
+ const { Hono } = await import("hono");
685
+ const wrapper = new Hono();
686
+ let result = true;
687
+ wrapper.all("/*", (c) => {
688
+ result = proxy.isMcpRequest(c);
689
+ return c.json({ result });
690
+ });
691
+
692
+ await wrapper.request("/anything", { method: "GET" });
693
+ expect(result).toBe(false);
694
+ });
695
+ });
696
+ });
@@ -0,0 +1,17 @@
1
+ import { describe, expect, test } from "bun:test";
2
+ import { isSenderAllowed } from "../connections/message-handler-bridge";
3
+
4
+ describe("isSenderAllowed", () => {
5
+ test("allows everyone when allowFrom is not configured", () => {
6
+ expect(isSenderAllowed(undefined, "user-1")).toBe(true);
7
+ });
8
+
9
+ test("blocks everyone when allowFrom is an empty array", () => {
10
+ expect(isSenderAllowed([], "user-1")).toBe(false);
11
+ });
12
+
13
+ test("only allows listed users when allowFrom is configured", () => {
14
+ expect(isSenderAllowed(["user-1"], "user-1")).toBe(true);
15
+ expect(isSenderAllowed(["user-1"], "user-2")).toBe(false);
16
+ });
17
+ });