@vibescope/mcp-server 0.5.0 → 0.5.1

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 (161) hide show
  1. package/CHANGELOG.md +84 -84
  2. package/README.md +194 -194
  3. package/dist/api-client/tasks.d.ts +1 -0
  4. package/dist/cli-init.js +21 -21
  5. package/dist/cli.js +26 -26
  6. package/dist/handlers/tasks.js +7 -1
  7. package/dist/handlers/tool-docs.js +1216 -1216
  8. package/dist/index.js +73 -73
  9. package/dist/templates/agent-guidelines.d.ts +1 -1
  10. package/dist/templates/agent-guidelines.js +205 -205
  11. package/dist/templates/help-content.js +1621 -1621
  12. package/dist/tools/bodies-of-work.js +6 -6
  13. package/dist/tools/cloud-agents.js +22 -22
  14. package/dist/tools/milestones.js +2 -2
  15. package/dist/tools/requests.js +1 -1
  16. package/dist/tools/session.js +11 -11
  17. package/dist/tools/sprints.js +9 -9
  18. package/dist/tools/tasks.js +43 -35
  19. package/dist/tools/worktrees.js +14 -14
  20. package/dist/utils.js +11 -11
  21. package/docs/TOOLS.md +2687 -2685
  22. package/package.json +53 -53
  23. package/scripts/generate-docs.ts +212 -212
  24. package/scripts/version-bump.ts +203 -203
  25. package/src/api-client/blockers.ts +86 -86
  26. package/src/api-client/bodies-of-work.ts +194 -194
  27. package/src/api-client/chat.ts +50 -50
  28. package/src/api-client/connectors.ts +152 -152
  29. package/src/api-client/cost.ts +185 -185
  30. package/src/api-client/decisions.ts +87 -87
  31. package/src/api-client/deployment.ts +313 -313
  32. package/src/api-client/discovery.ts +81 -81
  33. package/src/api-client/fallback.ts +52 -52
  34. package/src/api-client/file-checkouts.ts +115 -115
  35. package/src/api-client/findings.ts +100 -100
  36. package/src/api-client/git-issues.ts +88 -88
  37. package/src/api-client/ideas.ts +112 -112
  38. package/src/api-client/index.ts +592 -592
  39. package/src/api-client/milestones.ts +83 -83
  40. package/src/api-client/organizations.ts +185 -185
  41. package/src/api-client/progress.ts +94 -94
  42. package/src/api-client/project.ts +181 -181
  43. package/src/api-client/requests.ts +54 -54
  44. package/src/api-client/session.ts +220 -220
  45. package/src/api-client/sprints.ts +227 -227
  46. package/src/api-client/subtasks.ts +57 -57
  47. package/src/api-client/tasks.ts +451 -450
  48. package/src/api-client/types.ts +32 -32
  49. package/src/api-client/validation.ts +60 -60
  50. package/src/api-client/worktrees.ts +53 -53
  51. package/src/api-client.test.ts +847 -847
  52. package/src/api-client.ts +2728 -2728
  53. package/src/cli-init.ts +558 -558
  54. package/src/cli.test.ts +284 -284
  55. package/src/cli.ts +204 -204
  56. package/src/handlers/__test-setup__.ts +240 -240
  57. package/src/handlers/__test-utils__.ts +89 -89
  58. package/src/handlers/blockers.test.ts +468 -468
  59. package/src/handlers/blockers.ts +172 -172
  60. package/src/handlers/bodies-of-work.test.ts +704 -704
  61. package/src/handlers/bodies-of-work.ts +526 -526
  62. package/src/handlers/chat.test.ts +185 -185
  63. package/src/handlers/chat.ts +101 -101
  64. package/src/handlers/cloud-agents.test.ts +438 -438
  65. package/src/handlers/cloud-agents.ts +156 -156
  66. package/src/handlers/connectors.test.ts +834 -834
  67. package/src/handlers/connectors.ts +229 -229
  68. package/src/handlers/cost.test.ts +462 -462
  69. package/src/handlers/cost.ts +285 -285
  70. package/src/handlers/decisions.test.ts +382 -382
  71. package/src/handlers/decisions.ts +153 -153
  72. package/src/handlers/deployment.test.ts +551 -551
  73. package/src/handlers/deployment.ts +570 -570
  74. package/src/handlers/discovery.test.ts +206 -206
  75. package/src/handlers/discovery.ts +433 -433
  76. package/src/handlers/fallback.test.ts +537 -537
  77. package/src/handlers/fallback.ts +194 -194
  78. package/src/handlers/file-checkouts.test.ts +750 -750
  79. package/src/handlers/file-checkouts.ts +185 -185
  80. package/src/handlers/findings.test.ts +633 -633
  81. package/src/handlers/findings.ts +239 -239
  82. package/src/handlers/git-issues.test.ts +631 -631
  83. package/src/handlers/git-issues.ts +136 -136
  84. package/src/handlers/ideas.test.ts +644 -644
  85. package/src/handlers/ideas.ts +207 -207
  86. package/src/handlers/index.ts +93 -93
  87. package/src/handlers/milestones.test.ts +475 -475
  88. package/src/handlers/milestones.ts +180 -180
  89. package/src/handlers/organizations.test.ts +826 -826
  90. package/src/handlers/organizations.ts +315 -315
  91. package/src/handlers/progress.test.ts +269 -269
  92. package/src/handlers/progress.ts +77 -77
  93. package/src/handlers/project.test.ts +546 -546
  94. package/src/handlers/project.ts +245 -245
  95. package/src/handlers/requests.test.ts +303 -303
  96. package/src/handlers/requests.ts +99 -99
  97. package/src/handlers/roles.test.ts +305 -305
  98. package/src/handlers/roles.ts +219 -219
  99. package/src/handlers/session.test.ts +998 -998
  100. package/src/handlers/session.ts +1105 -1105
  101. package/src/handlers/sprints.test.ts +732 -732
  102. package/src/handlers/sprints.ts +537 -537
  103. package/src/handlers/tasks.test.ts +931 -931
  104. package/src/handlers/tasks.ts +1144 -1137
  105. package/src/handlers/tool-categories.test.ts +66 -66
  106. package/src/handlers/tool-docs.test.ts +511 -511
  107. package/src/handlers/tool-docs.ts +1595 -1595
  108. package/src/handlers/types.test.ts +259 -259
  109. package/src/handlers/types.ts +176 -176
  110. package/src/handlers/validation.test.ts +582 -582
  111. package/src/handlers/validation.ts +164 -164
  112. package/src/handlers/version.ts +63 -63
  113. package/src/index.test.ts +674 -674
  114. package/src/index.ts +884 -884
  115. package/src/setup.test.ts +243 -243
  116. package/src/setup.ts +410 -410
  117. package/src/templates/agent-guidelines.ts +233 -233
  118. package/src/templates/help-content.ts +1751 -1751
  119. package/src/token-tracking.test.ts +463 -463
  120. package/src/token-tracking.ts +167 -167
  121. package/src/tools/blockers.ts +122 -122
  122. package/src/tools/bodies-of-work.ts +283 -283
  123. package/src/tools/chat.ts +72 -72
  124. package/src/tools/cloud-agents.ts +101 -101
  125. package/src/tools/connectors.ts +191 -191
  126. package/src/tools/cost.ts +111 -111
  127. package/src/tools/decisions.ts +111 -111
  128. package/src/tools/deployment.ts +455 -455
  129. package/src/tools/discovery.ts +76 -76
  130. package/src/tools/fallback.ts +111 -111
  131. package/src/tools/features.ts +154 -154
  132. package/src/tools/file-checkouts.ts +145 -145
  133. package/src/tools/findings.ts +101 -101
  134. package/src/tools/git-issues.ts +130 -130
  135. package/src/tools/ideas.ts +162 -162
  136. package/src/tools/index.ts +145 -145
  137. package/src/tools/milestones.ts +118 -118
  138. package/src/tools/organizations.ts +224 -224
  139. package/src/tools/persona-templates.ts +25 -25
  140. package/src/tools/progress.ts +73 -73
  141. package/src/tools/project.ts +210 -210
  142. package/src/tools/requests.ts +68 -68
  143. package/src/tools/roles.ts +112 -112
  144. package/src/tools/session.ts +181 -181
  145. package/src/tools/sprints.ts +298 -298
  146. package/src/tools/tasks.ts +583 -575
  147. package/src/tools/tools.test.ts +222 -222
  148. package/src/tools/types.ts +9 -9
  149. package/src/tools/validation.ts +75 -75
  150. package/src/tools/version.ts +34 -34
  151. package/src/tools/worktrees.ts +66 -66
  152. package/src/tools.test.ts +416 -416
  153. package/src/utils.test.ts +1014 -1014
  154. package/src/utils.ts +586 -586
  155. package/src/validators.test.ts +223 -223
  156. package/src/validators.ts +249 -249
  157. package/src/version.ts +162 -162
  158. package/tsconfig.json +16 -16
  159. package/vitest.config.ts +14 -14
  160. package/dist/tools.d.ts +0 -2
  161. package/dist/tools.js +0 -3602
package/src/index.test.ts CHANGED
@@ -1,674 +1,674 @@
1
- /**
2
- * Tests for MCP Server Entry Point (index.ts)
3
- *
4
- * Tests covering:
5
- * 1. Server lifecycle (startup, shutdown, signal handling)
6
- * 2. Tool routing and handler selection
7
- * 3. Error handling and recovery
8
- * 4. Rate limiting behavior
9
- * 5. Token usage tracking
10
- * 6. Request/response formatting
11
- */
12
-
13
- import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
14
-
15
- // =============================================================================
16
- // Mock Setup - MUST be before any imports that use these modules
17
- // =============================================================================
18
-
19
- // Store original env
20
- const originalEnv = process.env.VIBESCOPE_API_KEY;
21
-
22
- // Mock the MCP SDK
23
- const mockServerConnect = vi.fn().mockResolvedValue(undefined);
24
- const mockSetRequestHandler = vi.fn();
25
- const mockServer = {
26
- connect: mockServerConnect,
27
- setRequestHandler: mockSetRequestHandler,
28
- };
29
- vi.mock('@modelcontextprotocol/sdk/server/index.js', () => ({
30
- Server: vi.fn(() => mockServer),
31
- }));
32
-
33
- const mockTransport = {};
34
- vi.mock('@modelcontextprotocol/sdk/server/stdio.js', () => ({
35
- StdioServerTransport: vi.fn(() => mockTransport),
36
- }));
37
-
38
- // Mock the API client
39
- const mockValidateAuth = vi.fn();
40
- const mockSyncSession = vi.fn().mockResolvedValue(undefined);
41
- const mockApiClient = {
42
- validateAuth: mockValidateAuth,
43
- syncSession: mockSyncSession,
44
- };
45
- vi.mock('./api-client.js', () => ({
46
- initApiClient: vi.fn(),
47
- getApiClient: vi.fn(() => mockApiClient),
48
- }));
49
-
50
- // Mock handlers registry
51
- const mockHandlerResult = { result: { success: true }, user_updates: null };
52
- const mockHandler = vi.fn().mockResolvedValue(mockHandlerResult);
53
- const mockHandlerRegistry: Record<string, typeof mockHandler> = {
54
- get_next_task: mockHandler,
55
- complete_task: mockHandler,
56
- update_task: mockHandler,
57
- add_task: mockHandler,
58
- start_work_session: mockHandler,
59
- get_help: mockHandler,
60
- };
61
- vi.mock('./handlers/index.js', () => ({
62
- buildHandlerRegistry: vi.fn(() => mockHandlerRegistry),
63
- }));
64
-
65
- // Mock token tracking
66
- const mockTokenUsage = {
67
- totalInputTokens: 0,
68
- totalOutputTokens: 0,
69
- callCount: 0,
70
- toolCounts: new Map(),
71
- };
72
- vi.mock('./token-tracking.js', () => ({
73
- createTokenUsage: vi.fn(() => mockTokenUsage),
74
- trackTokenUsage: vi.fn(),
75
- setCurrentModel: vi.fn(),
76
- }));
77
-
78
- // Mock tools
79
- vi.mock('./tools.js', () => ({
80
- tools: [
81
- { name: 'get_next_task', description: 'Get next task', inputSchema: { type: 'object' } },
82
- { name: 'complete_task', description: 'Complete task', inputSchema: { type: 'object' } },
83
- ],
84
- }));
85
-
86
- // Mock utils
87
- vi.mock('./utils.js', () => ({
88
- AGENT_PERSONAS: ['Thor', 'Loki', 'Odin'],
89
- FALLBACK_ACTIVITIES: ['code_review', 'security_review'],
90
- getRandomFallbackActivity: vi.fn(() => 'code_review'),
91
- selectPersona: vi.fn(() => 'Thor'),
92
- RateLimiter: class MockRateLimiter {
93
- check = vi.fn().mockReturnValue({ allowed: true, remaining: 50, resetIn: 60000 });
94
- cleanup = vi.fn();
95
- },
96
- extractProjectNameFromGitUrl: vi.fn((url: string) => 'test-project'),
97
- isValidStatusTransition: vi.fn(() => true),
98
- }));
99
-
100
- // Mock validators
101
- vi.mock('./validators.js', () => ({
102
- ValidationError: class ValidationError extends Error {
103
- constructor(
104
- public field: string,
105
- message: string,
106
- public expected?: string
107
- ) {
108
- super(message);
109
- this.name = 'ValidationError';
110
- }
111
- toJSON() {
112
- return { error: 'validation_error', field: this.field, message: this.message };
113
- }
114
- },
115
- validateRequired: vi.fn(),
116
- validateUUID: vi.fn(),
117
- validateTaskStatus: vi.fn(),
118
- validateProjectStatus: vi.fn(),
119
- validatePriority: vi.fn(),
120
- validateProgressPercentage: vi.fn(),
121
- validateEstimatedMinutes: vi.fn(),
122
- validateEnvironment: vi.fn(),
123
- VALID_TASK_STATUSES: ['pending', 'in_progress', 'completed'],
124
- VALID_PROJECT_STATUSES: ['active', 'paused', 'completed'],
125
- VALID_BLOCKER_STATUSES: ['open', 'resolved'],
126
- VALID_DEPLOYMENT_STATUSES: ['pending', 'deploying', 'completed'],
127
- VALID_ENVIRONMENTS: ['development', 'staging', 'production'],
128
- }));
129
-
130
- // =============================================================================
131
- // Test Suites
132
- // =============================================================================
133
-
134
- describe('MCP Server Entry Point', () => {
135
- beforeAll(() => {
136
- // Set required env var
137
- process.env.VIBESCOPE_API_KEY = 'test-api-key-12345';
138
- });
139
-
140
- afterAll(() => {
141
- // Restore original env
142
- if (originalEnv !== undefined) {
143
- process.env.VIBESCOPE_API_KEY = originalEnv;
144
- } else {
145
- delete process.env.VIBESCOPE_API_KEY;
146
- }
147
- });
148
-
149
- beforeEach(() => {
150
- vi.clearAllMocks();
151
- // Default: valid auth
152
- mockValidateAuth.mockResolvedValue({
153
- ok: true,
154
- data: { valid: true, user_id: 'user-123', api_key_id: 'key-123' },
155
- });
156
- });
157
-
158
- // =========================================================================
159
- // Knowledge Base Tests
160
- // =========================================================================
161
- describe('Knowledge Base', () => {
162
- it('should have getting_started topic', async () => {
163
- mockHandlerRegistry['get_help'] = vi.fn().mockImplementation(async (args) => {
164
- if (args.topic === 'getting_started') {
165
- return {
166
- result: {
167
- topic: 'getting_started',
168
- content: 'Call start_work_session to initialize',
169
- },
170
- };
171
- }
172
- return { result: { error: 'Topic not found' } };
173
- });
174
-
175
- const handler = mockHandlerRegistry['get_help'];
176
- const result = await handler({ topic: 'getting_started' }, {} as never);
177
-
178
- expect(result.result).toHaveProperty('topic', 'getting_started');
179
- });
180
-
181
- it('should have topics listing available help', async () => {
182
- mockHandlerRegistry['get_help'] = vi.fn().mockImplementation(async (args) => {
183
- if (args.topic === 'topics') {
184
- return {
185
- result: {
186
- topic: 'topics',
187
- content: 'Available: getting_started, tasks, validation, deployment, git, blockers',
188
- },
189
- };
190
- }
191
- return { result: { error: 'Topic not found' } };
192
- });
193
-
194
- const handler = mockHandlerRegistry['get_help'];
195
- const result = await handler({ topic: 'topics' }, {} as never);
196
-
197
- expect(result.result).toHaveProperty('topic', 'topics');
198
- expect(result.result.content).toContain('getting_started');
199
- });
200
- });
201
-
202
- // =========================================================================
203
- // Handler Routing Tests
204
- // =========================================================================
205
- describe('Tool Handler Routing', () => {
206
- it('should route to registered handler', async () => {
207
- const handler = mockHandlerRegistry['get_next_task'];
208
- const result = await handler({ project_id: 'proj-1' }, {} as never);
209
-
210
- expect(result).toEqual(mockHandlerResult);
211
- expect(mockHandler).toHaveBeenCalledWith({ project_id: 'proj-1' }, expect.anything());
212
- });
213
-
214
- it('should call handler with correct context structure', async () => {
215
- const testArgs = { project_id: 'proj-123', limit: 10 };
216
- await mockHandlerRegistry['get_next_task'](testArgs, {} as never);
217
-
218
- expect(mockHandler).toHaveBeenCalledWith(testArgs, expect.anything());
219
- });
220
-
221
- it('should throw for unknown tool', async () => {
222
- const unknownToolName = 'nonexistent_tool';
223
- expect(mockHandlerRegistry[unknownToolName]).toBeUndefined();
224
- });
225
-
226
- it('should support multiple handlers', async () => {
227
- const handlers = Object.keys(mockHandlerRegistry);
228
- expect(handlers).toContain('get_next_task');
229
- expect(handlers).toContain('complete_task');
230
- expect(handlers).toContain('update_task');
231
- expect(handlers).toContain('add_task');
232
- });
233
- });
234
-
235
- // =========================================================================
236
- // Rate Limiting Tests
237
- // =========================================================================
238
- describe('Rate Limiting', () => {
239
- it('should allow requests when under limit', async () => {
240
- const { RateLimiter } = await import('./utils.js');
241
- const limiter = new RateLimiter(60, 60000);
242
-
243
- const check = limiter.check('test-key');
244
- expect(check.allowed).toBe(true);
245
- expect(check.remaining).toBeGreaterThan(0);
246
- });
247
-
248
- it('should track remaining requests', async () => {
249
- const { RateLimiter } = await import('./utils.js');
250
- const limiter = new RateLimiter(60, 60000);
251
-
252
- const check = limiter.check('test-key');
253
- expect(check).toHaveProperty('remaining');
254
- expect(typeof check.remaining).toBe('number');
255
- });
256
-
257
- it('should provide reset time when limited', async () => {
258
- const { RateLimiter } = await import('./utils.js');
259
- const limiter = new RateLimiter(60, 60000);
260
-
261
- const check = limiter.check('test-key');
262
- expect(check).toHaveProperty('resetIn');
263
- expect(typeof check.resetIn).toBe('number');
264
- });
265
- });
266
-
267
- // =========================================================================
268
- // Token Tracking Tests
269
- // =========================================================================
270
- describe('Token Usage Tracking', () => {
271
- it('should create token usage object', async () => {
272
- const { createTokenUsage } = await import('./token-tracking.js');
273
- const usage = createTokenUsage();
274
-
275
- expect(usage).toBeDefined();
276
- expect(usage).toHaveProperty('totalInputTokens');
277
- expect(usage).toHaveProperty('totalOutputTokens');
278
- expect(usage).toHaveProperty('callCount');
279
- });
280
-
281
- it('should track usage with trackTokenUsage', async () => {
282
- const { trackTokenUsage, createTokenUsage } = await import('./token-tracking.js');
283
- const usage = createTokenUsage();
284
-
285
- // trackTokenUsage is mocked, so we just verify it can be called
286
- expect(() => trackTokenUsage(usage, 'get_next_task', {}, { success: true })).not.toThrow();
287
- });
288
- });
289
-
290
- // =========================================================================
291
- // Error Handling Tests
292
- // =========================================================================
293
- describe('Error Handling', () => {
294
- it('should handle ValidationError with structured output', async () => {
295
- const { ValidationError } = await import('./validators.js');
296
- const error = new ValidationError('project_id', 'Required field missing', 'UUID');
297
-
298
- expect(error.toJSON()).toEqual({
299
- error: 'validation_error',
300
- field: 'project_id',
301
- message: 'Required field missing',
302
- });
303
- });
304
-
305
- it('should handle handler errors gracefully', async () => {
306
- const errorHandler = vi.fn().mockRejectedValue(new Error('Database connection failed'));
307
- mockHandlerRegistry['failing_tool'] = errorHandler;
308
-
309
- await expect(mockHandlerRegistry['failing_tool']({}, {} as never)).rejects.toThrow(
310
- 'Database connection failed'
311
- );
312
- });
313
-
314
- it('should handle foreign key constraint errors', async () => {
315
- const dbError = new Error('violates foreign key constraint "tasks_project_id_fkey"');
316
- const errorHandler = vi.fn().mockRejectedValue(dbError);
317
- mockHandlerRegistry['db_error_tool'] = errorHandler;
318
-
319
- try {
320
- await mockHandlerRegistry['db_error_tool']({}, {} as never);
321
- } catch (error) {
322
- expect((error as Error).message).toContain('foreign key constraint');
323
- }
324
- });
325
-
326
- it('should handle duplicate key errors', async () => {
327
- const dbError = new Error('duplicate key value violates unique constraint');
328
- const errorHandler = vi.fn().mockRejectedValue(dbError);
329
- mockHandlerRegistry['duplicate_error_tool'] = errorHandler;
330
-
331
- try {
332
- await mockHandlerRegistry['duplicate_error_tool']({}, {} as never);
333
- } catch (error) {
334
- expect((error as Error).message).toContain('duplicate key');
335
- }
336
- });
337
- });
338
-
339
- // =========================================================================
340
- // API Client Tests
341
- // =========================================================================
342
- describe('API Client Integration', () => {
343
- it('should validate API key on startup', async () => {
344
- mockValidateAuth.mockResolvedValueOnce({
345
- ok: true,
346
- data: { valid: true, user_id: 'user-1', api_key_id: 'key-1' },
347
- });
348
-
349
- const { getApiClient } = await import('./api-client.js');
350
- const client = getApiClient();
351
- const result = await client.validateAuth();
352
-
353
- expect(result.ok).toBe(true);
354
- expect(result.data?.valid).toBe(true);
355
- });
356
-
357
- it('should fail with invalid API key', async () => {
358
- mockValidateAuth.mockResolvedValueOnce({
359
- ok: false,
360
- data: null,
361
- });
362
-
363
- const { getApiClient } = await import('./api-client.js');
364
- const client = getApiClient();
365
- const result = await client.validateAuth();
366
-
367
- expect(result.ok).toBe(false);
368
- });
369
-
370
- it('should sync session on tool calls', async () => {
371
- const { getApiClient } = await import('./api-client.js');
372
- const client = getApiClient();
373
-
374
- await client.syncSession('session-123');
375
- expect(mockSyncSession).toHaveBeenCalledWith('session-123');
376
- });
377
- });
378
-
379
- // =========================================================================
380
- // Response Formatting Tests
381
- // =========================================================================
382
- describe('Response Formatting', () => {
383
- it('should format success response as JSON', () => {
384
- const result = { success: true, task_id: 'task-123' };
385
- const formatted = JSON.stringify(result, null, 2);
386
-
387
- expect(formatted).toContain('"success": true');
388
- expect(formatted).toContain('"task_id": "task-123"');
389
- });
390
-
391
- it('should format error response with message', () => {
392
- const error = { error: 'not_found', message: 'Task not found' };
393
- const formatted = JSON.stringify(error, null, 2);
394
-
395
- expect(formatted).toContain('"error": "not_found"');
396
- expect(formatted).toContain('"message": "Task not found"');
397
- });
398
-
399
- it('should include user_updates when present', async () => {
400
- const handlerWithUpdates = vi.fn().mockResolvedValue({
401
- result: { success: true },
402
- user_updates: {
403
- tasks: [{ id: 'task-1', title: 'New Task' }],
404
- blockers: [],
405
- ideas: [],
406
- },
407
- });
408
-
409
- const response = await handlerWithUpdates({}, {} as never);
410
- expect(response.user_updates).toBeDefined();
411
- expect(response.user_updates.tasks).toHaveLength(1);
412
- });
413
- });
414
-
415
- // =========================================================================
416
- // Handler Context Tests
417
- // =========================================================================
418
- describe('Handler Context', () => {
419
- it('should include auth in context', async () => {
420
- const contextCapture = vi.fn().mockImplementation((args, ctx) => {
421
- expect(ctx).toBeDefined();
422
- return { result: { success: true } };
423
- });
424
- mockHandlerRegistry['context_test'] = contextCapture;
425
-
426
- await mockHandlerRegistry['context_test']({}, { auth: { userId: 'user-1' } } as never);
427
- expect(contextCapture).toHaveBeenCalled();
428
- });
429
-
430
- it('should include session info in context', async () => {
431
- const contextCapture = vi.fn().mockImplementation((args, ctx) => {
432
- expect(ctx.session || ctx).toBeDefined();
433
- return { result: { success: true } };
434
- });
435
- mockHandlerRegistry['session_test'] = contextCapture;
436
-
437
- await mockHandlerRegistry['session_test'](
438
- {},
439
- {
440
- session: {
441
- instanceId: 'inst-1',
442
- currentSessionId: 'sess-1',
443
- currentPersona: 'Thor',
444
- currentRole: 'developer',
445
- },
446
- } as never
447
- );
448
- expect(contextCapture).toHaveBeenCalled();
449
- });
450
- });
451
-
452
- // =========================================================================
453
- // Complete Task Reminder Tests
454
- // =========================================================================
455
- describe('Tool Reminders', () => {
456
- it('should have reminder for complete_task', async () => {
457
- // Simulate what the server does - complete_task gets a reminder
458
- const expectedReminder =
459
- 'CONTINUE WORKING: Call get_next_task or start the next_task. If awaiting_validation tasks exist, validate them FIRST before new work. If context is large, run /clear then start_work_session to refresh.';
460
-
461
- const reminders: Record<string, string> = {
462
- complete_task: expectedReminder,
463
- batch_complete_tasks:
464
- 'CONTINUE WORKING: Call get_next_task. If awaiting_validation tasks exist, validate them FIRST before new work.',
465
- };
466
-
467
- expect(reminders['complete_task']).toBeDefined();
468
- expect(reminders['complete_task']).toContain('CONTINUE WORKING');
469
- });
470
-
471
- it('should not have reminder for most tools', () => {
472
- const reminders: Record<string, string> = {
473
- complete_task: 'some reminder',
474
- batch_complete_tasks: 'another reminder',
475
- };
476
-
477
- expect(reminders['get_next_task']).toBeUndefined();
478
- expect(reminders['update_task']).toBeUndefined();
479
- expect(reminders['add_task']).toBeUndefined();
480
- });
481
- });
482
-
483
- // =========================================================================
484
- // Session Management Tests
485
- // =========================================================================
486
- describe('Session Management', () => {
487
- it('should track session ID after start_work_session', async () => {
488
- const startHandler = vi.fn().mockImplementation(async (args, ctx) => {
489
- // Simulate setting session ID
490
- if (ctx.updateSession) {
491
- ctx.updateSession({ currentSessionId: 'new-session-id' });
492
- }
493
- return {
494
- result: {
495
- session_id: 'new-session-id',
496
- persona: 'Thor',
497
- project: { id: 'proj-1', name: 'Test' },
498
- },
499
- };
500
- });
501
- mockHandlerRegistry['start_work_session'] = startHandler;
502
-
503
- const mockContext = {
504
- auth: { userId: 'user-1' },
505
- session: { instanceId: 'inst-1', currentSessionId: null },
506
- updateSession: vi.fn(),
507
- };
508
-
509
- const result = await mockHandlerRegistry['start_work_session'](
510
- { git_url: 'https://github.com/test/repo' },
511
- mockContext as never
512
- );
513
-
514
- expect(result.result.session_id).toBe('new-session-id');
515
- expect(mockContext.updateSession).toHaveBeenCalledWith({ currentSessionId: 'new-session-id' });
516
- });
517
-
518
- it('should track persona assignment', async () => {
519
- const startHandler = vi.fn().mockImplementation(async (args, ctx) => {
520
- if (ctx.updateSession) {
521
- ctx.updateSession({ currentPersona: 'Odin' });
522
- }
523
- return {
524
- result: {
525
- session_id: 'sess-1',
526
- persona: 'Odin',
527
- },
528
- };
529
- });
530
- mockHandlerRegistry['start_work_session'] = startHandler;
531
-
532
- const mockContext = {
533
- updateSession: vi.fn(),
534
- };
535
-
536
- await mockHandlerRegistry['start_work_session']({}, mockContext as never);
537
- expect(mockContext.updateSession).toHaveBeenCalledWith({ currentPersona: 'Odin' });
538
- });
539
-
540
- it('should track role assignment', async () => {
541
- const startHandler = vi.fn().mockImplementation(async (args, ctx) => {
542
- if (ctx.updateSession) {
543
- ctx.updateSession({ currentRole: 'validator' });
544
- }
545
- return {
546
- result: {
547
- session_id: 'sess-1',
548
- role: 'validator',
549
- },
550
- };
551
- });
552
- mockHandlerRegistry['start_work_session'] = startHandler;
553
-
554
- const mockContext = {
555
- updateSession: vi.fn(),
556
- };
557
-
558
- await mockHandlerRegistry['start_work_session']({ role: 'validator' }, mockContext as never);
559
- expect(mockContext.updateSession).toHaveBeenCalledWith({ currentRole: 'validator' });
560
- });
561
- });
562
-
563
- // =========================================================================
564
- // Instance ID Tests
565
- // =========================================================================
566
- describe('Instance Tracking', () => {
567
- it('should generate unique instance ID', async () => {
568
- // The server generates a UUID for INSTANCE_ID
569
- const uuid1 = crypto.randomUUID();
570
- const uuid2 = crypto.randomUUID();
571
-
572
- expect(uuid1).not.toBe(uuid2);
573
- expect(uuid1).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
574
- });
575
-
576
- it('should include instance ID in session context', () => {
577
- const sessionContext = {
578
- instanceId: 'inst-12345',
579
- currentSessionId: 'sess-1',
580
- currentPersona: 'Thor',
581
- currentRole: 'developer',
582
- };
583
-
584
- expect(sessionContext.instanceId).toBeDefined();
585
- expect(typeof sessionContext.instanceId).toBe('string');
586
- });
587
- });
588
-
589
- // =========================================================================
590
- // Server Configuration Tests
591
- // =========================================================================
592
- describe('Server Configuration', () => {
593
- it('should configure server with correct name and version', async () => {
594
- const { Server } = await import('@modelcontextprotocol/sdk/server/index.js');
595
-
596
- // Verify Server was called with correct config
597
- expect(Server).toBeDefined();
598
- });
599
-
600
- it('should enable tools capability', () => {
601
- const serverConfig = {
602
- capabilities: {
603
- tools: {},
604
- },
605
- };
606
-
607
- expect(serverConfig.capabilities.tools).toBeDefined();
608
- });
609
- });
610
-
611
- // =========================================================================
612
- // Signal Handling Tests
613
- // =========================================================================
614
- describe('Signal Handling', () => {
615
- it('should have handlers for SIGINT and SIGTERM', () => {
616
- // These are set up in the actual module
617
- // We can verify the pattern is correct
618
- const signals = ['SIGINT', 'SIGTERM'];
619
- signals.forEach((signal) => {
620
- expect(['SIGINT', 'SIGTERM']).toContain(signal);
621
- });
622
- });
623
-
624
- it('should cleanup rate limiter on exit', () => {
625
- // Verify cleanup can be called without error
626
- const mockCleanup = vi.fn();
627
- const mockInterval = setInterval(() => {}, 1000);
628
- clearInterval(mockInterval);
629
-
630
- expect(mockCleanup).not.toThrow;
631
- });
632
- });
633
-
634
- // =========================================================================
635
- // Tools List Tests
636
- // =========================================================================
637
- describe('Tools Registration', () => {
638
- it('should export tools array', async () => {
639
- const { tools } = await import('./tools/index.js');
640
- expect(Array.isArray(tools)).toBe(true);
641
- });
642
-
643
- it('should have required tool properties', async () => {
644
- const { tools } = await import('./tools/index.js');
645
- tools.forEach((tool) => {
646
- expect(tool).toHaveProperty('name');
647
- expect(tool).toHaveProperty('description');
648
- expect(tool).toHaveProperty('inputSchema');
649
- });
650
- });
651
- });
652
- });
653
-
654
- describe('Environment Variable Handling', () => {
655
- const originalEnvKey = process.env.VIBESCOPE_API_KEY;
656
-
657
- beforeAll(() => {
658
- process.env.VIBESCOPE_API_KEY = 'test-api-key-12345';
659
- });
660
-
661
- afterAll(() => {
662
- if (originalEnvKey !== undefined) {
663
- process.env.VIBESCOPE_API_KEY = originalEnvKey;
664
- } else {
665
- delete process.env.VIBESCOPE_API_KEY;
666
- }
667
- });
668
-
669
- it('should use VIBESCOPE_API_KEY from environment', () => {
670
- const apiKey = process.env.VIBESCOPE_API_KEY;
671
- expect(apiKey).toBeDefined();
672
- expect(apiKey).toBe('test-api-key-12345');
673
- });
674
- });
1
+ /**
2
+ * Tests for MCP Server Entry Point (index.ts)
3
+ *
4
+ * Tests covering:
5
+ * 1. Server lifecycle (startup, shutdown, signal handling)
6
+ * 2. Tool routing and handler selection
7
+ * 3. Error handling and recovery
8
+ * 4. Rate limiting behavior
9
+ * 5. Token usage tracking
10
+ * 6. Request/response formatting
11
+ */
12
+
13
+ import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
14
+
15
+ // =============================================================================
16
+ // Mock Setup - MUST be before any imports that use these modules
17
+ // =============================================================================
18
+
19
+ // Store original env
20
+ const originalEnv = process.env.VIBESCOPE_API_KEY;
21
+
22
+ // Mock the MCP SDK
23
+ const mockServerConnect = vi.fn().mockResolvedValue(undefined);
24
+ const mockSetRequestHandler = vi.fn();
25
+ const mockServer = {
26
+ connect: mockServerConnect,
27
+ setRequestHandler: mockSetRequestHandler,
28
+ };
29
+ vi.mock('@modelcontextprotocol/sdk/server/index.js', () => ({
30
+ Server: vi.fn(() => mockServer),
31
+ }));
32
+
33
+ const mockTransport = {};
34
+ vi.mock('@modelcontextprotocol/sdk/server/stdio.js', () => ({
35
+ StdioServerTransport: vi.fn(() => mockTransport),
36
+ }));
37
+
38
+ // Mock the API client
39
+ const mockValidateAuth = vi.fn();
40
+ const mockSyncSession = vi.fn().mockResolvedValue(undefined);
41
+ const mockApiClient = {
42
+ validateAuth: mockValidateAuth,
43
+ syncSession: mockSyncSession,
44
+ };
45
+ vi.mock('./api-client.js', () => ({
46
+ initApiClient: vi.fn(),
47
+ getApiClient: vi.fn(() => mockApiClient),
48
+ }));
49
+
50
+ // Mock handlers registry
51
+ const mockHandlerResult = { result: { success: true }, user_updates: null };
52
+ const mockHandler = vi.fn().mockResolvedValue(mockHandlerResult);
53
+ const mockHandlerRegistry: Record<string, typeof mockHandler> = {
54
+ get_next_task: mockHandler,
55
+ complete_task: mockHandler,
56
+ update_task: mockHandler,
57
+ add_task: mockHandler,
58
+ start_work_session: mockHandler,
59
+ get_help: mockHandler,
60
+ };
61
+ vi.mock('./handlers/index.js', () => ({
62
+ buildHandlerRegistry: vi.fn(() => mockHandlerRegistry),
63
+ }));
64
+
65
+ // Mock token tracking
66
+ const mockTokenUsage = {
67
+ totalInputTokens: 0,
68
+ totalOutputTokens: 0,
69
+ callCount: 0,
70
+ toolCounts: new Map(),
71
+ };
72
+ vi.mock('./token-tracking.js', () => ({
73
+ createTokenUsage: vi.fn(() => mockTokenUsage),
74
+ trackTokenUsage: vi.fn(),
75
+ setCurrentModel: vi.fn(),
76
+ }));
77
+
78
+ // Mock tools
79
+ vi.mock('./tools.js', () => ({
80
+ tools: [
81
+ { name: 'get_next_task', description: 'Get next task', inputSchema: { type: 'object' } },
82
+ { name: 'complete_task', description: 'Complete task', inputSchema: { type: 'object' } },
83
+ ],
84
+ }));
85
+
86
+ // Mock utils
87
+ vi.mock('./utils.js', () => ({
88
+ AGENT_PERSONAS: ['Thor', 'Loki', 'Odin'],
89
+ FALLBACK_ACTIVITIES: ['code_review', 'security_review'],
90
+ getRandomFallbackActivity: vi.fn(() => 'code_review'),
91
+ selectPersona: vi.fn(() => 'Thor'),
92
+ RateLimiter: class MockRateLimiter {
93
+ check = vi.fn().mockReturnValue({ allowed: true, remaining: 50, resetIn: 60000 });
94
+ cleanup = vi.fn();
95
+ },
96
+ extractProjectNameFromGitUrl: vi.fn((url: string) => 'test-project'),
97
+ isValidStatusTransition: vi.fn(() => true),
98
+ }));
99
+
100
+ // Mock validators
101
+ vi.mock('./validators.js', () => ({
102
+ ValidationError: class ValidationError extends Error {
103
+ constructor(
104
+ public field: string,
105
+ message: string,
106
+ public expected?: string
107
+ ) {
108
+ super(message);
109
+ this.name = 'ValidationError';
110
+ }
111
+ toJSON() {
112
+ return { error: 'validation_error', field: this.field, message: this.message };
113
+ }
114
+ },
115
+ validateRequired: vi.fn(),
116
+ validateUUID: vi.fn(),
117
+ validateTaskStatus: vi.fn(),
118
+ validateProjectStatus: vi.fn(),
119
+ validatePriority: vi.fn(),
120
+ validateProgressPercentage: vi.fn(),
121
+ validateEstimatedMinutes: vi.fn(),
122
+ validateEnvironment: vi.fn(),
123
+ VALID_TASK_STATUSES: ['pending', 'in_progress', 'completed'],
124
+ VALID_PROJECT_STATUSES: ['active', 'paused', 'completed'],
125
+ VALID_BLOCKER_STATUSES: ['open', 'resolved'],
126
+ VALID_DEPLOYMENT_STATUSES: ['pending', 'deploying', 'completed'],
127
+ VALID_ENVIRONMENTS: ['development', 'staging', 'production'],
128
+ }));
129
+
130
+ // =============================================================================
131
+ // Test Suites
132
+ // =============================================================================
133
+
134
+ describe('MCP Server Entry Point', () => {
135
+ beforeAll(() => {
136
+ // Set required env var
137
+ process.env.VIBESCOPE_API_KEY = 'test-api-key-12345';
138
+ });
139
+
140
+ afterAll(() => {
141
+ // Restore original env
142
+ if (originalEnv !== undefined) {
143
+ process.env.VIBESCOPE_API_KEY = originalEnv;
144
+ } else {
145
+ delete process.env.VIBESCOPE_API_KEY;
146
+ }
147
+ });
148
+
149
+ beforeEach(() => {
150
+ vi.clearAllMocks();
151
+ // Default: valid auth
152
+ mockValidateAuth.mockResolvedValue({
153
+ ok: true,
154
+ data: { valid: true, user_id: 'user-123', api_key_id: 'key-123' },
155
+ });
156
+ });
157
+
158
+ // =========================================================================
159
+ // Knowledge Base Tests
160
+ // =========================================================================
161
+ describe('Knowledge Base', () => {
162
+ it('should have getting_started topic', async () => {
163
+ mockHandlerRegistry['get_help'] = vi.fn().mockImplementation(async (args) => {
164
+ if (args.topic === 'getting_started') {
165
+ return {
166
+ result: {
167
+ topic: 'getting_started',
168
+ content: 'Call start_work_session to initialize',
169
+ },
170
+ };
171
+ }
172
+ return { result: { error: 'Topic not found' } };
173
+ });
174
+
175
+ const handler = mockHandlerRegistry['get_help'];
176
+ const result = await handler({ topic: 'getting_started' }, {} as never);
177
+
178
+ expect(result.result).toHaveProperty('topic', 'getting_started');
179
+ });
180
+
181
+ it('should have topics listing available help', async () => {
182
+ mockHandlerRegistry['get_help'] = vi.fn().mockImplementation(async (args) => {
183
+ if (args.topic === 'topics') {
184
+ return {
185
+ result: {
186
+ topic: 'topics',
187
+ content: 'Available: getting_started, tasks, validation, deployment, git, blockers',
188
+ },
189
+ };
190
+ }
191
+ return { result: { error: 'Topic not found' } };
192
+ });
193
+
194
+ const handler = mockHandlerRegistry['get_help'];
195
+ const result = await handler({ topic: 'topics' }, {} as never);
196
+
197
+ expect(result.result).toHaveProperty('topic', 'topics');
198
+ expect(result.result.content).toContain('getting_started');
199
+ });
200
+ });
201
+
202
+ // =========================================================================
203
+ // Handler Routing Tests
204
+ // =========================================================================
205
+ describe('Tool Handler Routing', () => {
206
+ it('should route to registered handler', async () => {
207
+ const handler = mockHandlerRegistry['get_next_task'];
208
+ const result = await handler({ project_id: 'proj-1' }, {} as never);
209
+
210
+ expect(result).toEqual(mockHandlerResult);
211
+ expect(mockHandler).toHaveBeenCalledWith({ project_id: 'proj-1' }, expect.anything());
212
+ });
213
+
214
+ it('should call handler with correct context structure', async () => {
215
+ const testArgs = { project_id: 'proj-123', limit: 10 };
216
+ await mockHandlerRegistry['get_next_task'](testArgs, {} as never);
217
+
218
+ expect(mockHandler).toHaveBeenCalledWith(testArgs, expect.anything());
219
+ });
220
+
221
+ it('should throw for unknown tool', async () => {
222
+ const unknownToolName = 'nonexistent_tool';
223
+ expect(mockHandlerRegistry[unknownToolName]).toBeUndefined();
224
+ });
225
+
226
+ it('should support multiple handlers', async () => {
227
+ const handlers = Object.keys(mockHandlerRegistry);
228
+ expect(handlers).toContain('get_next_task');
229
+ expect(handlers).toContain('complete_task');
230
+ expect(handlers).toContain('update_task');
231
+ expect(handlers).toContain('add_task');
232
+ });
233
+ });
234
+
235
+ // =========================================================================
236
+ // Rate Limiting Tests
237
+ // =========================================================================
238
+ describe('Rate Limiting', () => {
239
+ it('should allow requests when under limit', async () => {
240
+ const { RateLimiter } = await import('./utils.js');
241
+ const limiter = new RateLimiter(60, 60000);
242
+
243
+ const check = limiter.check('test-key');
244
+ expect(check.allowed).toBe(true);
245
+ expect(check.remaining).toBeGreaterThan(0);
246
+ });
247
+
248
+ it('should track remaining requests', async () => {
249
+ const { RateLimiter } = await import('./utils.js');
250
+ const limiter = new RateLimiter(60, 60000);
251
+
252
+ const check = limiter.check('test-key');
253
+ expect(check).toHaveProperty('remaining');
254
+ expect(typeof check.remaining).toBe('number');
255
+ });
256
+
257
+ it('should provide reset time when limited', async () => {
258
+ const { RateLimiter } = await import('./utils.js');
259
+ const limiter = new RateLimiter(60, 60000);
260
+
261
+ const check = limiter.check('test-key');
262
+ expect(check).toHaveProperty('resetIn');
263
+ expect(typeof check.resetIn).toBe('number');
264
+ });
265
+ });
266
+
267
+ // =========================================================================
268
+ // Token Tracking Tests
269
+ // =========================================================================
270
+ describe('Token Usage Tracking', () => {
271
+ it('should create token usage object', async () => {
272
+ const { createTokenUsage } = await import('./token-tracking.js');
273
+ const usage = createTokenUsage();
274
+
275
+ expect(usage).toBeDefined();
276
+ expect(usage).toHaveProperty('totalInputTokens');
277
+ expect(usage).toHaveProperty('totalOutputTokens');
278
+ expect(usage).toHaveProperty('callCount');
279
+ });
280
+
281
+ it('should track usage with trackTokenUsage', async () => {
282
+ const { trackTokenUsage, createTokenUsage } = await import('./token-tracking.js');
283
+ const usage = createTokenUsage();
284
+
285
+ // trackTokenUsage is mocked, so we just verify it can be called
286
+ expect(() => trackTokenUsage(usage, 'get_next_task', {}, { success: true })).not.toThrow();
287
+ });
288
+ });
289
+
290
+ // =========================================================================
291
+ // Error Handling Tests
292
+ // =========================================================================
293
+ describe('Error Handling', () => {
294
+ it('should handle ValidationError with structured output', async () => {
295
+ const { ValidationError } = await import('./validators.js');
296
+ const error = new ValidationError('project_id', 'Required field missing', 'UUID');
297
+
298
+ expect(error.toJSON()).toEqual({
299
+ error: 'validation_error',
300
+ field: 'project_id',
301
+ message: 'Required field missing',
302
+ });
303
+ });
304
+
305
+ it('should handle handler errors gracefully', async () => {
306
+ const errorHandler = vi.fn().mockRejectedValue(new Error('Database connection failed'));
307
+ mockHandlerRegistry['failing_tool'] = errorHandler;
308
+
309
+ await expect(mockHandlerRegistry['failing_tool']({}, {} as never)).rejects.toThrow(
310
+ 'Database connection failed'
311
+ );
312
+ });
313
+
314
+ it('should handle foreign key constraint errors', async () => {
315
+ const dbError = new Error('violates foreign key constraint "tasks_project_id_fkey"');
316
+ const errorHandler = vi.fn().mockRejectedValue(dbError);
317
+ mockHandlerRegistry['db_error_tool'] = errorHandler;
318
+
319
+ try {
320
+ await mockHandlerRegistry['db_error_tool']({}, {} as never);
321
+ } catch (error) {
322
+ expect((error as Error).message).toContain('foreign key constraint');
323
+ }
324
+ });
325
+
326
+ it('should handle duplicate key errors', async () => {
327
+ const dbError = new Error('duplicate key value violates unique constraint');
328
+ const errorHandler = vi.fn().mockRejectedValue(dbError);
329
+ mockHandlerRegistry['duplicate_error_tool'] = errorHandler;
330
+
331
+ try {
332
+ await mockHandlerRegistry['duplicate_error_tool']({}, {} as never);
333
+ } catch (error) {
334
+ expect((error as Error).message).toContain('duplicate key');
335
+ }
336
+ });
337
+ });
338
+
339
+ // =========================================================================
340
+ // API Client Tests
341
+ // =========================================================================
342
+ describe('API Client Integration', () => {
343
+ it('should validate API key on startup', async () => {
344
+ mockValidateAuth.mockResolvedValueOnce({
345
+ ok: true,
346
+ data: { valid: true, user_id: 'user-1', api_key_id: 'key-1' },
347
+ });
348
+
349
+ const { getApiClient } = await import('./api-client.js');
350
+ const client = getApiClient();
351
+ const result = await client.validateAuth();
352
+
353
+ expect(result.ok).toBe(true);
354
+ expect(result.data?.valid).toBe(true);
355
+ });
356
+
357
+ it('should fail with invalid API key', async () => {
358
+ mockValidateAuth.mockResolvedValueOnce({
359
+ ok: false,
360
+ data: null,
361
+ });
362
+
363
+ const { getApiClient } = await import('./api-client.js');
364
+ const client = getApiClient();
365
+ const result = await client.validateAuth();
366
+
367
+ expect(result.ok).toBe(false);
368
+ });
369
+
370
+ it('should sync session on tool calls', async () => {
371
+ const { getApiClient } = await import('./api-client.js');
372
+ const client = getApiClient();
373
+
374
+ await client.syncSession('session-123');
375
+ expect(mockSyncSession).toHaveBeenCalledWith('session-123');
376
+ });
377
+ });
378
+
379
+ // =========================================================================
380
+ // Response Formatting Tests
381
+ // =========================================================================
382
+ describe('Response Formatting', () => {
383
+ it('should format success response as JSON', () => {
384
+ const result = { success: true, task_id: 'task-123' };
385
+ const formatted = JSON.stringify(result, null, 2);
386
+
387
+ expect(formatted).toContain('"success": true');
388
+ expect(formatted).toContain('"task_id": "task-123"');
389
+ });
390
+
391
+ it('should format error response with message', () => {
392
+ const error = { error: 'not_found', message: 'Task not found' };
393
+ const formatted = JSON.stringify(error, null, 2);
394
+
395
+ expect(formatted).toContain('"error": "not_found"');
396
+ expect(formatted).toContain('"message": "Task not found"');
397
+ });
398
+
399
+ it('should include user_updates when present', async () => {
400
+ const handlerWithUpdates = vi.fn().mockResolvedValue({
401
+ result: { success: true },
402
+ user_updates: {
403
+ tasks: [{ id: 'task-1', title: 'New Task' }],
404
+ blockers: [],
405
+ ideas: [],
406
+ },
407
+ });
408
+
409
+ const response = await handlerWithUpdates({}, {} as never);
410
+ expect(response.user_updates).toBeDefined();
411
+ expect(response.user_updates.tasks).toHaveLength(1);
412
+ });
413
+ });
414
+
415
+ // =========================================================================
416
+ // Handler Context Tests
417
+ // =========================================================================
418
+ describe('Handler Context', () => {
419
+ it('should include auth in context', async () => {
420
+ const contextCapture = vi.fn().mockImplementation((args, ctx) => {
421
+ expect(ctx).toBeDefined();
422
+ return { result: { success: true } };
423
+ });
424
+ mockHandlerRegistry['context_test'] = contextCapture;
425
+
426
+ await mockHandlerRegistry['context_test']({}, { auth: { userId: 'user-1' } } as never);
427
+ expect(contextCapture).toHaveBeenCalled();
428
+ });
429
+
430
+ it('should include session info in context', async () => {
431
+ const contextCapture = vi.fn().mockImplementation((args, ctx) => {
432
+ expect(ctx.session || ctx).toBeDefined();
433
+ return { result: { success: true } };
434
+ });
435
+ mockHandlerRegistry['session_test'] = contextCapture;
436
+
437
+ await mockHandlerRegistry['session_test'](
438
+ {},
439
+ {
440
+ session: {
441
+ instanceId: 'inst-1',
442
+ currentSessionId: 'sess-1',
443
+ currentPersona: 'Thor',
444
+ currentRole: 'developer',
445
+ },
446
+ } as never
447
+ );
448
+ expect(contextCapture).toHaveBeenCalled();
449
+ });
450
+ });
451
+
452
+ // =========================================================================
453
+ // Complete Task Reminder Tests
454
+ // =========================================================================
455
+ describe('Tool Reminders', () => {
456
+ it('should have reminder for complete_task', async () => {
457
+ // Simulate what the server does - complete_task gets a reminder
458
+ const expectedReminder =
459
+ 'CONTINUE WORKING: Call get_next_task or start the next_task. If awaiting_validation tasks exist, validate them FIRST before new work. If context is large, run /clear then start_work_session to refresh.';
460
+
461
+ const reminders: Record<string, string> = {
462
+ complete_task: expectedReminder,
463
+ batch_complete_tasks:
464
+ 'CONTINUE WORKING: Call get_next_task. If awaiting_validation tasks exist, validate them FIRST before new work.',
465
+ };
466
+
467
+ expect(reminders['complete_task']).toBeDefined();
468
+ expect(reminders['complete_task']).toContain('CONTINUE WORKING');
469
+ });
470
+
471
+ it('should not have reminder for most tools', () => {
472
+ const reminders: Record<string, string> = {
473
+ complete_task: 'some reminder',
474
+ batch_complete_tasks: 'another reminder',
475
+ };
476
+
477
+ expect(reminders['get_next_task']).toBeUndefined();
478
+ expect(reminders['update_task']).toBeUndefined();
479
+ expect(reminders['add_task']).toBeUndefined();
480
+ });
481
+ });
482
+
483
+ // =========================================================================
484
+ // Session Management Tests
485
+ // =========================================================================
486
+ describe('Session Management', () => {
487
+ it('should track session ID after start_work_session', async () => {
488
+ const startHandler = vi.fn().mockImplementation(async (args, ctx) => {
489
+ // Simulate setting session ID
490
+ if (ctx.updateSession) {
491
+ ctx.updateSession({ currentSessionId: 'new-session-id' });
492
+ }
493
+ return {
494
+ result: {
495
+ session_id: 'new-session-id',
496
+ persona: 'Thor',
497
+ project: { id: 'proj-1', name: 'Test' },
498
+ },
499
+ };
500
+ });
501
+ mockHandlerRegistry['start_work_session'] = startHandler;
502
+
503
+ const mockContext = {
504
+ auth: { userId: 'user-1' },
505
+ session: { instanceId: 'inst-1', currentSessionId: null },
506
+ updateSession: vi.fn(),
507
+ };
508
+
509
+ const result = await mockHandlerRegistry['start_work_session'](
510
+ { git_url: 'https://github.com/test/repo' },
511
+ mockContext as never
512
+ );
513
+
514
+ expect(result.result.session_id).toBe('new-session-id');
515
+ expect(mockContext.updateSession).toHaveBeenCalledWith({ currentSessionId: 'new-session-id' });
516
+ });
517
+
518
+ it('should track persona assignment', async () => {
519
+ const startHandler = vi.fn().mockImplementation(async (args, ctx) => {
520
+ if (ctx.updateSession) {
521
+ ctx.updateSession({ currentPersona: 'Odin' });
522
+ }
523
+ return {
524
+ result: {
525
+ session_id: 'sess-1',
526
+ persona: 'Odin',
527
+ },
528
+ };
529
+ });
530
+ mockHandlerRegistry['start_work_session'] = startHandler;
531
+
532
+ const mockContext = {
533
+ updateSession: vi.fn(),
534
+ };
535
+
536
+ await mockHandlerRegistry['start_work_session']({}, mockContext as never);
537
+ expect(mockContext.updateSession).toHaveBeenCalledWith({ currentPersona: 'Odin' });
538
+ });
539
+
540
+ it('should track role assignment', async () => {
541
+ const startHandler = vi.fn().mockImplementation(async (args, ctx) => {
542
+ if (ctx.updateSession) {
543
+ ctx.updateSession({ currentRole: 'validator' });
544
+ }
545
+ return {
546
+ result: {
547
+ session_id: 'sess-1',
548
+ role: 'validator',
549
+ },
550
+ };
551
+ });
552
+ mockHandlerRegistry['start_work_session'] = startHandler;
553
+
554
+ const mockContext = {
555
+ updateSession: vi.fn(),
556
+ };
557
+
558
+ await mockHandlerRegistry['start_work_session']({ role: 'validator' }, mockContext as never);
559
+ expect(mockContext.updateSession).toHaveBeenCalledWith({ currentRole: 'validator' });
560
+ });
561
+ });
562
+
563
+ // =========================================================================
564
+ // Instance ID Tests
565
+ // =========================================================================
566
+ describe('Instance Tracking', () => {
567
+ it('should generate unique instance ID', async () => {
568
+ // The server generates a UUID for INSTANCE_ID
569
+ const uuid1 = crypto.randomUUID();
570
+ const uuid2 = crypto.randomUUID();
571
+
572
+ expect(uuid1).not.toBe(uuid2);
573
+ expect(uuid1).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/);
574
+ });
575
+
576
+ it('should include instance ID in session context', () => {
577
+ const sessionContext = {
578
+ instanceId: 'inst-12345',
579
+ currentSessionId: 'sess-1',
580
+ currentPersona: 'Thor',
581
+ currentRole: 'developer',
582
+ };
583
+
584
+ expect(sessionContext.instanceId).toBeDefined();
585
+ expect(typeof sessionContext.instanceId).toBe('string');
586
+ });
587
+ });
588
+
589
+ // =========================================================================
590
+ // Server Configuration Tests
591
+ // =========================================================================
592
+ describe('Server Configuration', () => {
593
+ it('should configure server with correct name and version', async () => {
594
+ const { Server } = await import('@modelcontextprotocol/sdk/server/index.js');
595
+
596
+ // Verify Server was called with correct config
597
+ expect(Server).toBeDefined();
598
+ });
599
+
600
+ it('should enable tools capability', () => {
601
+ const serverConfig = {
602
+ capabilities: {
603
+ tools: {},
604
+ },
605
+ };
606
+
607
+ expect(serverConfig.capabilities.tools).toBeDefined();
608
+ });
609
+ });
610
+
611
+ // =========================================================================
612
+ // Signal Handling Tests
613
+ // =========================================================================
614
+ describe('Signal Handling', () => {
615
+ it('should have handlers for SIGINT and SIGTERM', () => {
616
+ // These are set up in the actual module
617
+ // We can verify the pattern is correct
618
+ const signals = ['SIGINT', 'SIGTERM'];
619
+ signals.forEach((signal) => {
620
+ expect(['SIGINT', 'SIGTERM']).toContain(signal);
621
+ });
622
+ });
623
+
624
+ it('should cleanup rate limiter on exit', () => {
625
+ // Verify cleanup can be called without error
626
+ const mockCleanup = vi.fn();
627
+ const mockInterval = setInterval(() => {}, 1000);
628
+ clearInterval(mockInterval);
629
+
630
+ expect(mockCleanup).not.toThrow;
631
+ });
632
+ });
633
+
634
+ // =========================================================================
635
+ // Tools List Tests
636
+ // =========================================================================
637
+ describe('Tools Registration', () => {
638
+ it('should export tools array', async () => {
639
+ const { tools } = await import('./tools/index.js');
640
+ expect(Array.isArray(tools)).toBe(true);
641
+ });
642
+
643
+ it('should have required tool properties', async () => {
644
+ const { tools } = await import('./tools/index.js');
645
+ tools.forEach((tool) => {
646
+ expect(tool).toHaveProperty('name');
647
+ expect(tool).toHaveProperty('description');
648
+ expect(tool).toHaveProperty('inputSchema');
649
+ });
650
+ });
651
+ });
652
+ });
653
+
654
+ describe('Environment Variable Handling', () => {
655
+ const originalEnvKey = process.env.VIBESCOPE_API_KEY;
656
+
657
+ beforeAll(() => {
658
+ process.env.VIBESCOPE_API_KEY = 'test-api-key-12345';
659
+ });
660
+
661
+ afterAll(() => {
662
+ if (originalEnvKey !== undefined) {
663
+ process.env.VIBESCOPE_API_KEY = originalEnvKey;
664
+ } else {
665
+ delete process.env.VIBESCOPE_API_KEY;
666
+ }
667
+ });
668
+
669
+ it('should use VIBESCOPE_API_KEY from environment', () => {
670
+ const apiKey = process.env.VIBESCOPE_API_KEY;
671
+ expect(apiKey).toBeDefined();
672
+ expect(apiKey).toBe('test-api-key-12345');
673
+ });
674
+ });