@cachly-dev/mcp-server 0.10.27 → 0.10.41

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 (79) hide show
  1. package/.env.test.example +23 -0
  2. package/.github/ISSUE_TEMPLATE/bug_report.md +50 -0
  3. package/.github/ISSUE_TEMPLATE/config.yml +8 -0
  4. package/.github/ISSUE_TEMPLATE/feature_request.md +25 -0
  5. package/.github/workflows/publish.yml +72 -0
  6. package/CHANGELOG.md +252 -0
  7. package/LAUNCH_TEXTS.md +182 -0
  8. package/LICENSE +202 -0
  9. package/README.md +145 -115
  10. package/dist/__tests__/auth.test.d.ts +1 -0
  11. package/dist/__tests__/auth.test.js +107 -0
  12. package/dist/__tests__/auth.test.js.map +1 -0
  13. package/dist/__tests__/e2e/api-auth.test.d.ts +7 -0
  14. package/dist/__tests__/e2e/api-auth.test.js +162 -0
  15. package/dist/__tests__/e2e/api-auth.test.js.map +1 -0
  16. package/dist/__tests__/e2e/api-health.test.d.ts +7 -0
  17. package/dist/__tests__/e2e/api-health.test.js +95 -0
  18. package/dist/__tests__/e2e/api-health.test.js.map +1 -0
  19. package/dist/__tests__/e2e/cli.test.d.ts +10 -0
  20. package/dist/__tests__/e2e/cli.test.js +204 -0
  21. package/dist/__tests__/e2e/cli.test.js.map +1 -0
  22. package/dist/__tests__/e2e/config.d.ts +35 -0
  23. package/dist/__tests__/e2e/config.js +53 -0
  24. package/dist/__tests__/e2e/config.js.map +1 -0
  25. package/dist/__tests__/e2e/funnel.test.d.ts +13 -0
  26. package/dist/__tests__/e2e/funnel.test.js +90 -0
  27. package/dist/__tests__/e2e/funnel.test.js.map +1 -0
  28. package/dist/__tests__/e2e/mcp-tools.test.d.ts +7 -0
  29. package/dist/__tests__/e2e/mcp-tools.test.js +129 -0
  30. package/dist/__tests__/e2e/mcp-tools.test.js.map +1 -0
  31. package/dist/__tests__/e2e/provisioning.test.d.ts +15 -0
  32. package/dist/__tests__/e2e/provisioning.test.js +123 -0
  33. package/dist/__tests__/e2e/provisioning.test.js.map +1 -0
  34. package/dist/handlers/advanced.js +38 -227
  35. package/dist/handlers/advanced.js.map +1 -1
  36. package/dist/handlers/brain.js +146 -82
  37. package/dist/handlers/brain.js.map +1 -1
  38. package/dist/handlers/fedbrain.js +93 -44
  39. package/dist/handlers/fedbrain.js.map +1 -1
  40. package/dist/handlers/roadmap.js +8 -2
  41. package/dist/handlers/roadmap.js.map +1 -1
  42. package/dist/handlers/syndicate.js +15 -7
  43. package/dist/handlers/syndicate.js.map +1 -1
  44. package/dist/handlers/team.js +62 -50
  45. package/dist/handlers/team.js.map +1 -1
  46. package/dist/index.js +1264 -234
  47. package/dist/index.js.map +1 -1
  48. package/dist/tools.d.ts +3 -54
  49. package/dist/tools.js +8 -62
  50. package/dist/tools.js.map +1 -1
  51. package/eslint.config.js +16 -0
  52. package/glama.json +36 -0
  53. package/llms.txt +155 -0
  54. package/package.json +38 -32
  55. package/scripts/e2e-run.sh +160 -0
  56. package/scripts/postinstall.js +12 -12
  57. package/server.json +3 -9
  58. package/smithery.yaml +15 -8
  59. package/src/__tests__/auth.test.ts +147 -0
  60. package/src/__tests__/e2e/api-auth.test.ts +182 -0
  61. package/src/__tests__/e2e/api-health.test.ts +103 -0
  62. package/src/__tests__/e2e/cli.test.ts +228 -0
  63. package/src/__tests__/e2e/config.ts +53 -0
  64. package/src/__tests__/e2e/funnel.test.ts +99 -0
  65. package/src/__tests__/e2e/mcp-tools.test.ts +191 -0
  66. package/src/__tests__/e2e/provisioning.test.ts +128 -0
  67. package/src/handlers/advanced.ts +37 -217
  68. package/src/handlers/brain.ts +143 -78
  69. package/src/handlers/fedbrain.ts +88 -38
  70. package/src/handlers/roadmap.ts +7 -2
  71. package/src/handlers/syndicate.ts +13 -7
  72. package/src/handlers/team.ts +57 -33
  73. package/src/index.ts +1312 -257
  74. package/src/tools.ts +8 -66
  75. package/vitest.config.ts +12 -0
  76. package/dist/__tests__/brain-predict-failures.test.d.ts +0 -17
  77. package/dist/__tests__/brain-predict-failures.test.js +0 -339
  78. package/dist/__tests__/brain-predict-failures.test.js.map +0 -1
  79. package/src/__tests__/brain-predict-failures.test.ts +0 -430
@@ -0,0 +1,103 @@
1
+ /**
2
+ * E2E: API health & public endpoints
3
+ *
4
+ * These tests require NO credentials — they hit publicly accessible endpoints.
5
+ * Run: E2E_API_URL=https://api.dev.cachly.dev npx vitest run src/__tests__/e2e/api-health.test.ts
6
+ */
7
+
8
+ import { describe, it, expect, beforeAll } from 'vitest';
9
+ import { cfg } from './config.js';
10
+
11
+ describe('API health (no auth required)', () => {
12
+ it('GET /health returns 200', async () => {
13
+ const res = await fetch(`${cfg.apiUrl}/health`);
14
+ expect(res.status).toBe(200);
15
+ });
16
+
17
+ it('GET /health body contains status ok', async () => {
18
+ const res = await fetch(`${cfg.apiUrl}/health`);
19
+ const body = await res.json() as Record<string, unknown>;
20
+ expect(body.status ?? body.ok ?? body.alive).toBeTruthy();
21
+ });
22
+
23
+ it('unknown route returns 404, not 500', async () => {
24
+ const res = await fetch(`${cfg.apiUrl}/api/v1/does-not-exist-xyz`);
25
+ expect(res.status).toBe(404);
26
+ });
27
+ });
28
+
29
+ describe('Device flow init (no auth required)', () => {
30
+ it('GET /api/v1/auth/device/code returns device_code and user_code', async () => {
31
+ const res = await fetch(`${cfg.apiUrl}/api/v1/auth/device/code`);
32
+ expect(res.status).toBe(200);
33
+ const body = await res.json() as Record<string, unknown>;
34
+ expect(typeof body.device_code).toBe('string');
35
+ expect(typeof body.user_code).toBe('string');
36
+ expect(typeof body.verification_uri).toBe('string');
37
+ expect(body.verification_uri).toContain('cachly.dev');
38
+ });
39
+
40
+ it('device_code is at least 20 chars (not truncated)', async () => {
41
+ const res = await fetch(`${cfg.apiUrl}/api/v1/auth/device/code`);
42
+ const body = await res.json() as Record<string, unknown>;
43
+ expect((body.device_code as string).length).toBeGreaterThanOrEqual(20);
44
+ });
45
+
46
+ it('expires_in is a positive number', async () => {
47
+ const res = await fetch(`${cfg.apiUrl}/api/v1/auth/device/code`);
48
+ const body = await res.json() as Record<string, unknown>;
49
+ expect(Number(body.expires_in)).toBeGreaterThan(0);
50
+ });
51
+ });
52
+
53
+ describe('Badge endpoint (public, no auth)', () => {
54
+ it('returns 400 or 404 for an invalid instance id', async () => {
55
+ const res = await fetch(`${cfg.apiUrl}/api/v1/badge/not-a-real-uuid`);
56
+ expect([400, 404]).toContain(res.status);
57
+ });
58
+
59
+ it('returns badge JSON for a valid instance id', async () => {
60
+ if (!cfg.instanceId) return; // skip if not configured
61
+ const res = await fetch(`${cfg.apiUrl}/api/v1/badge/${cfg.instanceId}`);
62
+ expect(res.status).toBe(200);
63
+ const body = await res.json() as Record<string, unknown>;
64
+ expect(typeof body.schemaVersion).toBe('number');
65
+ expect(typeof body.label).toBe('string');
66
+ expect(typeof body.message).toBe('string');
67
+ });
68
+
69
+ it('badge message contains lesson count (numeric string)', async () => {
70
+ if (!cfg.instanceId) return;
71
+ const res = await fetch(`${cfg.apiUrl}/api/v1/badge/${cfg.instanceId}`);
72
+ const body = await res.json() as Record<string, unknown>;
73
+ expect((body.message as string)).toMatch(/\d+/);
74
+ });
75
+ });
76
+
77
+ describe('Telemetry endpoint (public)', () => {
78
+ it('POST /api/v1/telemetry/mcp accepts anonymous event', async () => {
79
+ const res = await fetch(`${cfg.apiUrl}/api/v1/telemetry/mcp`, {
80
+ method: 'POST',
81
+ headers: { 'Content-Type': 'application/json' },
82
+ body: JSON.stringify({ event: 'e2e_test_ping', version: '0.0.0', editor: 'test', source: 'e2e' }),
83
+ });
84
+ expect([200, 202, 204]).toContain(res.status);
85
+ });
86
+
87
+ it('POST /api/v1/telemetry/mcp accepts jwt-attributed event', async () => {
88
+ if (!cfg.jwt) return;
89
+ const res = await fetch(`${cfg.apiUrl}/api/v1/telemetry/mcp`, {
90
+ method: 'POST',
91
+ headers: { 'Content-Type': 'application/json' },
92
+ body: JSON.stringify({
93
+ event: 'e2e_test_ping_authed',
94
+ version: '0.0.0',
95
+ editor: 'test',
96
+ source: 'e2e',
97
+ jwt: cfg.jwt,
98
+ instance_id: cfg.instanceId,
99
+ }),
100
+ });
101
+ expect([200, 202, 204]).toContain(res.status);
102
+ });
103
+ });
@@ -0,0 +1,228 @@
1
+ /**
2
+ * E2E: CLI command smoke tests
3
+ *
4
+ * Spawns the actual CLI binary and verifies output + exit codes.
5
+ * Uses the built dist/ — run `npm run build` first.
6
+ *
7
+ * Requires: E2E_JWT, E2E_INSTANCE_ID (for health/badge/share)
8
+ * Run: npm run build && npx vitest run src/__tests__/e2e/cli.test.ts
9
+ */
10
+
11
+ import { describe, it, expect } from 'vitest';
12
+ import { spawnSync } from 'node:child_process';
13
+ import { join } from 'node:path';
14
+ import { cfg } from './config.js';
15
+
16
+ const BIN = join(import.meta.dirname, '../../../../dist/index.js');
17
+ const TIMEOUT_MS = 30_000;
18
+
19
+ function run(
20
+ args: string[],
21
+ env: Record<string, string> = {},
22
+ timeoutMs = TIMEOUT_MS,
23
+ ): { stdout: string; stderr: string; code: number | null } {
24
+ const result = spawnSync(process.execPath, [BIN, ...args], {
25
+ env: {
26
+ ...process.env,
27
+ CACHLY_JWT: cfg.jwt,
28
+ CACHLY_BRAIN_INSTANCE_ID: cfg.instanceId,
29
+ CACHLY_API_URL: cfg.apiUrl,
30
+ ...env,
31
+ },
32
+ timeout: timeoutMs,
33
+ encoding: 'utf8',
34
+ });
35
+ return {
36
+ stdout: result.stdout ?? '',
37
+ stderr: result.stderr ?? '',
38
+ code: result.status,
39
+ };
40
+ }
41
+
42
+ describe('cachly (no args) — help output', () => {
43
+ it('exits 0', () => {
44
+ const { code } = run([]);
45
+ expect(code).toBe(0);
46
+ });
47
+
48
+ it('prints cachly branding', () => {
49
+ const { stdout } = run([]);
50
+ expect(stdout).toMatch(/cachly/i);
51
+ });
52
+
53
+ it('lists setup command', () => {
54
+ const { stdout } = run([]);
55
+ expect(stdout).toContain('setup');
56
+ });
57
+
58
+ it('lists demo command', () => {
59
+ const { stdout } = run([]);
60
+ expect(stdout).toContain('demo');
61
+ });
62
+
63
+ it('mentions 1–5 minutes (no false "30 seconds" promise)', () => {
64
+ const { stdout } = run([]);
65
+ // Must NOT contain "30 seconds" — we corrected this in v0.10.19+
66
+ expect(stdout).not.toContain('30 seconds');
67
+ expect(stdout).not.toMatch(/\b30s\b/);
68
+ });
69
+
70
+ it('mentions free forever', () => {
71
+ const { stdout } = run([]);
72
+ expect(stdout.toLowerCase()).toMatch(/free|kostenlos/);
73
+ });
74
+ });
75
+
76
+ describe('cachly upgrade', () => {
77
+ it('exits 0', () => {
78
+ const { code } = run(['upgrade']);
79
+ expect(code).toBe(0);
80
+ });
81
+
82
+ it('prints current version', () => {
83
+ const { stdout } = run(['upgrade']);
84
+ expect(stdout).toMatch(/\d+\.\d+\.\d+/);
85
+ });
86
+
87
+ it('version string is valid semver', () => {
88
+ const { stdout } = run(['upgrade']);
89
+ const match = stdout.match(/(\d+\.\d+\.\d+)/);
90
+ expect(match).not.toBeNull();
91
+ const parts = match![1].split('.').map(Number);
92
+ expect(parts).toHaveLength(3);
93
+ parts.forEach((p) => expect(Number.isInteger(p)).toBe(true));
94
+ });
95
+
96
+ it('does not crash on npm registry timeout (graceful error)', () => {
97
+ const { code } = run(['upgrade'], { CACHLY_API_URL: 'http://127.0.0.1:1' });
98
+ // Should exit 0 or 1 — never crash with unhandled exception
99
+ expect([0, 1]).toContain(code);
100
+ });
101
+ });
102
+
103
+ describe('cachly demo', () => {
104
+ it('exits 0 even without credentials', () => {
105
+ const { code } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
106
+ expect(code).toBe(0);
107
+ });
108
+
109
+ it('prints Brain Preview header', () => {
110
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
111
+ expect(stdout).toMatch(/brain|preview|cachly/i);
112
+ });
113
+
114
+ it('prints setup command at the end', () => {
115
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
116
+ expect(stdout).toContain('setup');
117
+ });
118
+
119
+ it('does not crash with invalid git repo (fallback gracefully)', () => {
120
+ const { code } = run(['demo'], {
121
+ CACHLY_JWT: '',
122
+ CACHLY_BRAIN_INSTANCE_ID: '',
123
+ }, 15_000);
124
+ expect([0, 1]).toContain(code); // never 2+ (unhandled crash)
125
+ });
126
+
127
+ it('shows Brain Level (valid level name)', () => {
128
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
129
+ // Demo must show a valid brain level — Apprentice for new projects is expected
130
+ expect(stdout).toMatch(/Apprentice|Explorer|Expert|Architect|Oracle/);
131
+ });
132
+
133
+ it('shows 1–5 minutes in the CTA (no "30 seconds")', () => {
134
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
135
+ expect(stdout).toContain('1–5 minutes');
136
+ expect(stdout).not.toContain('30 seconds');
137
+ });
138
+
139
+ it('shows "never repeat" instead of "remember" for bug fixes', () => {
140
+ const { stdout } = run(['demo'], { CACHLY_JWT: '', CACHLY_BRAIN_INSTANCE_ID: '' }, 15_000);
141
+ // Copy should say "never repeat" not "remember" — old wording was weaker
142
+ if (stdout.includes('Bug fixes')) {
143
+ expect(stdout).toMatch(/never repeat/i);
144
+ }
145
+ });
146
+ });
147
+
148
+ describe('cachly health', () => {
149
+ it('exits 0 with valid credentials', () => {
150
+ if (!cfg.jwt || !cfg.instanceId) return;
151
+ const { code } = run(['health']);
152
+ expect(code).toBe(0);
153
+ });
154
+
155
+ it('prints API status', () => {
156
+ if (!cfg.jwt || !cfg.instanceId) return;
157
+ const { stdout } = run(['health']);
158
+ expect(stdout.toLowerCase()).toMatch(/api|status|ok|connected/);
159
+ });
160
+
161
+ it('prints editor detection results', () => {
162
+ if (!cfg.jwt || !cfg.instanceId) return;
163
+ const { stdout } = run(['health']);
164
+ expect(stdout.toLowerCase()).toMatch(/editor|claude|cursor|copilot|windsurf/);
165
+ });
166
+
167
+ it('exits non-zero without JWT', () => {
168
+ const { code, stdout } = run(['health'], { CACHLY_JWT: '' });
169
+ // Either exits non-zero, or prints an error message
170
+ const hasError = code !== 0 || stdout.toLowerCase().includes('not set') || stdout.toLowerCase().includes('sign in');
171
+ expect(hasError).toBe(true);
172
+ });
173
+ });
174
+
175
+ describe('cachly badge', () => {
176
+ it('exits 0 with valid instance', () => {
177
+ if (!cfg.jwt || !cfg.instanceId) return;
178
+ const { code } = run(['badge']);
179
+ expect(code).toBe(0);
180
+ });
181
+
182
+ it('outputs a markdown badge snippet', () => {
183
+ if (!cfg.jwt || !cfg.instanceId) return;
184
+ const { stdout } = run(['badge']);
185
+ expect(stdout).toMatch(/\[!\[.*cachly.*\]\(.*\)\]\(.*\)/i);
186
+ });
187
+
188
+ it('badge URL points to api.cachly.dev', () => {
189
+ if (!cfg.jwt || !cfg.instanceId) return;
190
+ const { stdout } = run(['badge']);
191
+ expect(stdout).toContain('api.cachly.dev');
192
+ });
193
+ });
194
+
195
+ describe('cachly share', () => {
196
+ it('exits 0 with valid credentials', () => {
197
+ if (!cfg.jwt || !cfg.instanceId) return;
198
+ const { code } = run(['share']);
199
+ expect(code).toBe(0);
200
+ });
201
+
202
+ it('output contains UTM share URL', () => {
203
+ if (!cfg.jwt || !cfg.instanceId) return;
204
+ const { stdout } = run(['share']);
205
+ expect(stdout).toContain('utm_source=x');
206
+ });
207
+
208
+ it('output contains tweet text', () => {
209
+ if (!cfg.jwt || !cfg.instanceId) return;
210
+ const { stdout } = run(['share']);
211
+ expect(stdout.toLowerCase()).toMatch(/tweet|x\.com|twitter/i);
212
+ });
213
+ });
214
+
215
+ describe('cachly invite', () => {
216
+ it('exits 0 and prints invite link', () => {
217
+ if (!cfg.jwt || !cfg.instanceId) return;
218
+ const { code, stdout } = run(['invite']);
219
+ expect(code).toBe(0);
220
+ expect(stdout).toMatch(/invite|join|cachly\.dev/i);
221
+ });
222
+
223
+ it('does NOT mention 30 seconds (1-5 minutes only)', () => {
224
+ if (!cfg.jwt || !cfg.instanceId) return;
225
+ const { stdout } = run(['invite']);
226
+ expect(stdout).not.toContain('30 seconds');
227
+ });
228
+ });
@@ -0,0 +1,53 @@
1
+ /**
2
+ * E2E test configuration — read from environment variables.
3
+ *
4
+ * Required for full e2e run:
5
+ * E2E_API_URL Base URL of the API server (default: https://api.cachly.dev)
6
+ * E2E_JWT Valid Keycloak JWT for a test user
7
+ * E2E_INSTANCE_ID ID of a pre-provisioned (active) Brain instance
8
+ * E2E_API_KEY Redis password for the test instance
9
+ * E2E_REDIS_HOST Redis host for the test instance
10
+ * E2E_REDIS_PORT Redis port (default: 6380)
11
+ * E2E_REDIS_TLS "true" if TLS is required (default: true)
12
+ *
13
+ * Optional:
14
+ * E2E_SKIP_SLOW "true" to skip provisioning + device-flow tests
15
+ */
16
+
17
+ export const cfg = {
18
+ apiUrl: process.env.E2E_API_URL ?? 'https://api.cachly.dev',
19
+ jwt: process.env.E2E_JWT ?? '',
20
+ instanceId: process.env.E2E_INSTANCE_ID ?? '',
21
+ apiKey: process.env.E2E_API_KEY ?? '',
22
+ redisHost: process.env.E2E_REDIS_HOST ?? '',
23
+ redisPort: Number(process.env.E2E_REDIS_PORT ?? '6380'),
24
+ redisTls: (process.env.E2E_REDIS_TLS ?? 'true') !== 'false',
25
+ skipSlow: process.env.E2E_SKIP_SLOW === 'true',
26
+ };
27
+
28
+ export function requireAuth() {
29
+ if (!cfg.jwt) throw new Error('E2E_JWT is required — run: export E2E_JWT=<your-token>');
30
+ if (!cfg.instanceId) throw new Error('E2E_INSTANCE_ID is required');
31
+ }
32
+
33
+ export function requireRedis() {
34
+ requireAuth();
35
+ if (!cfg.apiKey) throw new Error('E2E_API_KEY is required');
36
+ if (!cfg.redisHost) throw new Error('E2E_REDIS_HOST is required');
37
+ }
38
+
39
+ export async function apiGet(path: string, jwt = cfg.jwt) {
40
+ const res = await fetch(`${cfg.apiUrl}${path}`, {
41
+ headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
42
+ });
43
+ return { status: res.status, body: await res.json().catch(() => null) };
44
+ }
45
+
46
+ export async function apiPost(path: string, body: unknown, jwt = cfg.jwt) {
47
+ const res = await fetch(`${cfg.apiUrl}${path}`, {
48
+ method: 'POST',
49
+ headers: { Authorization: `Bearer ${jwt}`, 'Content-Type': 'application/json' },
50
+ body: JSON.stringify(body),
51
+ });
52
+ return { status: res.status, body: await res.json().catch(() => null) };
53
+ }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * E2E: Activation funnel telemetry
3
+ *
4
+ * Verifies that every funnel event:
5
+ * setup_started → device_flow_started → device_flow_completed →
6
+ * first_call_success → onboarding_completed
7
+ *
8
+ * is accepted by the API and (after Docker redeploy) persisted to mcp_events.
9
+ *
10
+ * Requires: E2E_JWT, E2E_INSTANCE_ID
11
+ * Run: npx vitest run src/__tests__/e2e/funnel.test.ts
12
+ */
13
+
14
+ import { describe, it, expect, beforeAll } from 'vitest';
15
+ import { cfg, requireAuth, apiGet } from './config.js';
16
+
17
+ beforeAll(() => requireAuth());
18
+
19
+ const FUNNEL_EVENTS = [
20
+ 'setup_started',
21
+ 'device_flow_started',
22
+ 'device_flow_completed',
23
+ 'auto_provision_started',
24
+ 'first_call_success',
25
+ 'onboarding_completed',
26
+ ] as const;
27
+
28
+ async function postTelemetry(event: string, extra: Record<string, unknown> = {}) {
29
+ return fetch(`${cfg.apiUrl}/api/v1/telemetry/mcp`, {
30
+ method: 'POST',
31
+ headers: { 'Content-Type': 'application/json' },
32
+ body: JSON.stringify({
33
+ event,
34
+ version: '0.10.24',
35
+ editor: 'claude',
36
+ source: 'e2e',
37
+ jwt: cfg.jwt,
38
+ instance_id: cfg.instanceId,
39
+ ...extra,
40
+ }),
41
+ });
42
+ }
43
+
44
+ describe('Funnel event acceptance', () => {
45
+ for (const event of FUNNEL_EVENTS) {
46
+ it(`POST ${event} returns 2xx`, async () => {
47
+ const res = await postTelemetry(event);
48
+ expect(res.status).toBeGreaterThanOrEqual(200);
49
+ expect(res.status).toBeLessThan(300);
50
+ });
51
+ }
52
+
53
+ it('unknown event is accepted (API is permissive)', async () => {
54
+ const res = await postTelemetry('e2e_unknown_event_xyz');
55
+ expect(res.status).toBeGreaterThanOrEqual(200);
56
+ expect(res.status).toBeLessThan(300);
57
+ });
58
+
59
+ it('event with no jwt is still accepted', async () => {
60
+ const res = await fetch(`${cfg.apiUrl}/api/v1/telemetry/mcp`, {
61
+ method: 'POST',
62
+ headers: { 'Content-Type': 'application/json' },
63
+ body: JSON.stringify({ event: 'setup_started', version: '0.10.24', editor: 'cursor', source: 'mcp' }),
64
+ });
65
+ expect(res.status).toBeGreaterThanOrEqual(200);
66
+ expect(res.status).toBeLessThan(300);
67
+ });
68
+ });
69
+
70
+ describe('first_call_success attribution', () => {
71
+ it('fires with tool and instance_id fields', async () => {
72
+ const res = await postTelemetry('first_call_success', {
73
+ tool: 'brain_recall',
74
+ instance_id: cfg.instanceId,
75
+ });
76
+ expect(res.status).toBeGreaterThanOrEqual(200);
77
+ expect(res.status).toBeLessThan(300);
78
+ });
79
+
80
+ it('fires for different tools', async () => {
81
+ for (const tool of ['brain_store', 'session_start', 'causal_trace']) {
82
+ const res = await postTelemetry('first_call_success', { tool, instance_id: cfg.instanceId });
83
+ expect(res.status).toBeGreaterThanOrEqual(200);
84
+ expect(res.status).toBeLessThan(300);
85
+ }
86
+ });
87
+ });
88
+
89
+ describe('Funnel stats endpoint (post-deploy only)', () => {
90
+ it('daily summary telemetry query is reachable', async () => {
91
+ // This verifies the mcp_events table exists after Docker redeploy.
92
+ // Hits /api/v1/admin/funnel if it exists, otherwise checks telemetry endpoint.
93
+ const { status } = await apiGet('/api/v1/admin/funnel');
94
+ // 200 = table exists and endpoint works
95
+ // 404 = endpoint not exposed (acceptable — internal only via watchdog)
96
+ // 401/403 = auth required (also acceptable)
97
+ expect([200, 401, 403, 404]).toContain(status);
98
+ });
99
+ });
@@ -0,0 +1,191 @@
1
+ /**
2
+ * E2E: MCP tool calls via live Redis connection
3
+ *
4
+ * Requires: E2E_JWT, E2E_INSTANCE_ID, E2E_API_KEY, E2E_REDIS_HOST
5
+ * Run: npx vitest run src/__tests__/e2e/mcp-tools.test.ts
6
+ */
7
+
8
+ import { describe, it, expect, beforeAll, afterAll } from 'vitest';
9
+ import { Redis } from 'ioredis';
10
+ import { cfg, requireRedis } from './config.js';
11
+
12
+ import { handleBrainTool } from '../../handlers/brain.js';
13
+ import { handleContextTool } from '../../handlers/context.js';
14
+
15
+ let redis: Redis;
16
+
17
+ function getConn(_id: string): Promise<Redis> {
18
+ return Promise.resolve(redis);
19
+ }
20
+
21
+ // ApiFetch matches the generic signature the handlers expect
22
+ async function apiFetch<T>(path: string, opts?: RequestInit): Promise<T> {
23
+ const res = await fetch(`${cfg.apiUrl}${path}`, {
24
+ ...opts,
25
+ headers: {
26
+ Authorization: `Bearer ${cfg.jwt}`,
27
+ 'Content-Type': 'application/json',
28
+ ...(opts?.headers as Record<string, string> ?? {}),
29
+ },
30
+ });
31
+ return res.json() as Promise<T>;
32
+ }
33
+
34
+ beforeAll(async () => {
35
+ requireRedis();
36
+ redis = new Redis({
37
+ host: cfg.redisHost,
38
+ port: cfg.redisPort,
39
+ password: cfg.apiKey,
40
+ tls: cfg.redisTls ? {} : undefined,
41
+ lazyConnect: true,
42
+ connectTimeout: 8000,
43
+ });
44
+ await redis.connect();
45
+ expect(await redis.ping()).toBe('PONG');
46
+ });
47
+
48
+ afterAll(async () => {
49
+ await redis.quit();
50
+ });
51
+
52
+ describe('Redis connectivity', () => {
53
+ it('PING returns PONG', async () => {
54
+ expect(await redis.ping()).toBe('PONG');
55
+ });
56
+
57
+ it('SET / GET round-trip works', async () => {
58
+ const key = `e2e:probe:${Date.now()}`;
59
+ await redis.set(key, 'ok', 'EX', 60);
60
+ expect(await redis.get(key)).toBe('ok');
61
+ await redis.del(key);
62
+ });
63
+ });
64
+
65
+ describe('session_start', () => {
66
+ it('returns a non-empty briefing string', async () => {
67
+ // session_start is handled by handleBrainTool, not handleContextTool
68
+ const result = await handleBrainTool(
69
+ 'session_start',
70
+ { instance_id: cfg.instanceId, focus: 'e2e-test' },
71
+ getConn,
72
+ apiFetch,
73
+ );
74
+ expect(typeof result === 'string' || result === null).toBe(true);
75
+ if (result !== null) expect(result.length).toBeGreaterThan(0);
76
+ });
77
+ });
78
+
79
+ describe('brain_store + brain_recall', () => {
80
+ const marker = `E2E-lesson-${Date.now()}`;
81
+
82
+ it('brain_store returns without error', async () => {
83
+ const result = await handleBrainTool(
84
+ 'brain_store',
85
+ {
86
+ instance_id: cfg.instanceId,
87
+ lesson: `${marker}: Redis race condition fixed with WAIT command`,
88
+ tags: ['e2e', 'redis', 'race-condition'],
89
+ severity: 'info',
90
+ },
91
+ getConn,
92
+ apiFetch,
93
+ );
94
+ // Returns a string (confirmation message) or null — never throws
95
+ expect(result === null || typeof result === 'string').toBe(true);
96
+ });
97
+
98
+ it('brain_recall finds the stored lesson', async () => {
99
+ await new Promise((r) => setTimeout(r, 400));
100
+ const result = await handleBrainTool(
101
+ 'brain_recall',
102
+ {
103
+ instance_id: cfg.instanceId,
104
+ query: marker,
105
+ limit: 5,
106
+ },
107
+ getConn,
108
+ apiFetch,
109
+ );
110
+ // Result is a formatted string with lessons, or null if empty
111
+ if (result !== null) {
112
+ expect(result).toContain(marker.split(':')[0]);
113
+ }
114
+ });
115
+
116
+ it('brain_recall handles unknown query gracefully (no throw)', async () => {
117
+ const result = await handleBrainTool(
118
+ 'brain_recall',
119
+ { instance_id: cfg.instanceId, query: 'xyzzy-no-match-e2e-99887766', limit: 3 },
120
+ getConn,
121
+ apiFetch,
122
+ );
123
+ expect(result === null || typeof result === 'string').toBe(true);
124
+ });
125
+ });
126
+
127
+ describe('brain_from_git (smoke)', () => {
128
+ it('responds without throwing', async () => {
129
+ const result = await handleBrainTool(
130
+ 'brain_from_git',
131
+ { instance_id: cfg.instanceId, max_commits: 5 },
132
+ getConn,
133
+ apiFetch,
134
+ );
135
+ expect(result === null || typeof result === 'string').toBe(true);
136
+ });
137
+ });
138
+
139
+ describe('causal_trace', () => {
140
+ it('returns a trace string without throwing', async () => {
141
+ const result = await handleBrainTool(
142
+ 'causal_trace',
143
+ { instance_id: cfg.instanceId, problem: 'auth breaks after restart', depth: 2 },
144
+ getConn,
145
+ apiFetch,
146
+ );
147
+ expect(result === null || typeof result === 'string').toBe(true);
148
+ });
149
+ });
150
+
151
+ describe('brain_predict', () => {
152
+ it('returns a prediction string without throwing', async () => {
153
+ const result = await handleBrainTool(
154
+ 'brain_predict',
155
+ { instance_id: cfg.instanceId, target: 'deploy' },
156
+ getConn,
157
+ apiFetch,
158
+ );
159
+ expect(result === null || typeof result === 'string').toBe(true);
160
+ });
161
+ });
162
+
163
+ describe('session_end', () => {
164
+ it('persists session summary without throwing', async () => {
165
+ const result = await handleContextTool(
166
+ 'session_end',
167
+ {
168
+ instance_id: cfg.instanceId,
169
+ summary: 'E2E test session completed.',
170
+ lessons: ['brain_recall round-trip verified', 'causal_trace responded correctly'],
171
+ },
172
+ getConn,
173
+ apiFetch,
174
+ );
175
+ expect(result === null || typeof result === 'string').toBe(true);
176
+ });
177
+ });
178
+
179
+ describe('brain_health', () => {
180
+ it('returns a health string containing a positive indicator', async () => {
181
+ const result = await handleBrainTool(
182
+ 'brain_health',
183
+ { instance_id: cfg.instanceId },
184
+ getConn,
185
+ apiFetch,
186
+ );
187
+ if (result !== null) {
188
+ expect(result.toLowerCase()).toMatch(/ok|healthy|active|ping|pong|connected/);
189
+ }
190
+ });
191
+ });