@prajwolkc/stk 0.6.1 → 0.7.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.
@@ -8,1561 +8,22 @@
8
8
  */
9
9
  import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
10
10
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
11
- import { z } from "zod";
12
- import { loadConfig, enabledServices } from "../lib/config.js";
13
- import { getChecker, allCheckerNames, loadPluginCheckers } from "../services/registry.js";
14
- import { getLocalBrainClient, ingestProject, loadBrainStore, saveBrainStore, syncBrain, pushToCloud, pullFromCloud, brainCheck, brainDiagnose } from "../services/brain.js";
15
- import { execSync } from "child_process";
11
+ import { registerInfraTools } from "./tools/infra.js";
12
+ import { registerOpsTools } from "./tools/ops.js";
13
+ import { registerDataTools } from "./tools/data.js";
14
+ import { registerBrainTools } from "./tools/brain.js";
15
+ import { registerGithubTools } from "./tools/github.js";
16
+ import { registerSecurityTools } from "./tools/security.js";
16
17
  const server = new McpServer({
17
18
  name: "stk",
18
- version: "0.2.0",
19
- });
20
- // ──────────────────────────────────────────
21
- // Tool: stk_health
22
- // ──────────────────────────────────────────
23
- server.tool("stk_health", "Check the health of all configured infrastructure services (databases, deploy providers, storage, billing). Returns structured results with status, latency, and details for each service.", {
24
- all: z.boolean().optional().describe("Check all known services, not just configured ones"),
25
- }, async ({ all }) => {
26
- await loadPluginCheckers();
27
- const config = loadConfig();
28
- const serviceList = all ? allCheckerNames() : enabledServices(config);
29
- const checks = serviceList.map(async (name) => {
30
- const checker = getChecker(name);
31
- if (!checker) {
32
- return { name, status: "skipped", detail: `unknown service "${name}"` };
33
- }
34
- return checker();
35
- });
36
- const results = await Promise.all(checks);
37
- const down = results.filter((r) => r.status === "down");
38
- return {
39
- content: [
40
- {
41
- type: "text",
42
- text: JSON.stringify({
43
- project: config.name,
44
- services: results,
45
- summary: {
46
- healthy: results.filter((r) => r.status === "healthy").length,
47
- down: down.length,
48
- skipped: results.filter((r) => r.status === "skipped").length,
49
- total: results.length,
50
- },
51
- ok: down.length === 0,
52
- }, null, 2),
53
- },
54
- ],
55
- };
56
- });
57
- // ──────────────────────────────────────────
58
- // Tool: stk_status
59
- // ──────────────────────────────────────────
60
- server.tool("stk_status", "Get a complete status overview: git state, service health, last deploy, and open issues — everything in one call.", {}, async () => {
61
- const config = loadConfig();
62
- const status = { project: config.name };
63
- // Git
64
- try {
65
- status.git = {
66
- branch: execSync("git rev-parse --abbrev-ref HEAD", { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim(),
67
- dirty: execSync("git status --porcelain", { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim().split("\n").filter(Boolean).length,
68
- lastCommit: execSync('git log -1 --format="%s"', { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim(),
69
- lastCommitAge: execSync('git log -1 --format="%cr"', { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim(),
70
- };
71
- }
72
- catch {
73
- status.git = null;
74
- }
75
- // Services
76
- await loadPluginCheckers();
77
- const serviceList = enabledServices(config);
78
- if (serviceList.length > 0) {
79
- const checks = serviceList.map(async (name) => {
80
- const checker = getChecker(name);
81
- if (!checker)
82
- return { name, status: "skipped" };
83
- return checker();
84
- });
85
- const results = await Promise.all(checks);
86
- status.services = {
87
- healthy: results.filter((r) => r.status === "healthy").length,
88
- down: results.filter((r) => r.status === "down").map((r) => r.name),
89
- skipped: results.filter((r) => r.status === "skipped").length,
90
- total: results.length,
91
- };
92
- }
93
- else {
94
- status.services = { total: 0, note: "no services configured" };
95
- }
96
- // Deploy
97
- if (process.env.VERCEL_TOKEN) {
98
- try {
99
- const res = await fetch("https://api.vercel.com/v6/deployments?limit=1", {
100
- headers: { Authorization: `Bearer ${process.env.VERCEL_TOKEN}` },
101
- });
102
- const data = (await res.json());
103
- const dep = data.deployments?.[0];
104
- if (dep) {
105
- status.lastDeploy = {
106
- provider: "vercel",
107
- state: dep.readyState ?? dep.state,
108
- url: dep.url,
109
- created: dep.created,
110
- };
111
- }
112
- }
113
- catch { /* skip */ }
114
- }
115
- return {
116
- content: [{ type: "text", text: JSON.stringify(status, null, 2) }],
117
- };
118
- });
119
- // ──────────────────────────────────────────
120
- // Tool: stk_doctor
121
- // ──────────────────────────────────────────
122
- server.tool("stk_doctor", "Diagnose infrastructure configuration issues. Checks for missing env vars, mismatched config, invalid URLs, and suggests fixes with documentation links.", {}, async () => {
123
- const config = loadConfig();
124
- const enabled = enabledServices(config);
125
- const issues = [];
126
- const ENV_REQS = {
127
- railway: { required: ["RAILWAY_API_TOKEN"], optional: ["RAILWAY_PROJECT_ID", "RAILWAY_ENVIRONMENT_ID", "RAILWAY_SERVICE_ID"] },
128
- vercel: { required: ["VERCEL_TOKEN"], optional: ["VERCEL_PROJECT_ID"] },
129
- fly: { required: ["FLY_API_TOKEN"], optional: ["FLY_APP_NAME"] },
130
- render: { required: ["RENDER_API_KEY"], optional: [] },
131
- aws: { required: ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY"], optional: ["AWS_REGION"] },
132
- database: { required: ["DATABASE_URL"], optional: [] },
133
- mongodb: { required: ["MONGODB_URL"], optional: [] },
134
- redis: { required: ["REDIS_URL"], optional: [] },
135
- supabase: { required: ["SUPABASE_URL"], optional: ["SUPABASE_SERVICE_KEY"] },
136
- r2: { required: ["CLOUDFLARE_ACCOUNT_ID", "CLOUDFLARE_API_TOKEN"], optional: [] },
137
- stripe: { required: ["STRIPE_SECRET_KEY"], optional: [] },
138
- };
139
- for (const svc of enabled) {
140
- const reqs = ENV_REQS[svc];
141
- if (!reqs)
142
- continue;
143
- const missingReq = reqs.required.filter((v) => !process.env[v]);
144
- const missingOpt = reqs.optional.filter((v) => !process.env[v]);
145
- if (missingReq.length > 0) {
146
- issues.push({ level: "error", service: svc, message: `Missing required: ${missingReq.join(", ")}` });
147
- }
148
- else {
149
- issues.push({ level: "ok", service: svc, message: "Configured correctly" });
150
- }
151
- if (missingOpt.length > 0) {
152
- issues.push({ level: "warn", service: svc, message: `Missing optional: ${missingOpt.join(", ")}`, fix: "Needed for logs, env sync, deploy watching" });
153
- }
154
- }
155
- return {
156
- content: [{
157
- type: "text",
158
- text: JSON.stringify({
159
- project: config.name,
160
- issues,
161
- summary: {
162
- errors: issues.filter((i) => i.level === "error").length,
163
- warnings: issues.filter((i) => i.level === "warn").length,
164
- ok: issues.filter((i) => i.level === "ok").length,
165
- },
166
- }, null, 2),
167
- }],
168
- };
169
- });
170
- // ──────────────────────────────────────────
171
- // Tool: stk_logs
172
- // ──────────────────────────────────────────
173
- server.tool("stk_logs", "Fetch recent production logs from Railway, Vercel, or other deploy providers. Useful for diagnosing errors and understanding runtime behavior.", {
174
- provider: z.enum(["railway", "vercel"]).optional().describe("Which provider to fetch logs from (auto-detects if omitted)"),
175
- lines: z.number().optional().default(30).describe("Number of log lines to fetch"),
176
- }, async ({ provider, lines }) => {
177
- // Railway logs
178
- if ((provider === "railway" || !provider) && process.env.RAILWAY_API_TOKEN) {
179
- const token = process.env.RAILWAY_API_TOKEN;
180
- const projectId = process.env.RAILWAY_PROJECT_ID;
181
- const serviceId = process.env.RAILWAY_SERVICE_ID;
182
- if (!projectId) {
183
- return { content: [{ type: "text", text: JSON.stringify({ error: "RAILWAY_PROJECT_ID not set" }) }] };
184
- }
185
- // Get latest deployment
186
- const serviceFilter = serviceId ? `serviceId: "${serviceId}",` : "";
187
- const depRes = await fetch("https://backboard.railway.com/graphql/v2", {
188
- method: "POST",
189
- headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
190
- body: JSON.stringify({
191
- query: `{ deployments(first: 1, input: { projectId: "${projectId}", ${serviceFilter} }) { edges { node { id } } } }`,
192
- }),
193
- });
194
- const depData = (await depRes.json());
195
- const deploymentId = depData.data?.deployments?.edges?.[0]?.node?.id;
196
- if (!deploymentId) {
197
- return { content: [{ type: "text", text: JSON.stringify({ error: "No deployments found" }) }] };
198
- }
199
- const logRes = await fetch("https://backboard.railway.com/graphql/v2", {
200
- method: "POST",
201
- headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
202
- body: JSON.stringify({
203
- query: `{ deploymentLogs(deploymentId: "${deploymentId}", limit: ${lines}) { timestamp message severity } }`,
204
- }),
205
- });
206
- const logData = (await logRes.json());
207
- const logs = logData.data?.deploymentLogs ?? [];
208
- return {
209
- content: [{ type: "text", text: JSON.stringify({ provider: "railway", deploymentId, logs }, null, 2) }],
210
- };
211
- }
212
- // Vercel logs
213
- if ((provider === "vercel" || !provider) && process.env.VERCEL_TOKEN) {
214
- const token = process.env.VERCEL_TOKEN;
215
- const depRes = await fetch("https://api.vercel.com/v6/deployments?limit=1", {
216
- headers: { Authorization: `Bearer ${token}` },
217
- });
218
- const depData = (await depRes.json());
219
- const dep = depData.deployments?.[0];
220
- if (!dep) {
221
- return { content: [{ type: "text", text: JSON.stringify({ error: "No deployments found" }) }] };
222
- }
223
- const logRes = await fetch(`https://api.vercel.com/v2/deployments/${dep.uid}/events`, {
224
- headers: { Authorization: `Bearer ${token}` },
225
- });
226
- const events = (await logRes.json());
227
- const logs = Array.isArray(events)
228
- ? events
229
- .filter((e) => e.type === "stdout" || e.type === "stderr")
230
- .slice(-lines)
231
- .map((e) => ({
232
- timestamp: new Date(e.created).toISOString(),
233
- message: e.payload?.text ?? e.text ?? "",
234
- severity: e.type === "stderr" ? "ERROR" : "INFO",
235
- }))
236
- : [];
237
- return {
238
- content: [{ type: "text", text: JSON.stringify({ provider: "vercel", deploymentUrl: dep.url, logs }, null, 2) }],
239
- };
240
- }
241
- return {
242
- content: [{ type: "text", text: JSON.stringify({ error: "No log provider available. Set RAILWAY_API_TOKEN or VERCEL_TOKEN." }) }],
243
- };
244
- });
245
- // ──────────────────────────────────────────
246
- // Tool: stk_todo_list
247
- // ──────────────────────────────────────────
248
- server.tool("stk_todo_list", "List open GitHub issues for this project. Helps understand what needs to be worked on.", {
249
- label: z.string().optional().describe("Filter by label"),
250
- limit: z.number().optional().default(15).describe("Max issues to return"),
251
- }, async ({ label, limit }) => {
252
- const config = loadConfig();
253
- const repo = config.github?.repo ?? process.env.GITHUB_REPO ?? detectGitHubRepo();
254
- const token = process.env.GITHUB_TOKEN;
255
- if (!repo) {
256
- return { content: [{ type: "text", text: JSON.stringify({ error: "Could not detect GitHub repo. Set GITHUB_REPO or add github.repo to stk.config.json" }) }] };
257
- }
258
- const params = new URLSearchParams({
259
- state: "open",
260
- per_page: String(limit),
261
- sort: "updated",
262
- direction: "desc",
263
- });
264
- if (label)
265
- params.set("labels", label);
266
- const headers = { Accept: "application/vnd.github+json" };
267
- if (token)
268
- headers.Authorization = `Bearer ${token}`;
269
- const res = await fetch(`https://api.github.com/repos/${repo}/issues?${params}`, { headers });
270
- if (!res.ok) {
271
- return { content: [{ type: "text", text: JSON.stringify({ error: `GitHub API: ${res.status}` }) }] };
272
- }
273
- const issues = (await res.json());
274
- const filtered = issues
275
- .filter((i) => !i.pull_request)
276
- .map((i) => ({
277
- number: i.number,
278
- title: i.title,
279
- labels: i.labels.map((l) => l.name),
280
- assignee: i.assignee?.login ?? null,
281
- created: i.created_at,
282
- url: i.html_url,
283
- }));
284
- return {
285
- content: [{ type: "text", text: JSON.stringify({ repo, issues: filtered }, null, 2) }],
286
- };
287
- });
288
- // ──────────────────────────────────────────
289
- // Tool: stk_todo_add
290
- // ──────────────────────────────────────────
291
- server.tool("stk_todo_add", "Create a new GitHub issue for this project.", {
292
- title: z.string().describe("Issue title"),
293
- body: z.string().optional().describe("Issue body/description"),
294
- labels: z.array(z.string()).optional().describe("Labels to add"),
295
- }, async ({ title, body, labels }) => {
296
- const config = loadConfig();
297
- const repo = config.github?.repo ?? process.env.GITHUB_REPO ?? detectGitHubRepo();
298
- const token = process.env.GITHUB_TOKEN;
299
- if (!repo || !token) {
300
- return { content: [{ type: "text", text: JSON.stringify({ error: "Need GITHUB_TOKEN and repo to create issues" }) }] };
301
- }
302
- const payload = { title };
303
- if (body)
304
- payload.body = body;
305
- if (labels)
306
- payload.labels = labels;
307
- const res = await fetch(`https://api.github.com/repos/${repo}/issues`, {
308
- method: "POST",
309
- headers: {
310
- Authorization: `Bearer ${token}`,
311
- Accept: "application/vnd.github+json",
312
- "Content-Type": "application/json",
313
- },
314
- body: JSON.stringify(payload),
315
- });
316
- if (!res.ok) {
317
- const data = (await res.json());
318
- return { content: [{ type: "text", text: JSON.stringify({ error: data.message ?? `HTTP ${res.status}` }) }] };
319
- }
320
- const issue = (await res.json());
321
- return {
322
- content: [{ type: "text", text: JSON.stringify({ created: true, number: issue.number, url: issue.html_url }, null, 2) }],
323
- };
324
- });
325
- // ──────────────────────────────────────────
326
- // Tool: stk_deploy
327
- // ──────────────────────────────────────────
328
- server.tool("stk_deploy", "Push current branch to remote and trigger deploys. Use with caution — this pushes code to production.", {
329
- skipPush: z.boolean().optional().describe("Skip git push, just report current deploy status"),
330
- }, async ({ skipPush }) => {
331
- const config = loadConfig();
332
- const branch = config.deploy?.branch ?? "main";
333
- if (!skipPush) {
334
- try {
335
- const currentBranch = execSync("git rev-parse --abbrev-ref HEAD", { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
336
- if (currentBranch !== branch) {
337
- return {
338
- content: [{ type: "text", text: JSON.stringify({ error: `On branch "${currentBranch}", not "${branch}". Switch branches first.` }) }],
339
- };
340
- }
341
- execSync(`git push origin ${branch}`, { encoding: "utf-8", stdio: "pipe" });
342
- }
343
- catch (err) {
344
- return {
345
- content: [{ type: "text", text: JSON.stringify({ error: `Git push failed: ${err.message}` }) }],
346
- };
347
- }
348
- }
349
- return {
350
- content: [{
351
- type: "text",
352
- text: JSON.stringify({
353
- pushed: !skipPush,
354
- branch,
355
- providers: config.deploy?.providers ?? [],
356
- note: "Deploy triggered. Use stk_health to verify after a few minutes.",
357
- }, null, 2),
358
- }],
359
- };
360
- });
361
- // ──────────────────────────────────────────
362
- // Tool: stk_config
363
- // ──────────────────────────────────────────
364
- server.tool("stk_config", "Read the current stk configuration for this project. Shows which services are enabled, deploy settings, and project name.", {}, async () => {
365
- const config = loadConfig();
366
- return {
367
- content: [{ type: "text", text: JSON.stringify(config, null, 2) }],
368
- };
369
- });
370
- // ──────────────────────────────────────────
371
- // Tool: stk_db
372
- // ──────────────────────────────────────────
373
- server.tool("stk_db", "Query your Supabase database directly. Run SELECT queries, check row counts, inspect table data — all from chat. Only read operations are allowed for safety.", {
374
- query: z.string().optional().describe("SQL query to run (SELECT only for safety)"),
375
- table: z.string().optional().describe("Shorthand: just provide a table name to SELECT * with a limit"),
376
- limit: z.number().optional().describe("Max rows to return (default 20)"),
377
- }, async ({ query, table, limit: rawLimit }) => {
378
- const limit = rawLimit ?? 20;
379
- const url = process.env.SUPABASE_URL;
380
- const key = process.env.SUPABASE_SERVICE_KEY;
381
- if (!url || !key) {
382
- return { content: [{ type: "text", text: JSON.stringify({ error: "SUPABASE_URL or SUPABASE_SERVICE_KEY not set" }) }] };
383
- }
384
- // If table shorthand is used, build a simple query
385
- let sql = query ?? "";
386
- if (table && !query) {
387
- sql = `SELECT * FROM ${table} ORDER BY created_at DESC LIMIT ${limit}`;
388
- }
389
- if (!sql && !table) {
390
- return { content: [{ type: "text", text: JSON.stringify({ error: "Provide either a 'query' or 'table' parameter" }) }] };
391
- }
392
- // Safety: only allow read operations
393
- const normalized = sql.trim().toUpperCase();
394
- if (!normalized.startsWith("SELECT") && !normalized.startsWith("WITH")) {
395
- return { content: [{ type: "text", text: JSON.stringify({ error: "Only SELECT/WITH queries are allowed for safety. Use Supabase dashboard for mutations." }) }] };
396
- }
397
- try {
398
- const res = await fetch(`${url}/rest/v1/rpc/`, {
399
- method: "POST",
400
- headers: {
401
- apikey: key,
402
- Authorization: `Bearer ${key}`,
403
- "Content-Type": "application/json",
404
- Prefer: "return=representation",
405
- },
406
- body: JSON.stringify({}),
407
- });
408
- // Use PostgREST query instead of RPC for better compatibility
409
- // Parse table name from SQL for simple queries
410
- const tableMatch = sql.match(/FROM\s+["']?(\w+)["']?/i);
411
- const targetTable = table ?? tableMatch?.[1];
412
- if (targetTable) {
413
- const restRes = await fetch(`${url}/rest/v1/${targetTable}?select=*&limit=${limit}`, {
414
- headers: {
415
- apikey: key,
416
- Authorization: `Bearer ${key}`,
417
- "Content-Type": "application/json",
418
- Prefer: "count=exact",
419
- },
420
- });
421
- if (!restRes.ok) {
422
- const errText = await restRes.text();
423
- return { content: [{ type: "text", text: JSON.stringify({ error: `Query failed: ${errText}` }) }] };
424
- }
425
- const contentRange = restRes.headers.get("content-range");
426
- const totalCount = contentRange ? contentRange.split("/")[1] : "unknown";
427
- const data = await restRes.json();
428
- return {
429
- content: [{
430
- type: "text",
431
- text: JSON.stringify({
432
- table: targetTable,
433
- totalRows: totalCount,
434
- returned: Array.isArray(data) ? data.length : 0,
435
- data,
436
- }, null, 2),
437
- }],
438
- };
439
- }
440
- return { content: [{ type: "text", text: JSON.stringify({ error: "Could not parse table name from query. Use the 'table' parameter instead." }) }] };
441
- }
442
- catch (err) {
443
- return { content: [{ type: "text", text: JSON.stringify({ error: err.message }) }] };
444
- }
445
- });
446
- // ──────────────────────────────────────────
447
- // Tool: stk_analytics
448
- // ──────────────────────────────────────────
449
- server.tool("stk_analytics", "Get live app analytics: total users, posts, payments, revenue, and recent activity. Pulls data from Supabase and Stripe in one call.", {}, async () => {
450
- const results = {};
451
- // Supabase stats
452
- const url = process.env.SUPABASE_URL;
453
- const key = process.env.SUPABASE_SERVICE_KEY;
454
- if (url && key) {
455
- const headers = {
456
- apikey: key,
457
- Authorization: `Bearer ${key}`,
458
- Prefer: "count=exact",
459
- };
460
- // Get table counts in parallel
461
- const [postsRes, usersRes, paymentsRes] = await Promise.all([
462
- fetch(`${url}/rest/v1/posts?select=id&limit=0`, { headers }).catch(() => null),
463
- fetch(`${url}/rest/v1/users?select=id&limit=0`, { headers }).catch(() => null),
464
- fetch(`${url}/rest/v1/payments?select=id&limit=0`, { headers }).catch(() => null),
465
- ]);
466
- const getCount = (res) => {
467
- if (!res?.ok)
468
- return null;
469
- const range = res.headers.get("content-range");
470
- return range ? parseInt(range.split("/")[1]) || 0 : null;
471
- };
472
- results.supabase = {
473
- totalPosts: getCount(postsRes),
474
- totalUsers: getCount(usersRes),
475
- totalPayments: getCount(paymentsRes),
476
- };
477
- // Recent posts (last 24h)
478
- const oneDayAgo = Math.floor(Date.now() / 1000) - 86400;
479
- const recentRes = await fetch(`${url}/rest/v1/posts?select=id&timestamp=gte.${oneDayAgo}&limit=0`, { headers: { ...headers, Prefer: "count=exact" } }).catch(() => null);
480
- results.supabase.postsLast24h = getCount(recentRes);
481
- // Recent users with paid posts
482
- const paidUsersRes = await fetch(`${url}/rest/v1/users?select=id&paid_posts_available=gt.0&limit=0`, { headers: { ...headers, Prefer: "count=exact" } }).catch(() => null);
483
- results.supabase.usersWithPaidPosts = getCount(paidUsersRes);
484
- }
485
- // Stripe stats
486
- const stripeKey = process.env.STRIPE_SECRET_KEY;
487
- if (stripeKey) {
488
- try {
489
- // Balance
490
- const balRes = await fetch("https://api.stripe.com/v1/balance", {
491
- headers: { Authorization: `Bearer ${stripeKey}` },
492
- });
493
- const balData = await balRes.json();
494
- // Recent charges
495
- const chargesRes = await fetch("https://api.stripe.com/v1/charges?limit=100", {
496
- headers: { Authorization: `Bearer ${stripeKey}` },
497
- });
498
- const chargesData = await chargesRes.json();
499
- const charges = chargesData.data ?? [];
500
- const totalRevenue = charges.reduce((sum, c) => sum + (c.status === "succeeded" ? c.amount : 0), 0);
501
- results.stripe = {
502
- balance: balData.available?.map((b) => `${(b.amount / 100).toFixed(2)} ${b.currency.toUpperCase()}`) ?? [],
503
- totalCharges: charges.length,
504
- successfulCharges: charges.filter((c) => c.status === "succeeded").length,
505
- totalRevenue: `${(totalRevenue / 100).toFixed(2)}`,
506
- mode: stripeKey.startsWith("sk_live") ? "live" : "test",
507
- };
508
- }
509
- catch (err) {
510
- results.stripe = { error: err.message };
511
- }
512
- }
513
- return {
514
- content: [{ type: "text", text: JSON.stringify({ analytics: results }, null, 2) }],
515
- };
516
- });
517
- // ──────────────────────────────────────────
518
- // Tool: stk_alerts
519
- // ──────────────────────────────────────────
520
- server.tool("stk_alerts", "Scan for problems across your entire stack: failed deploys, down services, error logs, Stripe failures, and database issues. Returns actionable alerts.", {}, async () => {
521
- await loadPluginCheckers();
522
- const config = loadConfig();
523
- const alerts = [];
524
- // 1. Check all service health
525
- const serviceList = enabledServices(config);
526
- const checks = serviceList.map(async (name) => {
527
- const checker = getChecker(name);
528
- if (!checker)
529
- return null;
530
- return checker();
531
- });
532
- const results = (await Promise.all(checks)).filter(Boolean);
533
- for (const r of results) {
534
- if (r.status === "down") {
535
- alerts.push({ level: "critical", source: r.name, message: `Service is DOWN: ${r.detail ?? "unreachable"}` });
536
- }
537
- else if (r.status === "degraded") {
538
- alerts.push({ level: "warning", source: r.name, message: `Service degraded: ${r.detail ?? "slow response"}` });
539
- }
540
- else if (r.latency && r.latency > 3000) {
541
- alerts.push({ level: "warning", source: r.name, message: `High latency: ${r.latency}ms` });
542
- }
543
- }
544
- // 2. Check Vercel for failed deploys
545
- if (process.env.VERCEL_TOKEN) {
546
- try {
547
- const res = await fetch("https://api.vercel.com/v6/deployments?limit=5", {
548
- headers: { Authorization: `Bearer ${process.env.VERCEL_TOKEN}` },
549
- });
550
- const data = await res.json();
551
- for (const dep of data.deployments ?? []) {
552
- const state = dep.readyState ?? dep.state;
553
- if (state === "ERROR" || state === "CANCELED") {
554
- alerts.push({ level: "critical", source: "Vercel", message: `Deploy ${state}: ${dep.url ?? dep.uid}` });
555
- }
556
- }
557
- }
558
- catch { /* skip */ }
559
- }
560
- // 3. Check Stripe for recent failures
561
- if (process.env.STRIPE_SECRET_KEY) {
562
- try {
563
- const res = await fetch("https://api.stripe.com/v1/charges?limit=20", {
564
- headers: { Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}` },
565
- });
566
- const data = await res.json();
567
- const failed = (data.data ?? []).filter((c) => c.status === "failed");
568
- if (failed.length > 0) {
569
- alerts.push({ level: "warning", source: "Stripe", message: `${failed.length} failed charge(s) in recent transactions` });
570
- }
571
- }
572
- catch { /* skip */ }
573
- }
574
- // 4. Check for error logs in Vercel
575
- if (process.env.VERCEL_TOKEN) {
576
- try {
577
- const depRes = await fetch("https://api.vercel.com/v6/deployments?limit=1", {
578
- headers: { Authorization: `Bearer ${process.env.VERCEL_TOKEN}` },
579
- });
580
- const depData = await depRes.json();
581
- const dep = depData.deployments?.[0];
582
- if (dep) {
583
- const logRes = await fetch(`https://api.vercel.com/v2/deployments/${dep.uid}/events`, {
584
- headers: { Authorization: `Bearer ${process.env.VERCEL_TOKEN}` },
585
- });
586
- const events = await logRes.json();
587
- if (Array.isArray(events)) {
588
- const errors = events.filter((e) => e.type === "stderr");
589
- if (errors.length > 5) {
590
- alerts.push({ level: "warning", source: "Vercel Logs", message: `${errors.length} stderr entries in latest deploy` });
591
- }
592
- }
593
- }
594
- }
595
- catch { /* skip */ }
596
- }
597
- if (alerts.length === 0) {
598
- alerts.push({ level: "info", source: "stk", message: "All clear — no issues detected" });
599
- }
600
- return {
601
- content: [{
602
- type: "text",
603
- text: JSON.stringify({
604
- project: config.name,
605
- alerts,
606
- summary: {
607
- critical: alerts.filter((a) => a.level === "critical").length,
608
- warnings: alerts.filter((a) => a.level === "warning").length,
609
- ok: alerts.every((a) => a.level === "info"),
610
- },
611
- }, null, 2),
612
- }],
613
- };
614
- });
615
- // ──────────────────────────────────────────
616
- // Tool: stk_rollback
617
- // ──────────────────────────────────────────
618
- server.tool("stk_rollback", "Rollback to a previous Vercel deployment. Lists recent deploys and can promote an older one to production.", {
619
- deployId: z.string().optional().describe("Deployment ID to rollback to. If omitted, lists recent deployments to choose from."),
620
- confirm: z.boolean().optional().default(false).describe("Must be true to actually execute the rollback"),
621
- }, async ({ deployId, confirm }) => {
622
- const token = process.env.VERCEL_TOKEN;
623
- if (!token) {
624
- return { content: [{ type: "text", text: JSON.stringify({ error: "VERCEL_TOKEN not set" }) }] };
625
- }
626
- // List recent deployments
627
- const depRes = await fetch("https://api.vercel.com/v6/deployments?limit=10", {
628
- headers: { Authorization: `Bearer ${token}` },
629
- });
630
- const depData = await depRes.json();
631
- const deployments = (depData.deployments ?? []).map((d) => ({
632
- id: d.uid,
633
- url: d.url,
634
- state: d.readyState ?? d.state,
635
- created: new Date(d.created).toISOString(),
636
- target: d.target ?? "preview",
637
- }));
638
- if (!deployId) {
639
- return {
640
- content: [{
641
- type: "text",
642
- text: JSON.stringify({
643
- message: "Recent deployments — provide a deployId to rollback",
644
- deployments,
645
- }, null, 2),
646
- }],
647
- };
648
- }
649
- if (!confirm) {
650
- const target = deployments.find((d) => d.id === deployId);
651
- return {
652
- content: [{
653
- type: "text",
654
- text: JSON.stringify({
655
- message: "Rollback requires confirmation. Call again with confirm: true",
656
- target: target ?? deployId,
657
- }, null, 2),
658
- }],
659
- };
660
- }
661
- // Execute rollback by promoting the old deployment
662
- try {
663
- // Get the deployment's project
664
- const detailRes = await fetch(`https://api.vercel.com/v13/deployments/${deployId}`, {
665
- headers: { Authorization: `Bearer ${token}` },
666
- });
667
- const detail = await detailRes.json();
668
- const projectId = detail.projectId;
669
- if (!projectId) {
670
- return { content: [{ type: "text", text: JSON.stringify({ error: "Could not determine project from deployment" }) }] };
671
- }
672
- // Create a new deployment based on the old one (redeploy)
673
- const rollbackRes = await fetch(`https://api.vercel.com/v13/deployments`, {
674
- method: "POST",
675
- headers: {
676
- Authorization: `Bearer ${token}`,
677
- "Content-Type": "application/json",
678
- },
679
- body: JSON.stringify({
680
- name: detail.name,
681
- deploymentId: deployId,
682
- target: "production",
683
- }),
684
- });
685
- if (!rollbackRes.ok) {
686
- const errData = await rollbackRes.json();
687
- return { content: [{ type: "text", text: JSON.stringify({ error: errData.error?.message ?? `HTTP ${rollbackRes.status}` }) }] };
688
- }
689
- const rollbackData = await rollbackRes.json();
690
- return {
691
- content: [{
692
- type: "text",
693
- text: JSON.stringify({
694
- rolledBack: true,
695
- newDeploymentId: rollbackData.id,
696
- url: rollbackData.url,
697
- note: "Rollback triggered. Use stk_health to verify.",
698
- }, null, 2),
699
- }],
700
- };
701
- }
702
- catch (err) {
703
- return { content: [{ type: "text", text: JSON.stringify({ error: err.message }) }] };
704
- }
705
- });
706
- // ──────────────────────────────────────────
707
- // Tool: stk_env_sync
708
- // ──────────────────────────────────────────
709
- server.tool("stk_env_sync", "Compare and sync environment variables between local .env and Vercel. Shows which vars are missing, extra, or mismatched.", {
710
- action: z.enum(["diff", "pull", "push"]).optional().default("diff").describe("diff: compare local vs remote. pull: download remote to .env.pulled. push: upload local to Vercel."),
711
- confirm: z.boolean().optional().default(false).describe("Required for push action"),
712
- }, async ({ action, confirm }) => {
713
- const token = process.env.VERCEL_TOKEN;
714
- const projectId = process.env.VERCEL_PROJECT_ID;
715
- // Read local .env
716
- let localVars = {};
717
- try {
718
- const { readFileSync } = await import("fs");
719
- const envContent = readFileSync(".env", "utf-8");
720
- for (const line of envContent.split("\n")) {
721
- const trimmed = line.trim();
722
- if (!trimmed || trimmed.startsWith("#"))
723
- continue;
724
- const eqIdx = trimmed.indexOf("=");
725
- if (eqIdx > 0) {
726
- localVars[trimmed.slice(0, eqIdx)] = trimmed.slice(eqIdx + 1);
727
- }
728
- }
729
- }
730
- catch {
731
- localVars = {};
732
- }
733
- if (!token) {
734
- return {
735
- content: [{
736
- type: "text",
737
- text: JSON.stringify({
738
- localVars: Object.keys(localVars),
739
- remote: "VERCEL_TOKEN not set — cannot fetch remote env vars",
740
- }, null, 2),
741
- }],
742
- };
743
- }
744
- // Fetch Vercel env vars
745
- let remoteVars = {};
746
- const envUrl = projectId
747
- ? `https://api.vercel.com/v9/projects/${projectId}/env`
748
- : null;
749
- if (envUrl) {
750
- try {
751
- const res = await fetch(envUrl, {
752
- headers: { Authorization: `Bearer ${token}` },
753
- });
754
- const data = await res.json();
755
- for (const env of data.envs ?? []) {
756
- remoteVars[env.key] = env.value ?? "(encrypted)";
757
- }
758
- }
759
- catch { /* skip */ }
760
- }
761
- const localKeys = new Set(Object.keys(localVars));
762
- const remoteKeys = new Set(Object.keys(remoteVars));
763
- const onlyLocal = [...localKeys].filter((k) => !remoteKeys.has(k));
764
- const onlyRemote = [...remoteKeys].filter((k) => !localKeys.has(k));
765
- const shared = [...localKeys].filter((k) => remoteKeys.has(k));
766
- if (action === "diff" || !action) {
767
- return {
768
- content: [{
769
- type: "text",
770
- text: JSON.stringify({
771
- localCount: localKeys.size,
772
- remoteCount: remoteKeys.size,
773
- onlyInLocal: onlyLocal,
774
- onlyInRemote: onlyRemote,
775
- inBoth: shared.length,
776
- note: projectId ? undefined : "Set VERCEL_PROJECT_ID for remote env comparison",
777
- }, null, 2),
778
- }],
779
- };
780
- }
781
- if (action === "pull") {
782
- const { writeFileSync } = await import("fs");
783
- const lines = Object.entries(remoteVars).map(([k, v]) => `${k}=${v}`);
784
- writeFileSync(".env.pulled", lines.join("\n") + "\n");
785
- return {
786
- content: [{ type: "text", text: JSON.stringify({ pulled: true, file: ".env.pulled", count: lines.length }) }],
787
- };
788
- }
789
- if (action === "push") {
790
- if (!confirm) {
791
- return {
792
- content: [{ type: "text", text: JSON.stringify({ message: "Push requires confirm: true. This will overwrite remote env vars.", varsToUpload: onlyLocal.length + shared.length }) }],
793
- };
794
- }
795
- if (!projectId || !envUrl) {
796
- return { content: [{ type: "text", text: JSON.stringify({ error: "VERCEL_PROJECT_ID required for push" }) }] };
797
- }
798
- let uploaded = 0;
799
- for (const [key, value] of Object.entries(localVars)) {
800
- await fetch(envUrl, {
801
- method: "POST",
802
- headers: {
803
- Authorization: `Bearer ${token}`,
804
- "Content-Type": "application/json",
805
- },
806
- body: JSON.stringify({
807
- key,
808
- value,
809
- type: "encrypted",
810
- target: ["production", "preview", "development"],
811
- }),
812
- });
813
- uploaded++;
814
- }
815
- return {
816
- content: [{ type: "text", text: JSON.stringify({ pushed: true, uploaded }) }],
817
- };
818
- }
819
- return { content: [{ type: "text", text: JSON.stringify({ error: "Unknown action" }) }] };
820
- });
821
- // ──────────────────────────────────────────
822
- // Tool: stk_perf
823
- // ──────────────────────────────────────────
824
- server.tool("stk_perf", "Check performance across your stack: Supabase query latency, table sizes, Vercel deploy times, and API response times.", {
825
- tables: z.array(z.string()).optional().describe("Specific Supabase tables to benchmark (defaults to all detected)"),
826
- }, async ({ tables }) => {
827
- const perf = {};
828
- // Supabase performance
829
- const url = process.env.SUPABASE_URL;
830
- const key = process.env.SUPABASE_SERVICE_KEY;
831
- if (url && key) {
832
- const headers = {
833
- apikey: key,
834
- Authorization: `Bearer ${key}`,
835
- Prefer: "count=exact",
836
- };
837
- // Auto-detect tables or use provided list
838
- const tablesToCheck = tables ?? ["posts", "users", "payments"];
839
- const tableStats = [];
840
- for (const table of tablesToCheck) {
841
- const start = Date.now();
842
- try {
843
- const res = await fetch(`${url}/rest/v1/${table}?select=id&limit=0`, {
844
- headers,
845
- });
846
- const latency = Date.now() - start;
847
- const range = res.headers.get("content-range");
848
- const count = range ? parseInt(range.split("/")[1]) || 0 : null;
849
- let status = "fast";
850
- if (latency > 1000)
851
- status = "slow";
852
- else if (latency > 500)
853
- status = "moderate";
854
- tableStats.push({ table, rowCount: count, queryLatency: latency, status });
855
- }
856
- catch {
857
- tableStats.push({ table, rowCount: null, queryLatency: Date.now() - start, status: "error" });
858
- }
859
- }
860
- // API latency test
861
- const apiStart = Date.now();
862
- await fetch(`${url}/rest/v1/`, { headers }).catch(() => null);
863
- const apiLatency = Date.now() - apiStart;
864
- perf.supabase = {
865
- apiLatency,
866
- tables: tableStats,
867
- recommendation: tableStats.some((t) => t.status === "slow")
868
- ? "Some queries are slow. Consider adding database indexes."
869
- : tableStats.some((t) => (t.rowCount ?? 0) > 10000)
870
- ? "Large tables detected. Ensure you have indexes on frequently queried columns."
871
- : "Performance looks good.",
872
- };
873
- }
874
- // Vercel deploy performance
875
- if (process.env.VERCEL_TOKEN) {
876
- try {
877
- const res = await fetch("https://api.vercel.com/v6/deployments?limit=5", {
878
- headers: { Authorization: `Bearer ${process.env.VERCEL_TOKEN}` },
879
- });
880
- const data = await res.json();
881
- const deploys = (data.deployments ?? []).map((d) => {
882
- const buildDuration = d.buildingAt && d.ready
883
- ? Math.round((d.ready - d.buildingAt) / 1000)
884
- : null;
885
- return {
886
- id: d.uid,
887
- state: d.readyState ?? d.state,
888
- buildDuration: buildDuration ? `${buildDuration}s` : "unknown",
889
- created: new Date(d.created).toISOString(),
890
- };
891
- });
892
- perf.vercel = {
893
- recentDeploys: deploys,
894
- avgBuildTime: deploys.filter((d) => d.buildDuration !== "unknown").length > 0
895
- ? "see individual deploys"
896
- : "no build data available",
897
- };
898
- }
899
- catch { /* skip */ }
900
- }
901
- // Stripe API latency
902
- if (process.env.STRIPE_SECRET_KEY) {
903
- const start = Date.now();
904
- await fetch("https://api.stripe.com/v1/balance", {
905
- headers: { Authorization: `Bearer ${process.env.STRIPE_SECRET_KEY}` },
906
- }).catch(() => null);
907
- perf.stripe = { apiLatency: Date.now() - start };
908
- }
909
- return {
910
- content: [{ type: "text", text: JSON.stringify({ performance: perf }, null, 2) }],
911
- };
912
- });
913
- // ──────────────────────────────────────────
914
- // Tool: stk_cost
915
- // ──────────────────────────────────────────
916
- server.tool("stk_cost", "Track costs across your stack: Stripe fees, Vercel usage, Supabase plan details. Get a unified view of what you're spending.", {}, async () => {
917
- const costs = {};
918
- // Stripe revenue & fees
919
- if (process.env.STRIPE_SECRET_KEY) {
920
- try {
921
- const stripeKey = process.env.STRIPE_SECRET_KEY;
922
- // Balance
923
- const balRes = await fetch("https://api.stripe.com/v1/balance", {
924
- headers: { Authorization: `Bearer ${stripeKey}` },
925
- });
926
- const balData = await balRes.json();
927
- // Recent balance transactions for fee tracking
928
- const txRes = await fetch("https://api.stripe.com/v1/balance_transactions?limit=100", {
929
- headers: { Authorization: `Bearer ${stripeKey}` },
930
- });
931
- const txData = await txRes.json();
932
- const transactions = txData.data ?? [];
933
- const totalFees = transactions.reduce((sum, t) => sum + (t.fee || 0), 0);
934
- const totalGross = transactions.reduce((sum, t) => sum + (t.amount > 0 ? t.amount : 0), 0);
935
- const totalNet = transactions.reduce((sum, t) => sum + (t.net || 0), 0);
936
- costs.stripe = {
937
- mode: stripeKey.startsWith("sk_live") ? "live" : "test",
938
- balance: balData.available?.map((b) => ({
939
- amount: (b.amount / 100).toFixed(2),
940
- currency: b.currency.toUpperCase(),
941
- })) ?? [],
942
- recentTransactions: transactions.length,
943
- totalGross: (totalGross / 100).toFixed(2),
944
- totalFees: (totalFees / 100).toFixed(2),
945
- totalNet: (totalNet / 100).toFixed(2),
946
- feePercentage: totalGross > 0 ? ((totalFees / totalGross) * 100).toFixed(1) + "%" : "N/A",
947
- };
948
- }
949
- catch (err) {
950
- costs.stripe = { error: err.message };
951
- }
952
- }
953
- // Vercel usage
954
- if (process.env.VERCEL_TOKEN) {
955
- try {
956
- // Get team/user info for billing context
957
- const userRes = await fetch("https://api.vercel.com/v2/user", {
958
- headers: { Authorization: `Bearer ${process.env.VERCEL_TOKEN}` },
959
- });
960
- const userData = await userRes.json();
961
- // Count deployments
962
- const depRes = await fetch("https://api.vercel.com/v6/deployments?limit=100", {
963
- headers: { Authorization: `Bearer ${process.env.VERCEL_TOKEN}` },
964
- });
965
- const depData = await depRes.json();
966
- const deployments = depData.deployments ?? [];
967
- // Deployments this month
968
- const monthStart = new Date();
969
- monthStart.setDate(1);
970
- monthStart.setHours(0, 0, 0, 0);
971
- const thisMonth = deployments.filter((d) => new Date(d.created) >= monthStart);
972
- costs.vercel = {
973
- plan: userData.user?.billing?.plan ?? "unknown",
974
- deploymentsThisMonth: thisMonth.length,
975
- totalDeployments: deployments.length,
976
- note: "Vercel free tier includes 100 deployments/day. Check vercel.com/dashboard for detailed billing.",
977
- };
978
- }
979
- catch { /* skip */ }
980
- }
981
- // Supabase usage estimate
982
- if (process.env.SUPABASE_URL && process.env.SUPABASE_SERVICE_KEY) {
983
- const url = process.env.SUPABASE_URL;
984
- const key = process.env.SUPABASE_SERVICE_KEY;
985
- const headers = {
986
- apikey: key,
987
- Authorization: `Bearer ${key}`,
988
- Prefer: "count=exact",
989
- };
990
- const tableCounts = {};
991
- for (const table of ["posts", "users", "payments"]) {
992
- try {
993
- const res = await fetch(`${url}/rest/v1/${table}?select=id&limit=0`, { headers });
994
- const range = res.headers.get("content-range");
995
- tableCounts[table] = range ? parseInt(range.split("/")[1]) || 0 : null;
996
- }
997
- catch {
998
- tableCounts[table] = null;
999
- }
1000
- }
1001
- const totalRows = Object.values(tableCounts).reduce((s, v) => s + (v ?? 0), 0);
1002
- costs.supabase = {
1003
- tables: tableCounts,
1004
- totalRows,
1005
- note: "Supabase free tier: 500MB database, 1GB storage, 50k monthly active users. Check supabase.com/dashboard for detailed usage.",
1006
- };
1007
- }
1008
- return {
1009
- content: [{ type: "text", text: JSON.stringify({ costs }, null, 2) }],
1010
- };
1011
- });
1012
- // ──────────────────────────────────────────
1013
- // Brain: Supabase Knowledge Base Client
1014
- // ──────────────────────────────────────────
1015
- function getBrainClient() {
1016
- return getLocalBrainClient();
1017
- }
1018
- // ──────────────────────────────────────────
1019
- // Tool: stk_brain_search
1020
- // ──────────────────────────────────────────
1021
- server.tool("stk_brain_search", "Search the knowledge base for SaaS patterns, best practices, and architecture examples from top open-source projects (LangChain, Ollama, Transformers, llama.cpp, vLLM, AutoGen, OpenAI Cookbook). Use this when you need to know how successful projects solve specific problems.", {
1022
- query: z.string().describe("What to search for (e.g., 'authentication', 'real-time updates', 'payment integration')"),
1023
- category: z.string().optional().describe("Filter: architecture, auth, payments, database, api, deployment, testing, performance, security, ml, realtime, general"),
1024
- }, async ({ query, category }) => {
1025
- const brain = getBrainClient();
1026
- // Try ilike search on content and title
1027
- const words = query.split(" ").filter(w => w.length > 2);
1028
- const searchWord = words[0] ?? query;
1029
- const params = {
1030
- or: `(title.ilike.%${searchWord}%,content.ilike.%${searchWord}%)`,
1031
- limit: "10",
1032
- order: "source",
1033
- };
1034
- if (category)
1035
- params["category"] = `eq.${category}`;
1036
- const { data, ok } = await brain.query("knowledge", params);
1037
- if (!ok)
1038
- return { content: [{ type: "text", text: JSON.stringify({ error: "Query failed", data }) }] };
1039
- return {
1040
- content: [{
1041
- type: "text",
1042
- text: JSON.stringify({
1043
- query,
1044
- results: (data ?? []).map((r) => ({ source: r.source, category: r.category, title: r.title, content: r.content, tags: r.tags })),
1045
- total: data?.length ?? 0,
1046
- }, null, 2),
1047
- }],
1048
- };
1049
- });
1050
- // ──────────────────────────────────────────
1051
- // Tool: stk_brain_patterns
1052
- // ──────────────────────────────────────────
1053
- server.tool("stk_brain_patterns", "Get best practice patterns for a specific feature. Returns how top projects implement auth, payments, real-time, caching, APIs, etc.", {
1054
- feature: z.string().describe("The feature or pattern (e.g., 'authentication', 'webhooks', 'caching', 'model serving', 'fine-tuning')"),
1055
- }, async ({ feature }) => {
1056
- const brain = getBrainClient();
1057
- const { data, ok } = await brain.query("knowledge", {
1058
- or: `(title.ilike.%${feature}%,content.ilike.%${feature}%)`,
1059
- limit: "15",
1060
- order: "source",
1061
- });
1062
- if (!ok)
1063
- return { content: [{ type: "text", text: JSON.stringify({ error: "Query failed" }) }] };
1064
- // Group by source
1065
- const grouped = {};
1066
- for (const item of data ?? []) {
1067
- if (!grouped[item.source])
1068
- grouped[item.source] = [];
1069
- grouped[item.source].push({ title: item.title, category: item.category, content: item.content });
1070
- }
1071
- return {
1072
- content: [{
1073
- type: "text",
1074
- text: JSON.stringify({
1075
- feature,
1076
- patterns: grouped,
1077
- totalSources: Object.keys(grouped).length,
1078
- totalPatterns: data?.length ?? 0,
1079
- }, null, 2),
1080
- }],
1081
- };
1082
- });
1083
- // ──────────────────────────────────────────
1084
- // Tool: stk_brain_stack
1085
- // ──────────────────────────────────────────
1086
- server.tool("stk_brain_stack", "Get recommendations specific to YOUR stack (Supabase + Vercel + Stripe + Node.js). Filters knowledge for patterns matching your technology choices.", {
1087
- question: z.string().describe("What you want to build or solve (e.g., 'add user auth', 'implement webhooks', 'optimize queries')"),
1088
- }, async ({ question }) => {
1089
- const brain = getBrainClient();
1090
- const words = question.split(" ").filter(w => w.length > 3);
1091
- const searchWord = words[0] ?? question;
1092
- const { data, ok } = await brain.query("knowledge", {
1093
- or: `(content.ilike.%${searchWord}%,title.ilike.%${searchWord}%)`,
1094
- limit: "10",
1095
- });
1096
- if (!ok)
1097
- return { content: [{ type: "text", text: JSON.stringify({ error: "Query failed" }) }] };
1098
- return {
1099
- content: [{
1100
- type: "text",
1101
- text: JSON.stringify({
1102
- question,
1103
- stack: ["Supabase", "Vercel", "Stripe", "Node.js/Express"],
1104
- recommendations: (data ?? []).map((r) => ({ source: r.source, title: r.title, content: r.content, relevance: r.category })),
1105
- total: data?.length ?? 0,
1106
- }, null, 2),
1107
- }],
1108
- };
1109
- });
1110
- // ──────────────────────────────────────────
1111
- // Tool: stk_brain_learn
1112
- // ──────────────────────────────────────────
1113
- server.tool("stk_brain_learn", "Save new knowledge to the brain. Use this to remember patterns, solutions, or learnings for future reference across all projects.", {
1114
- title: z.string().describe("Short title"),
1115
- content: z.string().describe("The knowledge — pattern, solution, or best practice"),
1116
- source: z.string().optional().describe("Where this came from (e.g., 'project:worldchat', 'github:vercel/next.js')"),
1117
- category: z.string().optional().describe("Category: architecture, auth, payments, database, api, deployment, testing, performance, security, ml, general"),
1118
- tags: z.array(z.string()).optional().describe("Tags for searchability"),
1119
- }, async ({ title, content, source, category, tags }) => {
1120
- const brain = getBrainClient();
1121
- const { data, ok } = await brain.insert("knowledge", {
1122
- title,
1123
- content,
1124
- source: source ?? "manual",
1125
- category: category ?? "general",
1126
- tags: tags ?? [],
1127
- created_at: new Date().toISOString(),
1128
- });
1129
- if (!ok)
1130
- return { content: [{ type: "text", text: JSON.stringify({ error: "Insert failed", data }) }] };
1131
- return {
1132
- content: [{
1133
- type: "text",
1134
- text: JSON.stringify({ learned: true, title, message: "Knowledge saved. I can recall this in future conversations." }, null, 2),
1135
- }],
1136
- };
1137
- });
1138
- // ──────────────────────────────────────────
1139
- // Tool: stk_brain_stats
1140
- // ──────────────────────────────────────────
1141
- server.tool("stk_brain_stats", "Check what the brain knows — total knowledge entries, categories, sources, and coverage.", {}, async () => {
1142
- const brain = getBrainClient();
1143
- const { data, count } = await brain.query("knowledge", { select: "category,source", limit: "1000" });
1144
- const categories = {};
1145
- const sources = {};
1146
- for (const row of data ?? []) {
1147
- categories[row.category] = (categories[row.category] || 0) + 1;
1148
- sources[row.source] = (sources[row.source] || 0) + 1;
1149
- }
1150
- return {
1151
- content: [{
1152
- type: "text",
1153
- text: JSON.stringify({
1154
- totalKnowledge: count ?? data?.length ?? 0,
1155
- categories,
1156
- sources,
1157
- topSources: Object.entries(sources)
1158
- .sort(([, a], [, b]) => b - a)
1159
- .slice(0, 10)
1160
- .map(([name, count]) => ({ name, count })),
1161
- }, null, 2),
1162
- }],
1163
- };
1164
- });
1165
- // ──────────────────────────────────────────
1166
- // Tool: stk_brain_check
1167
- // ──────────────────────────────────────────
1168
- server.tool("stk_brain_check", "PROACTIVE GOTCHA DETECTION — Run this BEFORE implementing any feature or fixing any bug. Searches the brain for known gotchas, pitfalls, and patterns related to your task. Returns warnings ranked by relevance so you can avoid repeating past mistakes. Claude should call this automatically before writing code.", {
1169
- task: z.string().describe("What you're about to implement or fix (e.g., 'add email verification', 'update user model', 'fix auth redirect')"),
1170
- }, async ({ task }) => {
1171
- const results = brainCheck(task);
1172
- if (results.length === 0) {
1173
- return {
1174
- content: [{
1175
- type: "text",
1176
- text: JSON.stringify({
1177
- task,
1178
- warnings: [],
1179
- message: "No known gotchas found. Proceed with caution — this might be new territory.",
1180
- }, null, 2),
1181
- }],
1182
- };
1183
- }
1184
- const warnings = results.slice(0, 5).map(r => ({
1185
- title: r.entry.title,
1186
- content: r.entry.content,
1187
- relevance: r.score,
1188
- matchedTerms: r.matchedTerms,
1189
- source: r.entry.source,
1190
- category: r.entry.category,
1191
- }));
1192
- return {
1193
- content: [{
1194
- type: "text",
1195
- text: JSON.stringify({
1196
- task,
1197
- warnings,
1198
- totalMatches: results.length,
1199
- message: `Found ${results.length} relevant pattern(s). Review warnings before coding.`,
1200
- }, null, 2),
1201
- }],
1202
- };
1203
- });
1204
- // ──────────────────────────────────────────
1205
- // Tool: stk_brain_diagnose
1206
- // ──────────────────────────────────────────
1207
- server.tool("stk_brain_diagnose", "ERROR PATTERN MATCHING — Run this when you encounter an error or bug. Searches the brain for matching patterns from past issues and returns known solutions. Claude should call this automatically when debugging.", {
1208
- error: z.string().describe("The error message, symptom, or bug description (e.g., 'redirect not working after verification', 'emails not sending', 'prisma field undefined')"),
1209
- }, async ({ error }) => {
1210
- const results = brainDiagnose(error);
1211
- if (results.length === 0) {
1212
- return {
1213
- content: [{
1214
- type: "text",
1215
- text: JSON.stringify({
1216
- error,
1217
- solutions: [],
1218
- message: "No matching patterns found. This is a new issue — after fixing it, use stk_brain_learn to save the pattern.",
1219
- }, null, 2),
1220
- }],
1221
- };
1222
- }
1223
- const solutions = results.slice(0, 5).map(r => ({
1224
- title: r.entry.title,
1225
- solution: r.entry.content,
1226
- relevance: r.score,
1227
- matchedTerms: r.matchedTerms,
1228
- source: r.entry.source,
1229
- }));
1230
- return {
1231
- content: [{
1232
- type: "text",
1233
- text: JSON.stringify({
1234
- error,
1235
- solutions,
1236
- totalMatches: results.length,
1237
- message: `Found ${results.length} matching pattern(s). Apply relevant solutions.`,
1238
- }, null, 2),
1239
- }],
1240
- };
1241
- });
1242
- // ──────────────────────────────────────────
1243
- // Tool: stk_brain_ingest
1244
- // ──────────────────────────────────────────
1245
- server.tool("stk_brain_ingest", "Scan the current project and ingest architecture knowledge into the local brain (~/.stk/brain.json). Automatically reads CLAUDE.md, package.json, Prisma schema, Dockerfile, CI config, and route files. Run this when setting up stk in a new project or after major changes.", {
1246
- force: z.boolean().optional().default(false).describe("Re-ingest even if already ingested"),
1247
- }, async ({ force }) => {
1248
- const store = loadBrainStore();
1249
- const { projectName, entries, filesScanned } = ingestProject(process.cwd());
1250
- if (store.projects[projectName] && !force) {
1251
- const existing = store.projects[projectName];
1252
- return {
1253
- content: [{
1254
- type: "text",
1255
- text: JSON.stringify({
1256
- alreadyIngested: true,
1257
- projectName,
1258
- entries: existing.entries.length,
1259
- ingestedAt: existing.ingestedAt,
1260
- message: "Already ingested. Use force: true to re-ingest.",
1261
- }, null, 2),
1262
- }],
1263
- };
1264
- }
1265
- if (entries.length === 0) {
1266
- return {
1267
- content: [{
1268
- type: "text",
1269
- text: JSON.stringify({ error: "No knowledge extracted. Make sure you're in a project directory with recognizable files." }),
1270
- }],
1271
- };
1272
- }
1273
- store.projects[projectName] = {
1274
- ingestedAt: new Date().toISOString(),
1275
- projectPath: process.cwd(),
1276
- entries,
1277
- };
1278
- saveBrainStore(store);
1279
- const categories = {};
1280
- for (const e of entries) {
1281
- categories[e.category] = (categories[e.category] || 0) + 1;
1282
- }
1283
- return {
1284
- content: [{
1285
- type: "text",
1286
- text: JSON.stringify({
1287
- ingested: true,
1288
- projectName,
1289
- totalEntries: entries.length,
1290
- filesScanned,
1291
- categories,
1292
- storedAt: "~/.stk/brain.json",
1293
- }, null, 2),
1294
- }],
1295
- };
1296
- });
1297
- // ──────────────────────────────────────────
1298
- // Tool: stk_brain_sync
1299
- // ──────────────────────────────────────────
1300
- server.tool("stk_brain_sync", "Sync brain knowledge between local (~/.stk/brain.json) and cloud (Supabase). Push shares your knowledge with other developers. Pull downloads knowledge from the cloud. Sync does both.", {
1301
- action: z.enum(["sync", "push", "pull"]).optional().default("sync").describe("sync: push+pull, push: local→cloud, pull: cloud→local"),
1302
- }, async ({ action }) => {
1303
- let result;
1304
- if (action === "push")
1305
- result = await pushToCloud();
1306
- else if (action === "pull")
1307
- result = await pullFromCloud();
1308
- else
1309
- result = await syncBrain();
1310
- return {
1311
- content: [{
1312
- type: "text",
1313
- text: JSON.stringify({
1314
- action,
1315
- pushed: result.pushed,
1316
- pulled: result.pulled,
1317
- errors: result.errors.length > 0 ? result.errors : undefined,
1318
- ok: result.errors.length === 0,
1319
- }, null, 2),
1320
- }],
1321
- };
1322
- });
1323
- // ──────────────────────────────────────────
1324
- // Tool: stk_brain_check (PROACTIVE — call before writing code)
1325
- // ──────────────────────────────────────────
1326
- server.tool("stk_brain_check", "PROACTIVE: Call this BEFORE implementing a feature or making changes. Searches the brain for known gotchas, past bugs, and patterns relevant to what you're about to build. Returns warnings that can prevent mistakes. Use this whenever you start a non-trivial coding task.", {
1327
- task: z.string().describe("What you're about to implement (e.g., 'add email verification', 'update user model', 'add webhook endpoint')"),
1328
- }, async ({ task }) => {
1329
- const results = brainCheck(task);
1330
- if (results.length === 0) {
1331
- return {
1332
- content: [{
1333
- type: "text",
1334
- text: JSON.stringify({
1335
- task,
1336
- warnings: [],
1337
- message: "No known gotchas found. Proceed carefully.",
1338
- }, null, 2),
1339
- }],
1340
- };
1341
- }
1342
- const warnings = results.slice(0, 8).map(r => ({
1343
- title: r.entry.title,
1344
- warning: r.entry.content,
1345
- relevance: r.score,
1346
- matchedTerms: r.matchedTerms,
1347
- source: r.entry.source,
1348
- category: r.entry.category,
1349
- }));
1350
- return {
1351
- content: [{
1352
- type: "text",
1353
- text: JSON.stringify({
1354
- task,
1355
- warnings,
1356
- totalMatches: results.length,
1357
- message: `Found ${results.length} relevant entries. Review warnings before coding.`,
1358
- }, null, 2),
1359
- }],
1360
- };
1361
- });
1362
- // ──────────────────────────────────────────
1363
- // Tool: stk_brain_diagnose (REACTIVE — call when you hit an error)
1364
- // ──────────────────────────────────────────
1365
- server.tool("stk_brain_diagnose", "REACTIVE: Call this when you encounter an error or bug. Searches the brain for matching patterns from past issues and returns known solutions. Use this before debugging from scratch — the answer may already be in the brain.", {
1366
- error: z.string().describe("The error message, bug description, or unexpected behavior you're seeing"),
1367
- }, async ({ error }) => {
1368
- const results = brainDiagnose(error);
1369
- if (results.length === 0) {
1370
- return {
1371
- content: [{
1372
- type: "text",
1373
- text: JSON.stringify({
1374
- error,
1375
- solutions: [],
1376
- message: "No matching patterns found in the brain. This is a new issue — debug it, fix it, then use stk_brain_learn to save the solution.",
1377
- }, null, 2),
1378
- }],
1379
- };
1380
- }
1381
- const solutions = results.slice(0, 5).map(r => ({
1382
- title: r.entry.title,
1383
- solution: r.entry.content,
1384
- relevance: r.score,
1385
- matchedTerms: r.matchedTerms,
1386
- source: r.entry.source,
1387
- }));
1388
- return {
1389
- content: [{
1390
- type: "text",
1391
- text: JSON.stringify({
1392
- error,
1393
- solutions,
1394
- totalMatches: results.length,
1395
- message: `Found ${results.length} matching patterns. Apply the most relevant solution.`,
1396
- }, null, 2),
1397
- }],
1398
- };
1399
- });
1400
- // ──────────────────────────────────────────
1401
- // Tool: stk_brain_claudemd
1402
- // ──────────────────────────────────────────
1403
- server.tool("stk_brain_claudemd", "Auto-generate a CLAUDE.md file for the current project. Analyzes the tech stack, project structure, services, and brain knowledge to create comprehensive project instructions for Claude Code.", {
1404
- projectName: z.string().optional().describe("Project name (auto-detected from stk.config.json if omitted)"),
1405
- write: z.boolean().optional().default(false).describe("Actually write the CLAUDE.md file to disk. If false, just returns the content for review."),
1406
- }, async ({ projectName, write }) => {
1407
- const config = loadConfig();
1408
- const name = projectName ?? config.name ?? "my-project";
1409
- const enabled = enabledServices(config);
1410
- // Detect project info
1411
- let gitBranch = "";
1412
- let gitRemote = "";
1413
- let packageJson = {};
1414
- try {
1415
- gitBranch = execSync("git rev-parse --abbrev-ref HEAD", { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
1416
- }
1417
- catch { }
1418
- try {
1419
- gitRemote = execSync("git remote get-url origin", { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
1420
- }
1421
- catch { }
1422
- try {
1423
- const { readFileSync } = await import("fs");
1424
- packageJson = JSON.parse(readFileSync("package.json", "utf-8"));
1425
- }
1426
- catch { }
1427
- // Detect tech stack
1428
- const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
1429
- const stack = [];
1430
- if (deps?.["next"])
1431
- stack.push("Next.js");
1432
- if (deps?.["react"])
1433
- stack.push("React");
1434
- if (deps?.["vue"])
1435
- stack.push("Vue");
1436
- if (deps?.["express"])
1437
- stack.push("Express.js");
1438
- if (deps?.["fastify"])
1439
- stack.push("Fastify");
1440
- if (deps?.["@supabase/supabase-js"])
1441
- stack.push("Supabase");
1442
- if (deps?.["stripe"])
1443
- stack.push("Stripe");
1444
- if (deps?.["prisma"] || deps?.["@prisma/client"])
1445
- stack.push("Prisma");
1446
- if (deps?.["mongoose"])
1447
- stack.push("Mongoose/MongoDB");
1448
- if (deps?.["redis"] || deps?.["ioredis"])
1449
- stack.push("Redis");
1450
- if (deps?.["tailwindcss"])
1451
- stack.push("Tailwind CSS");
1452
- if (deps?.["typescript"])
1453
- stack.push("TypeScript");
1454
- if (deps?.["zod"])
1455
- stack.push("Zod");
1456
- if (stack.length === 0 && Object.keys(deps ?? {}).length > 0) {
1457
- stack.push("Node.js");
1458
- }
1459
- // Detect file structure
1460
- let fileStructure = "";
1461
- try {
1462
- fileStructure = execSync("find . -maxdepth 3 -type f -name '*.ts' -o -name '*.js' -o -name '*.tsx' -o -name '*.jsx' -o -name '*.json' -o -name '*.css' -o -name '*.html' | grep -v node_modules | grep -v dist | grep -v .git | sort | head -40", { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
1463
- }
1464
- catch { }
1465
- // Build CLAUDE.md
1466
- const lines = [];
1467
- lines.push(`# ${name}\n`);
1468
- // Project overview
1469
- lines.push(`## Overview\n`);
1470
- if (packageJson.description)
1471
- lines.push(`${packageJson.description}\n`);
1472
- if (stack.length > 0)
1473
- lines.push(`**Tech Stack:** ${stack.join(", ")}\n`);
1474
- if (gitRemote)
1475
- lines.push(`**Repo:** ${gitRemote}`);
1476
- if (gitBranch)
1477
- lines.push(`**Main Branch:** ${gitBranch}`);
1478
- lines.push("");
1479
- // Services
1480
- if (enabled.length > 0) {
1481
- lines.push(`## Services\n`);
1482
- for (const svc of enabled) {
1483
- const svcName = svc.charAt(0).toUpperCase() + svc.slice(1);
1484
- lines.push(`- **${svcName}** — configured and monitored via stk`);
1485
- }
1486
- lines.push("");
1487
- }
1488
- // Project structure
1489
- if (fileStructure) {
1490
- lines.push(`## Project Structure\n`);
1491
- lines.push("```");
1492
- lines.push(fileStructure);
1493
- lines.push("```\n");
1494
- }
1495
- // Development commands
1496
- lines.push(`## Development\n`);
1497
- if (packageJson.scripts) {
1498
- lines.push("```bash");
1499
- if (packageJson.scripts.dev)
1500
- lines.push(`npm run dev # Start dev server`);
1501
- if (packageJson.scripts.build)
1502
- lines.push(`npm run build # Build for production`);
1503
- if (packageJson.scripts.test)
1504
- lines.push(`npm test # Run tests`);
1505
- if (packageJson.scripts.start)
1506
- lines.push(`npm start # Start production server`);
1507
- lines.push("```\n");
1508
- }
1509
- // stk tools available
1510
- lines.push(`## stk Tools Available\n`);
1511
- lines.push(`This project uses stk for infrastructure monitoring. Available commands:\n`);
1512
- lines.push(`- \`stk_health\` — Check service health`);
1513
- lines.push(`- \`stk_status\` — Full project overview`);
1514
- lines.push(`- \`stk_logs\` — Production logs`);
1515
- lines.push(`- \`stk_db\` — Query database`);
1516
- lines.push(`- \`stk_alerts\` — Check for problems`);
1517
- lines.push(`- \`stk_deploy\` — Deploy to production`);
1518
- lines.push(`- \`stk_brain_search\` — Search knowledge base`);
1519
- lines.push(`- \`stk_brain_learn\` — Save patterns for future use`);
1520
- lines.push("");
1521
- // Conventions
1522
- lines.push(`## Conventions\n`);
1523
- if (deps?.["typescript"]) {
1524
- lines.push(`- TypeScript strict mode enabled`);
1525
- }
1526
- lines.push(`- Use existing patterns in the codebase before introducing new ones`);
1527
- lines.push(`- Check stk_health before debugging production issues`);
1528
- lines.push(`- Use stk_brain_search to find how other projects solve similar problems`);
1529
- lines.push(`- Save useful patterns with stk_brain_learn for future reference`);
1530
- lines.push("");
1531
- // Environment
1532
- lines.push(`## Environment Variables\n`);
1533
- lines.push(`Environment variables are managed via \`.env\` files. See \`.env.example\` for required variables.`);
1534
- if (enabled.includes("vercel"))
1535
- lines.push(`Use \`stk_env_sync\` to compare local vs remote env vars.`);
1536
- lines.push("");
1537
- const content = lines.join("\n");
1538
- if (write) {
1539
- const { writeFileSync } = await import("fs");
1540
- writeFileSync("CLAUDE.md", content);
1541
- return {
1542
- content: [{
1543
- type: "text",
1544
- text: JSON.stringify({ written: true, path: "CLAUDE.md", lines: content.split("\n").length }, null, 2),
1545
- }],
1546
- };
1547
- }
1548
- return {
1549
- content: [{
1550
- type: "text",
1551
- text: JSON.stringify({ preview: true, content, note: "Call again with write: true to save to disk" }, null, 2),
1552
- }],
1553
- };
1554
- });
1555
- // Helper
1556
- function detectGitHubRepo() {
1557
- try {
1558
- const url = execSync("git remote get-url origin", { encoding: "utf-8", stdio: ["pipe", "pipe", "pipe"] }).trim();
1559
- const match = url.match(/github\.com[:/]([^/]+\/[^/.]+)/);
1560
- return match?.[1] ?? null;
1561
- }
1562
- catch {
1563
- return null;
1564
- }
1565
- }
19
+ version: "0.7.0",
20
+ });
21
+ registerInfraTools(server);
22
+ registerOpsTools(server);
23
+ registerDataTools(server);
24
+ registerBrainTools(server);
25
+ registerGithubTools(server);
26
+ registerSecurityTools(server);
1566
27
  // Start
1567
28
  async function main() {
1568
29
  const transport = new StdioServerTransport();