@insforge/mcp 1.2.5-dev.0 → 1.2.6-dev.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1836 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/shared/tools.ts
4
- import { z as z19 } from "zod";
5
- import fetch2 from "node-fetch";
6
- import { promises as fs } from "fs";
7
- import { exec } from "child_process";
8
- import { promisify } from "util";
9
-
10
- // src/shared/response-handler.ts
11
- async function handleApiResponse(response) {
12
- const responseData = await response.json();
13
- if (!response.ok) {
14
- const errorData = responseData;
15
- let fullMessage = errorData.message || errorData.error || "Unknown error";
16
- if (errorData.nextAction) {
17
- fullMessage += `. ${errorData.nextAction}`;
18
- }
19
- throw new Error(fullMessage);
20
- }
21
- return responseData;
22
- }
23
- function formatSuccessMessage(operation, data) {
24
- if (data && typeof data === "object" && "message" in data) {
25
- return `${data.message}
26
- ${JSON.stringify(data, null, 2)}`;
27
- }
28
- return `${operation} completed successfully:
29
- ${JSON.stringify(data, null, 2)}`;
30
- }
31
-
32
- // src/shared/usage-tracker.ts
33
- import fetch from "node-fetch";
34
- var UsageTracker = class {
35
- apiBaseUrl;
36
- apiKey;
37
- constructor(apiBaseUrl, apiKey) {
38
- this.apiBaseUrl = apiBaseUrl;
39
- this.apiKey = apiKey;
40
- }
41
- async trackUsage(toolName, success = true) {
42
- if (!this.apiKey) {
43
- return;
44
- }
45
- try {
46
- const payload = {
47
- tool_name: toolName,
48
- success,
49
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
50
- };
51
- await fetch(`${this.apiBaseUrl}/api/usage/mcp`, {
52
- method: "POST",
53
- headers: {
54
- "Content-Type": "application/json",
55
- "x-api-key": this.apiKey
56
- },
57
- body: JSON.stringify(payload)
58
- });
59
- } catch (error) {
60
- console.error("Failed to track usage:", error);
61
- }
62
- }
63
- };
64
-
65
- // node_modules/@insforge/shared-schemas/dist/database.schema.js
66
- import { z } from "zod";
67
- var ColumnType;
68
- (function(ColumnType2) {
69
- ColumnType2["STRING"] = "string";
70
- ColumnType2["DATE"] = "date";
71
- ColumnType2["DATETIME"] = "datetime";
72
- ColumnType2["INTEGER"] = "integer";
73
- ColumnType2["FLOAT"] = "float";
74
- ColumnType2["BOOLEAN"] = "boolean";
75
- ColumnType2["UUID"] = "uuid";
76
- ColumnType2["JSON"] = "json";
77
- })(ColumnType || (ColumnType = {}));
78
- var onUpdateActionSchema = z.enum(["CASCADE", "RESTRICT", "NO ACTION"]);
79
- var onDeleteActionSchema = z.enum([
80
- "CASCADE",
81
- "SET NULL",
82
- "SET DEFAULT",
83
- "RESTRICT",
84
- "NO ACTION"
85
- ]);
86
- var columnTypeSchema = z.enum([
87
- ColumnType.STRING,
88
- ColumnType.DATE,
89
- ColumnType.DATETIME,
90
- ColumnType.INTEGER,
91
- ColumnType.FLOAT,
92
- ColumnType.BOOLEAN,
93
- ColumnType.UUID,
94
- ColumnType.JSON
95
- ]);
96
- var foreignKeySchema = z.object({
97
- referenceTable: z.string().min(1, "Target table cannot be empty"),
98
- referenceColumn: z.string().min(1, "Target column cannot be empty"),
99
- onDelete: onDeleteActionSchema,
100
- onUpdate: onUpdateActionSchema
101
- });
102
- var columnSchema = z.object({
103
- columnName: z.string().min(1, "Column name cannot be empty").max(64, "Column name must be less than 64 characters"),
104
- type: z.union([columnTypeSchema, z.string()]),
105
- defaultValue: z.string().optional(),
106
- isPrimaryKey: z.boolean().optional(),
107
- isNullable: z.boolean(),
108
- isUnique: z.boolean(),
109
- foreignKey: foreignKeySchema.optional()
110
- });
111
- var tableSchema = z.object({
112
- tableName: z.string().min(1, "Table name cannot be empty").max(64, "Table name must be less than 64 characters"),
113
- columns: z.array(columnSchema).min(1, "At least one column is required"),
114
- recordCount: z.number().optional(),
115
- createdAt: z.string().optional(),
116
- updatedAt: z.string().optional()
117
- });
118
- var databaseFunctionSchema = z.object({
119
- functionName: z.string(),
120
- functionDef: z.string(),
121
- kind: z.string()
122
- });
123
- var databaseIndexSchema = z.object({
124
- tableName: z.string(),
125
- indexName: z.string(),
126
- indexDef: z.string(),
127
- isUnique: z.boolean().nullable(),
128
- isPrimary: z.boolean().nullable()
129
- });
130
- var databasePolicySchema = z.object({
131
- tableName: z.string(),
132
- policyName: z.string(),
133
- cmd: z.string(),
134
- roles: z.array(z.string()),
135
- qual: z.string().nullable(),
136
- withCheck: z.string().nullable()
137
- });
138
- var databaseTriggerSchema = z.object({
139
- tableName: z.string(),
140
- triggerName: z.string(),
141
- actionTiming: z.string(),
142
- eventManipulation: z.string(),
143
- actionOrientation: z.string(),
144
- actionCondition: z.string().nullable(),
145
- actionStatement: z.string()
146
- });
147
-
148
- // node_modules/@insforge/shared-schemas/dist/database-api.schema.js
149
- import { z as z2 } from "zod";
150
- var createTableRequestSchema = tableSchema.pick({
151
- tableName: true,
152
- columns: true
153
- }).extend({
154
- rlsEnabled: z2.boolean().default(true)
155
- });
156
- var createTableResponseSchema = tableSchema.pick({
157
- tableName: true,
158
- columns: true
159
- }).extend({
160
- message: z2.string(),
161
- autoFields: z2.array(z2.string()),
162
- nextActions: z2.string()
163
- });
164
- var updateTableSchemaRequestSchema = z2.object({
165
- addColumns: z2.array(columnSchema.omit({
166
- foreignKey: true
167
- })).optional(),
168
- dropColumns: z2.array(z2.string()).optional(),
169
- updateColumns: z2.array(z2.object({
170
- columnName: z2.string(),
171
- defaultValue: z2.string().optional(),
172
- newColumnName: z2.string().min(1, "New column name cannot be empty").max(64, "New column name must be less than 64 characters").optional()
173
- })).optional(),
174
- addForeignKeys: z2.array(z2.object({
175
- columnName: z2.string().min(1, "Column name is required for adding foreign key"),
176
- foreignKey: foreignKeySchema
177
- })).optional(),
178
- dropForeignKeys: z2.array(z2.string()).optional(),
179
- renameTable: z2.object({
180
- newTableName: z2.string().min(1, "New table name cannot be empty").max(64, "New table name must be less than 64 characters")
181
- }).optional()
182
- });
183
- var updateTableSchemaResponse = z2.object({
184
- message: z2.string(),
185
- tableName: z2.string(),
186
- operations: z2.array(z2.string())
187
- });
188
- var deleteTableResponse = z2.object({
189
- message: z2.string(),
190
- tableName: z2.string(),
191
- nextActions: z2.string()
192
- });
193
- var rawSQLRequestSchema = z2.object({
194
- query: z2.string().min(1, "Query is required"),
195
- params: z2.array(z2.unknown()).optional()
196
- });
197
- var rawSQLResponseSchema = z2.object({
198
- rows: z2.array(z2.record(z2.string(), z2.unknown())),
199
- rowCount: z2.number().nullable(),
200
- fields: z2.array(z2.object({
201
- name: z2.string(),
202
- dataTypeID: z2.number()
203
- })).optional()
204
- });
205
- var exportRequestSchema = z2.object({
206
- tables: z2.array(z2.string()).optional(),
207
- format: z2.enum(["sql", "json"]).default("sql"),
208
- includeData: z2.boolean().default(true),
209
- includeFunctions: z2.boolean().default(false),
210
- includeSequences: z2.boolean().default(false),
211
- includeViews: z2.boolean().default(false),
212
- rowLimit: z2.number().int().positive().max(1e4).default(1e3)
213
- });
214
- var exportJsonDataSchema = z2.object({
215
- timestamp: z2.string(),
216
- tables: z2.record(z2.string(), z2.object({
217
- schema: z2.array(z2.object({
218
- columnName: z2.string(),
219
- dataType: z2.string(),
220
- characterMaximumLength: z2.number().nullable(),
221
- isNullable: z2.string(),
222
- columnDefault: z2.string().nullable()
223
- })),
224
- indexes: z2.array(z2.object({
225
- indexname: z2.string(),
226
- indexdef: z2.string(),
227
- isUnique: z2.boolean().nullable(),
228
- isPrimary: z2.boolean().nullable()
229
- })),
230
- foreignKeys: z2.array(z2.object({
231
- constraintName: z2.string(),
232
- columnName: z2.string(),
233
- foreignTableName: z2.string(),
234
- foreignColumnName: z2.string(),
235
- deleteRule: z2.string().nullable(),
236
- updateRule: z2.string().nullable()
237
- })),
238
- rlsEnabled: z2.boolean().optional(),
239
- policies: z2.array(z2.object({
240
- policyname: z2.string(),
241
- cmd: z2.string(),
242
- roles: z2.array(z2.string()),
243
- qual: z2.string().nullable(),
244
- withCheck: z2.string().nullable()
245
- })),
246
- triggers: z2.array(z2.object({
247
- triggerName: z2.string(),
248
- actionTiming: z2.string(),
249
- eventManipulation: z2.string(),
250
- actionOrientation: z2.string(),
251
- actionCondition: z2.string().nullable(),
252
- actionStatement: z2.string(),
253
- newTable: z2.string().nullable(),
254
- oldTable: z2.string().nullable()
255
- })),
256
- rows: z2.array(z2.record(z2.string(), z2.unknown())).optional(),
257
- recordCount: z2.number().optional()
258
- })),
259
- functions: z2.array(z2.object({
260
- functionName: z2.string(),
261
- functionDef: z2.string(),
262
- kind: z2.string()
263
- })),
264
- sequences: z2.array(z2.object({
265
- sequenceName: z2.string(),
266
- startValue: z2.string(),
267
- increment: z2.string(),
268
- minValue: z2.string().nullable(),
269
- maxValue: z2.string().nullable(),
270
- cycle: z2.string()
271
- })),
272
- views: z2.array(z2.object({
273
- viewName: z2.string(),
274
- definition: z2.string()
275
- }))
276
- });
277
- var exportResponseSchema = z2.object({
278
- format: z2.enum(["sql", "json"]),
279
- data: z2.union([z2.string(), exportJsonDataSchema]),
280
- timestamp: z2.string()
281
- });
282
- var importRequestSchema = z2.object({
283
- truncate: z2.union([
284
- z2.boolean(),
285
- z2.string().transform((val) => {
286
- if (val === "true")
287
- return true;
288
- if (val === "false")
289
- return false;
290
- throw new Error("Invalid boolean string");
291
- })
292
- ]).default(false)
293
- });
294
- var importResponseSchema = z2.object({
295
- success: z2.boolean(),
296
- message: z2.string(),
297
- filename: z2.string(),
298
- tables: z2.array(z2.string()),
299
- rowsImported: z2.number(),
300
- fileSize: z2.number()
301
- });
302
- var bulkUpsertRequestSchema = z2.object({
303
- table: z2.string().min(1, "Table name is required"),
304
- upsertKey: z2.string().optional()
305
- // Note: File handling is done at the API layer via multipart/form-data
306
- });
307
- var bulkUpsertResponseSchema = z2.object({
308
- success: z2.boolean(),
309
- message: z2.string(),
310
- table: z2.string(),
311
- rowsAffected: z2.number(),
312
- totalRecords: z2.number(),
313
- filename: z2.string()
314
- });
315
- var databaseFunctionsResponseSchema = z2.object({
316
- functions: z2.array(databaseFunctionSchema)
317
- });
318
- var databaseIndexesResponseSchema = z2.object({
319
- indexes: z2.array(databaseIndexSchema)
320
- });
321
- var databasePoliciesResponseSchema = z2.object({
322
- policies: z2.array(databasePolicySchema)
323
- });
324
- var databaseTriggersResponseSchema = z2.object({
325
- triggers: z2.array(databaseTriggerSchema)
326
- });
327
-
328
- // node_modules/@insforge/shared-schemas/dist/storage.schema.js
329
- import { z as z3 } from "zod";
330
- var storageFileSchema = z3.object({
331
- key: z3.string(),
332
- bucket: z3.string(),
333
- size: z3.number(),
334
- mimeType: z3.string().optional(),
335
- uploadedAt: z3.string(),
336
- url: z3.string()
337
- });
338
- var storageBucketSchema = z3.object({
339
- name: z3.string(),
340
- public: z3.boolean(),
341
- createdAt: z3.string()
342
- });
343
-
344
- // node_modules/@insforge/shared-schemas/dist/storage-api.schema.js
345
- import { z as z4 } from "zod";
346
- var createBucketRequestSchema = z4.object({
347
- bucketName: z4.string().min(1, "Bucket name cannot be empty"),
348
- isPublic: z4.boolean().default(true)
349
- });
350
- var updateBucketRequestSchema = z4.object({
351
- isPublic: z4.boolean()
352
- });
353
- var listObjectsResponseSchema = z4.object({
354
- objects: z4.array(storageFileSchema),
355
- pagination: z4.object({
356
- offset: z4.number(),
357
- limit: z4.number(),
358
- total: z4.number()
359
- })
360
- });
361
- var uploadStrategyRequestSchema = z4.object({
362
- filename: z4.string().min(1, "Filename cannot be empty"),
363
- contentType: z4.string().optional(),
364
- size: z4.number().optional()
365
- });
366
- var uploadStrategyResponseSchema = z4.object({
367
- method: z4.enum(["presigned", "direct"]),
368
- uploadUrl: z4.string(),
369
- fields: z4.record(z4.string()).optional(),
370
- key: z4.string(),
371
- confirmRequired: z4.boolean(),
372
- confirmUrl: z4.string().optional(),
373
- expiresAt: z4.date().optional()
374
- });
375
- var downloadStrategyRequestSchema = z4.object({
376
- expiresIn: z4.number().optional().default(3600)
377
- });
378
- var downloadStrategyResponseSchema = z4.object({
379
- method: z4.enum(["presigned", "direct"]),
380
- url: z4.string(),
381
- expiresAt: z4.date().optional(),
382
- headers: z4.record(z4.string()).optional()
383
- });
384
- var confirmUploadRequestSchema = z4.object({
385
- size: z4.number(),
386
- contentType: z4.string().optional(),
387
- etag: z4.string().optional()
388
- });
389
-
390
- // node_modules/@insforge/shared-schemas/dist/auth.schema.js
391
- import { z as z5 } from "zod";
392
- var userIdSchema = z5.string().uuid("Invalid user ID format");
393
- var emailSchema = z5.string().email("Invalid email format").toLowerCase().trim();
394
- var passwordSchema = z5.string();
395
- var nameSchema = z5.string().min(1, "Name is required").max(100, "Name must be less than 100 characters").trim();
396
- var roleSchema = z5.enum(["anon", "authenticated", "project_admin"]);
397
- var verificationMethodSchema = z5.enum(["code", "link"]);
398
- var profileSchema = z5.object({
399
- name: z5.string().optional(),
400
- // eslint-disable-next-line @typescript-eslint/naming-convention
401
- avatar_url: z5.string().url().optional()
402
- }).passthrough();
403
- var userSchema = z5.object({
404
- id: userIdSchema,
405
- email: emailSchema,
406
- emailVerified: z5.boolean(),
407
- providers: z5.array(z5.string()).optional(),
408
- createdAt: z5.string(),
409
- // PostgreSQL timestamp
410
- updatedAt: z5.string(),
411
- // PostgreSQL timestamp
412
- profile: profileSchema.nullable(),
413
- // User profile data (name, avatar_url, bio, etc.)
414
- metadata: z5.record(z5.unknown()).nullable()
415
- // System metadata (device ID, login IP, etc.)
416
- });
417
- var oAuthProvidersSchema = z5.enum([
418
- "google",
419
- "github",
420
- "discord",
421
- "linkedin",
422
- "facebook",
423
- "instagram",
424
- "tiktok",
425
- "apple",
426
- "x",
427
- "spotify",
428
- "microsoft"
429
- ]);
430
- var oAuthStateSchema = z5.object({
431
- provider: oAuthProvidersSchema,
432
- redirectUri: z5.string().url().optional()
433
- });
434
- var oAuthConfigSchema = z5.object({
435
- id: z5.string().uuid(),
436
- provider: oAuthProvidersSchema,
437
- clientId: z5.string().optional(),
438
- scopes: z5.array(z5.string()).optional(),
439
- redirectUri: z5.string().optional(),
440
- useSharedKey: z5.boolean(),
441
- createdAt: z5.string(),
442
- // PostgreSQL timestamp
443
- updatedAt: z5.string()
444
- // PostgreSQL timestamp
445
- });
446
- var authConfigSchema = z5.object({
447
- id: z5.string().uuid(),
448
- requireEmailVerification: z5.boolean(),
449
- passwordMinLength: z5.number().min(4).max(128),
450
- requireNumber: z5.boolean(),
451
- requireLowercase: z5.boolean(),
452
- requireUppercase: z5.boolean(),
453
- requireSpecialChar: z5.boolean(),
454
- verifyEmailMethod: verificationMethodSchema,
455
- resetPasswordMethod: verificationMethodSchema,
456
- signInRedirectTo: z5.union([z5.string().url(), z5.literal(""), z5.null()]).optional().transform((val) => val === "" ? null : val),
457
- createdAt: z5.string(),
458
- // PostgreSQL timestamp
459
- updatedAt: z5.string()
460
- // PostgreSQL timestamp
461
- });
462
- var tokenPayloadSchema = z5.object({
463
- sub: userIdSchema,
464
- // Subject (user ID)
465
- email: emailSchema,
466
- role: roleSchema,
467
- iat: z5.number().optional(),
468
- // Issued at
469
- exp: z5.number().optional()
470
- // Expiration
471
- });
472
-
473
- // node_modules/@insforge/shared-schemas/dist/auth-api.schema.js
474
- import { z as z6 } from "zod";
475
- var paginationSchema = z6.object({
476
- limit: z6.string().optional(),
477
- offset: z6.string().optional()
478
- });
479
- var createUserRequestSchema = z6.object({
480
- email: emailSchema,
481
- password: passwordSchema,
482
- name: nameSchema.optional()
483
- });
484
- var createSessionRequestSchema = z6.object({
485
- email: emailSchema,
486
- password: passwordSchema
487
- });
488
- var exchangeAdminSessionRequestSchema = z6.object({
489
- code: z6.string()
490
- });
491
- var listUsersRequestSchema = paginationSchema.extend({
492
- search: z6.string().optional()
493
- }).optional();
494
- var deleteUsersRequestSchema = z6.object({
495
- userIds: z6.array(userIdSchema).min(1, "At least one user ID is required")
496
- });
497
- var updateProfileRequestSchema = z6.object({
498
- profile: z6.record(z6.unknown())
499
- });
500
- var sendVerificationEmailRequestSchema = z6.object({
501
- email: emailSchema
502
- });
503
- var verifyEmailRequestSchema = z6.object({
504
- email: emailSchema.optional(),
505
- otp: z6.string().min(1)
506
- }).refine((data) => data.email || data.otp, {
507
- message: "Either email or otp must be provided"
508
- });
509
- var sendResetPasswordEmailRequestSchema = z6.object({
510
- email: emailSchema
511
- });
512
- var exchangeResetPasswordTokenRequestSchema = z6.object({
513
- email: emailSchema,
514
- code: z6.string().min(1)
515
- });
516
- var resetPasswordRequestSchema = z6.object({
517
- newPassword: passwordSchema,
518
- otp: z6.string().min(1, "OTP/token is required")
519
- });
520
- var createUserResponseSchema = z6.object({
521
- user: userSchema.optional(),
522
- accessToken: z6.string().nullable(),
523
- requireEmailVerification: z6.boolean().optional(),
524
- redirectTo: z6.string().url().optional(),
525
- csrfToken: z6.string().nullable().optional()
526
- });
527
- var createSessionResponseSchema = z6.object({
528
- user: userSchema,
529
- accessToken: z6.string(),
530
- redirectTo: z6.string().url().optional(),
531
- csrfToken: z6.string().nullable().optional()
532
- });
533
- var verifyEmailResponseSchema = z6.object({
534
- user: userSchema,
535
- accessToken: z6.string(),
536
- redirectTo: z6.string().url().optional(),
537
- csrfToken: z6.string().nullable().optional()
538
- });
539
- var refreshSessionResponseSchema = z6.object({
540
- accessToken: z6.string(),
541
- user: userSchema,
542
- csrfToken: z6.string()
543
- });
544
- var exchangeResetPasswordTokenResponseSchema = z6.object({
545
- token: z6.string(),
546
- expiresAt: z6.string().datetime()
547
- });
548
- var resetPasswordResponseSchema = z6.object({
549
- message: z6.string()
550
- });
551
- var getCurrentSessionResponseSchema = z6.object({
552
- user: userSchema
553
- });
554
- var getProfileResponseSchema = z6.object({
555
- id: userIdSchema,
556
- profile: profileSchema.nullable()
557
- });
558
- var listUsersResponseSchema = z6.object({
559
- data: z6.array(userSchema),
560
- pagination: z6.object({
561
- offset: z6.number(),
562
- limit: z6.number(),
563
- total: z6.number()
564
- })
565
- });
566
- var deleteUsersResponseSchema = z6.object({
567
- message: z6.string(),
568
- deletedCount: z6.number().int().nonnegative()
569
- });
570
- var getOauthUrlResponseSchema = z6.object({
571
- authUrl: z6.string().url()
572
- });
573
- var createOAuthConfigRequestSchema = oAuthConfigSchema.omit({
574
- id: true,
575
- createdAt: true,
576
- updatedAt: true
577
- }).extend({
578
- clientSecret: z6.string().optional()
579
- });
580
- var updateOAuthConfigRequestSchema = oAuthConfigSchema.omit({
581
- id: true,
582
- provider: true,
583
- createdAt: true,
584
- updatedAt: true
585
- }).extend({
586
- clientSecret: z6.string().optional()
587
- }).partial();
588
- var listOAuthConfigsResponseSchema = z6.object({
589
- data: z6.array(oAuthConfigSchema),
590
- count: z6.number()
591
- });
592
- var updateAuthConfigRequestSchema = authConfigSchema.omit({
593
- id: true,
594
- createdAt: true,
595
- updatedAt: true
596
- }).partial();
597
- var getPublicAuthConfigResponseSchema = z6.object({
598
- oAuthProviders: z6.array(oAuthProvidersSchema),
599
- ...authConfigSchema.omit({
600
- id: true,
601
- updatedAt: true,
602
- createdAt: true,
603
- signInRedirectTo: true
604
- }).shape
605
- });
606
- var authErrorResponseSchema = z6.object({
607
- error: z6.string(),
608
- message: z6.string(),
609
- statusCode: z6.number().int(),
610
- nextActions: z6.string().optional()
611
- });
612
-
613
- // node_modules/@insforge/shared-schemas/dist/metadata.schema.js
614
- import { z as z9 } from "zod";
615
-
616
- // node_modules/@insforge/shared-schemas/dist/realtime.schema.js
617
- import { z as z7 } from "zod";
618
- var senderTypeSchema = z7.enum(["system", "user"]);
619
- var realtimeChannelSchema = z7.object({
620
- id: z7.string().uuid(),
621
- pattern: z7.string().min(1),
622
- description: z7.string().nullable(),
623
- webhookUrls: z7.array(z7.string().url()).nullable(),
624
- enabled: z7.boolean(),
625
- createdAt: z7.string().datetime(),
626
- updatedAt: z7.string().datetime()
627
- });
628
- var realtimeMessageSchema = z7.object({
629
- id: z7.string().uuid(),
630
- eventName: z7.string().min(1),
631
- channelId: z7.string().uuid().nullable(),
632
- channelName: z7.string().min(1),
633
- payload: z7.record(z7.string(), z7.unknown()),
634
- senderType: senderTypeSchema,
635
- senderId: z7.string().uuid().nullable(),
636
- wsAudienceCount: z7.number().int().min(0),
637
- whAudienceCount: z7.number().int().min(0),
638
- whDeliveredCount: z7.number().int().min(0),
639
- createdAt: z7.string().datetime()
640
- });
641
- var subscribeChannelPayloadSchema = z7.object({
642
- channel: z7.string().min(1)
643
- // The resolved channel instance, e.g., "order:123"
644
- });
645
- var unsubscribeChannelPayloadSchema = z7.object({
646
- channel: z7.string().min(1)
647
- // The resolved channel instance, e.g., "order:123"
648
- });
649
- var publishEventPayloadSchema = z7.object({
650
- channel: z7.string().min(1),
651
- event: z7.string().min(1),
652
- payload: z7.record(z7.string(), z7.unknown())
653
- });
654
- var subscribeResponseSchema = z7.discriminatedUnion("ok", [
655
- z7.object({
656
- ok: z7.literal(true),
657
- channel: z7.string().min(1)
658
- }),
659
- z7.object({
660
- ok: z7.literal(false),
661
- channel: z7.string().min(1),
662
- error: z7.object({
663
- code: z7.string().min(1),
664
- message: z7.string().min(1)
665
- })
666
- })
667
- ]);
668
- var realtimeErrorPayloadSchema = z7.object({
669
- channel: z7.string().optional(),
670
- code: z7.string().min(1),
671
- message: z7.string().min(1)
672
- });
673
- var webhookMessageSchema = z7.object({
674
- messageId: z7.string().uuid(),
675
- channel: z7.string().min(1),
676
- eventName: z7.string().min(1),
677
- payload: z7.record(z7.string(), z7.unknown())
678
- });
679
- var socketMessageMetaSchema = z7.object({
680
- channel: z7.string().optional(),
681
- // Present for room broadcasts
682
- messageId: z7.string().uuid(),
683
- senderType: senderTypeSchema,
684
- senderId: z7.string().uuid().optional(),
685
- timestamp: z7.string().datetime()
686
- });
687
- var socketMessageSchema = z7.object({
688
- meta: socketMessageMetaSchema
689
- }).passthrough();
690
-
691
- // node_modules/@insforge/shared-schemas/dist/realtime-api.schema.js
692
- import { z as z8 } from "zod";
693
- var createChannelRequestSchema = z8.object({
694
- pattern: z8.string().min(1, "Channel pattern is required"),
695
- description: z8.string().optional(),
696
- webhookUrls: z8.array(z8.string().url()).optional(),
697
- enabled: z8.boolean().optional().default(true)
698
- });
699
- var updateChannelRequestSchema = z8.object({
700
- pattern: z8.string().min(1).optional(),
701
- description: z8.string().optional(),
702
- webhookUrls: z8.array(z8.string().url()).optional(),
703
- enabled: z8.boolean().optional()
704
- });
705
- var listChannelsResponseSchema = z8.array(realtimeChannelSchema);
706
- var deleteChannelResponseSchema = z8.object({
707
- message: z8.string()
708
- });
709
- var listMessagesRequestSchema = z8.object({
710
- channelId: z8.string().uuid().optional(),
711
- eventName: z8.string().optional(),
712
- limit: z8.coerce.number().int().min(1).max(1e3).optional().default(100),
713
- offset: z8.coerce.number().int().min(0).optional().default(0)
714
- });
715
- var listMessagesResponseSchema = z8.array(realtimeMessageSchema);
716
- var messageStatsRequestSchema = z8.object({
717
- channelId: z8.string().uuid().optional(),
718
- since: z8.coerce.date().optional()
719
- });
720
- var messageStatsResponseSchema = z8.object({
721
- totalMessages: z8.number().int().min(0),
722
- whDeliveryRate: z8.number().min(0).max(1),
723
- topEvents: z8.array(z8.object({
724
- eventName: z8.string(),
725
- count: z8.number().int().min(0)
726
- }))
727
- });
728
- var rlsPolicySchema = z8.object({
729
- policyName: z8.string(),
730
- tableName: z8.string(),
731
- command: z8.string(),
732
- roles: z8.array(z8.string()),
733
- using: z8.string().nullable(),
734
- withCheck: z8.string().nullable()
735
- });
736
- var realtimePermissionsResponseSchema = z8.object({
737
- subscribe: z8.object({
738
- policies: z8.array(rlsPolicySchema)
739
- }),
740
- publish: z8.object({
741
- policies: z8.array(rlsPolicySchema)
742
- })
743
- });
744
-
745
- // node_modules/@insforge/shared-schemas/dist/metadata.schema.js
746
- var authMetadataSchema = z9.object({
747
- oauths: z9.array(oAuthConfigSchema)
748
- });
749
- var databaseMetadataSchema = z9.object({
750
- tables: z9.array(z9.object({
751
- tableName: z9.string(),
752
- recordCount: z9.number()
753
- })),
754
- totalSizeInGB: z9.number(),
755
- hint: z9.string().optional()
756
- });
757
- var bucketMetadataSchema = storageBucketSchema.extend({
758
- objectCount: z9.number().optional()
759
- });
760
- var storageMetadataSchema = z9.object({
761
- buckets: z9.array(bucketMetadataSchema),
762
- totalSizeInGB: z9.number()
763
- });
764
- var edgeFunctionMetadataSchema = z9.object({
765
- slug: z9.string(),
766
- name: z9.string(),
767
- description: z9.string().nullable(),
768
- status: z9.string()
769
- });
770
- var aiMetadataSchema = z9.object({
771
- models: z9.array(z9.object({
772
- inputModality: z9.array(z9.string()),
773
- outputModality: z9.array(z9.string()),
774
- modelId: z9.string()
775
- }))
776
- });
777
- var realtimeMetadataSchema = z9.object({
778
- channels: z9.array(realtimeChannelSchema),
779
- permissions: realtimePermissionsResponseSchema
780
- });
781
- var appMetaDataSchema = z9.object({
782
- auth: authMetadataSchema,
783
- database: databaseMetadataSchema,
784
- storage: storageMetadataSchema,
785
- aiIntegration: aiMetadataSchema.optional(),
786
- functions: z9.array(edgeFunctionMetadataSchema),
787
- realtime: realtimeMetadataSchema.optional(),
788
- version: z9.string().optional()
789
- });
790
-
791
- // node_modules/@insforge/shared-schemas/dist/ai.schema.js
792
- import { z as z10 } from "zod";
793
- var modalitySchema = z10.enum(["text", "image"]);
794
- var aiConfigurationInputSchema = z10.object({
795
- inputModality: z10.array(modalitySchema).min(1),
796
- outputModality: z10.array(modalitySchema).min(1),
797
- provider: z10.string(),
798
- modelId: z10.string(),
799
- systemPrompt: z10.string().optional()
800
- });
801
- var aiConfigurationSchema = aiConfigurationInputSchema.extend({
802
- id: z10.string().uuid()
803
- });
804
- var aiConfigurationWithUsageSchema = aiConfigurationSchema.extend({
805
- usageStats: z10.object({
806
- totalInputTokens: z10.number(),
807
- totalOutputTokens: z10.number(),
808
- totalTokens: z10.number(),
809
- totalImageCount: z10.number(),
810
- totalRequests: z10.number()
811
- }).optional()
812
- });
813
- var aiUsageDataSchema = z10.object({
814
- configId: z10.string().uuid(),
815
- inputTokens: z10.number().int().optional(),
816
- outputTokens: z10.number().int().optional(),
817
- imageCount: z10.number().int().optional(),
818
- imageResolution: z10.string().optional()
819
- });
820
- var aiUsageRecordSchema = aiUsageDataSchema.extend({
821
- id: z10.string().uuid(),
822
- createdAt: z10.date(),
823
- modelId: z10.string().nullable().optional(),
824
- model: z10.string().nullable(),
825
- provider: z10.string().nullable(),
826
- inputModality: z10.array(modalitySchema).nullable(),
827
- outputModality: z10.array(modalitySchema).nullable()
828
- });
829
- var aiUsageSummarySchema = z10.object({
830
- totalInputTokens: z10.number(),
831
- totalOutputTokens: z10.number(),
832
- totalTokens: z10.number(),
833
- totalImageCount: z10.number(),
834
- totalRequests: z10.number()
835
- });
836
-
837
- // node_modules/@insforge/shared-schemas/dist/ai-api.schema.js
838
- import { z as z11 } from "zod";
839
- var textContentSchema = z11.object({
840
- type: z11.literal("text"),
841
- text: z11.string()
842
- });
843
- var imageContentSchema = z11.object({
844
- type: z11.literal("image_url"),
845
- // eslint-disable-next-line @typescript-eslint/naming-convention
846
- image_url: z11.object({
847
- // URL can be either a public URL or base64-encoded data URI
848
- // Examples:
849
- // - Public URL: "https://example.com/image.jpg"
850
- // - Base64: "data:image/jpeg;base64,/9j/4AAQ..."
851
- url: z11.string(),
852
- detail: z11.enum(["auto", "low", "high"]).optional()
853
- })
854
- });
855
- var contentSchema = z11.union([textContentSchema, imageContentSchema]);
856
- var chatMessageSchema = z11.object({
857
- role: z11.enum(["user", "assistant", "system"]),
858
- // New format: content can be string or array of content parts (OpenAI-compatible)
859
- content: z11.union([z11.string(), z11.array(contentSchema)]),
860
- // Legacy format: separate images field (deprecated but supported for backward compatibility)
861
- images: z11.array(z11.object({ url: z11.string() })).optional()
862
- });
863
- var chatCompletionRequestSchema = z11.object({
864
- model: z11.string(),
865
- messages: z11.array(chatMessageSchema),
866
- temperature: z11.number().min(0).max(2).optional(),
867
- maxTokens: z11.number().positive().optional(),
868
- topP: z11.number().min(0).max(1).optional(),
869
- stream: z11.boolean().optional()
870
- });
871
- var chatCompletionResponseSchema = z11.object({
872
- text: z11.string(),
873
- metadata: z11.object({
874
- model: z11.string(),
875
- usage: z11.object({
876
- promptTokens: z11.number().optional(),
877
- completionTokens: z11.number().optional(),
878
- totalTokens: z11.number().optional()
879
- }).optional()
880
- }).optional()
881
- });
882
- var imageGenerationRequestSchema = z11.object({
883
- model: z11.string(),
884
- prompt: z11.string(),
885
- images: z11.array(z11.object({
886
- url: z11.string()
887
- })).optional()
888
- });
889
- var imageGenerationResponseSchema = z11.object({
890
- text: z11.string().optional(),
891
- images: z11.array(z11.object({
892
- type: z11.literal("imageUrl"),
893
- imageUrl: z11.string()
894
- })),
895
- metadata: z11.object({
896
- model: z11.string(),
897
- usage: z11.object({
898
- promptTokens: z11.number().optional(),
899
- completionTokens: z11.number().optional(),
900
- totalTokens: z11.number().optional()
901
- }).optional()
902
- }).optional()
903
- });
904
- var aiModelSchema = z11.object({
905
- id: z11.string(),
906
- inputModality: z11.array(modalitySchema).min(1),
907
- outputModality: z11.array(modalitySchema).min(1),
908
- provider: z11.string(),
909
- modelId: z11.string(),
910
- priceLevel: z11.number().min(0).max(3).optional()
911
- });
912
- var createAIConfigurationRequestSchema = aiConfigurationSchema.omit({
913
- id: true
914
- });
915
- var updateAIConfigurationRequestSchema = z11.object({
916
- systemPrompt: z11.string().nullable()
917
- });
918
- var listAIUsageResponseSchema = z11.object({
919
- records: z11.array(aiUsageRecordSchema),
920
- total: z11.number()
921
- });
922
- var getAIUsageRequestSchema = z11.object({
923
- startDate: z11.string().datetime().optional(),
924
- endDate: z11.string().datetime().optional(),
925
- limit: z11.string().regex(/^\d+$/).default("50"),
926
- offset: z11.string().regex(/^\d+$/).default("0")
927
- });
928
- var getAIUsageSummaryRequestSchema = z11.object({
929
- configId: z11.string().uuid().optional(),
930
- startDate: z11.string().datetime().optional(),
931
- endDate: z11.string().datetime().optional()
932
- });
933
-
934
- // node_modules/@insforge/shared-schemas/dist/logs.schema.js
935
- import { z as z12 } from "zod";
936
- var auditLogSchema = z12.object({
937
- id: z12.string(),
938
- actor: z12.string(),
939
- action: z12.string(),
940
- module: z12.string(),
941
- details: z12.record(z12.unknown()).nullable(),
942
- ipAddress: z12.string().nullable(),
943
- createdAt: z12.string(),
944
- updatedAt: z12.string()
945
- });
946
- var logSourceSchema = z12.object({
947
- id: z12.string(),
948
- name: z12.string(),
949
- token: z12.string()
950
- });
951
- var logSchema = z12.object({
952
- id: z12.string(),
953
- eventMessage: z12.string(),
954
- timestamp: z12.string(),
955
- body: z12.record(z12.string(), z12.unknown()),
956
- source: z12.string().optional()
957
- });
958
- var logStatsSchema = z12.object({
959
- source: z12.string(),
960
- count: z12.number(),
961
- lastActivity: z12.string()
962
- });
963
-
964
- // node_modules/@insforge/shared-schemas/dist/logs-api.schema.js
965
- import { z as z13 } from "zod";
966
- var getAuditLogsRequestSchema = z13.object({
967
- limit: z13.number().default(100),
968
- offset: z13.number().default(0),
969
- actor: z13.string().optional(),
970
- action: z13.string().optional(),
971
- module: z13.string().optional(),
972
- startDate: z13.string().optional(),
973
- endDate: z13.string().optional()
974
- });
975
- var getAuditLogsResponseSchema = z13.object({
976
- data: z13.array(auditLogSchema),
977
- pagination: z13.object({
978
- limit: z13.number(),
979
- offset: z13.number(),
980
- total: z13.number()
981
- })
982
- });
983
- var getAuditLogStatsRequestSchema = z13.object({
984
- days: z13.number().default(7)
985
- });
986
- var getAuditLogStatsResponseSchema = z13.object({
987
- totalLogs: z13.number(),
988
- uniqueActors: z13.number(),
989
- uniqueModules: z13.number(),
990
- actionsByModule: z13.record(z13.number()),
991
- recentActivity: z13.array(auditLogSchema)
992
- });
993
- var clearAuditLogsRequestSchema = z13.object({
994
- daysToKeep: z13.number().default(90)
995
- });
996
- var clearAuditLogsResponseSchema = z13.object({
997
- message: z13.string(),
998
- deleted: z13.number()
999
- });
1000
- var getLogsResponseSchema = z13.object({
1001
- logs: z13.array(logSchema),
1002
- total: z13.number()
1003
- });
1004
-
1005
- // node_modules/@insforge/shared-schemas/dist/functions.schema.js
1006
- import { z as z14 } from "zod";
1007
- var functionSchema = z14.object({
1008
- id: z14.string(),
1009
- slug: z14.string(),
1010
- name: z14.string(),
1011
- description: z14.string().nullable(),
1012
- code: z14.string(),
1013
- status: z14.enum(["draft", "active"]),
1014
- createdAt: z14.string(),
1015
- updatedAt: z14.string(),
1016
- deployedAt: z14.string().nullable()
1017
- });
1018
-
1019
- // node_modules/@insforge/shared-schemas/dist/functions-api.schema.js
1020
- import { z as z15 } from "zod";
1021
- var functionUploadRequestSchema = z15.object({
1022
- name: z15.string().min(1, "Name is required"),
1023
- slug: z15.string().regex(/^[a-zA-Z0-9_-]+$/, "Invalid slug format - must be alphanumeric with hyphens or underscores only").optional(),
1024
- code: z15.string().min(1),
1025
- description: z15.string().optional(),
1026
- status: z15.enum(["draft", "active"]).optional().default("active")
1027
- });
1028
- var functionUpdateRequestSchema = z15.object({
1029
- name: z15.string().optional(),
1030
- code: z15.string().optional(),
1031
- description: z15.string().optional(),
1032
- status: z15.enum(["draft", "active"]).optional()
1033
- });
1034
-
1035
- // node_modules/@insforge/shared-schemas/dist/cloud-events.schema.js
1036
- import { z as z16 } from "zod";
1037
- var appRouteChangeEventSchema = z16.object({
1038
- type: z16.literal("APP_ROUTE_CHANGE"),
1039
- path: z16.string()
1040
- });
1041
- var authSuccessEventSchema = z16.object({
1042
- type: z16.literal("AUTH_SUCCESS")
1043
- });
1044
- var authErrorEventSchema = z16.object({
1045
- type: z16.literal("AUTH_ERROR"),
1046
- message: z16.string()
1047
- });
1048
- var mcpConnectionStatusEventSchema = z16.object({
1049
- type: z16.literal("MCP_CONNECTION_STATUS"),
1050
- connected: z16.boolean(),
1051
- toolName: z16.string(),
1052
- timestamp: z16.union([z16.number(), z16.string()])
1053
- });
1054
- var showOnboardingOverlayEventSchema = z16.object({
1055
- type: z16.literal("SHOW_ONBOARDING_OVERLAY")
1056
- });
1057
- var showSettingsOverlayEventSchema = z16.object({
1058
- type: z16.literal("SHOW_SETTINGS_OVERLAY")
1059
- });
1060
- var onboardingSuccessSchema = z16.object({
1061
- type: z16.literal("ONBOARDING_SUCCESS")
1062
- });
1063
- var navigateToUsageSchema = z16.object({
1064
- type: z16.literal("NAVIGATE_TO_USAGE")
1065
- });
1066
- var cloudEventSchema = z16.discriminatedUnion("type", [
1067
- appRouteChangeEventSchema,
1068
- authSuccessEventSchema,
1069
- authErrorEventSchema,
1070
- mcpConnectionStatusEventSchema,
1071
- showOnboardingOverlayEventSchema,
1072
- showSettingsOverlayEventSchema,
1073
- onboardingSuccessSchema,
1074
- navigateToUsageSchema
1075
- ]);
1076
-
1077
- // node_modules/@insforge/shared-schemas/dist/docs.schema.js
1078
- import { z as z17 } from "zod";
1079
- var docTypeSchema = z17.enum([
1080
- "instructions",
1081
- "auth-sdk",
1082
- "db-sdk",
1083
- "storage-sdk",
1084
- "functions-sdk",
1085
- "ai-integration-sdk",
1086
- "auth-components-react",
1087
- "auth-components-nextjs",
1088
- "real-time"
1089
- ]).describe(`
1090
- Documentation type:
1091
- "instructions" (essential backend setup - use FIRST),
1092
- "db-sdk" (database operations),
1093
- "storage-sdk" (file storage),
1094
- "functions-sdk" (edge functions),
1095
- "auth-components-react" (authentication components for React+Vite applications),
1096
- "auth-components-nextjs" (authentication components for Next.js applications),
1097
- "ai-integration-sdk" (AI features),
1098
- "real-time" (real-time pub/sub through WebSockets)
1099
- `);
1100
-
1101
- // node_modules/@insforge/shared-schemas/dist/email-api.schema.js
1102
- import { z as z18 } from "zod";
1103
- var emailOrEmails = z18.union([
1104
- emailSchema,
1105
- z18.array(emailSchema).min(1, "At least one email is required").max(50, "Maximum 50 recipients allowed")
1106
- ]);
1107
- var sendRawEmailRequestSchema = z18.object({
1108
- to: emailOrEmails,
1109
- subject: z18.string().trim().min(1, "Subject is required").max(500, "Subject too long"),
1110
- html: z18.string().trim().min(1, "HTML content is required"),
1111
- cc: emailOrEmails.optional(),
1112
- bcc: emailOrEmails.optional(),
1113
- from: z18.string().trim().max(100, "From name too long").optional(),
1114
- replyTo: z18.string().email("Reply-To must be a valid email").optional()
1115
- });
1116
- var sendEmailResponseSchema = z18.object({});
1117
-
1118
- // src/shared/tools.ts
1119
- var execAsync = promisify(exec);
1120
- var TOOL_VERSION_REQUIREMENTS = {
1121
- "upsert-schedule": "1.1.1",
1122
- // 'get-schedules': '1.1.1',
1123
- // 'get-schedule-logs': '1.1.1',
1124
- "delete-schedule": "1.1.1"
1125
- };
1126
- function registerInsforgeTools(server, config = {}) {
1127
- const GLOBAL_API_KEY = config.apiKey || process.env.API_KEY || "";
1128
- const API_BASE_URL = config.apiBaseUrl || process.env.API_BASE_URL || "http://localhost:7130";
1129
- const usageTracker = new UsageTracker(API_BASE_URL, GLOBAL_API_KEY);
1130
- let versionCache = null;
1131
- const VERSION_CACHE_TTL = 5 * 60 * 1e3;
1132
- async function getBackendVersion() {
1133
- const now = Date.now();
1134
- if (versionCache && now - versionCache.timestamp < VERSION_CACHE_TTL) {
1135
- return versionCache.version;
1136
- }
1137
- try {
1138
- const response = await fetch2(`${API_BASE_URL}/api/health`, {
1139
- method: "GET",
1140
- headers: {
1141
- "Content-Type": "application/json"
1142
- }
1143
- });
1144
- if (!response.ok) {
1145
- throw new Error(`Health check failed with status ${response.status}`);
1146
- }
1147
- const health = await response.json();
1148
- versionCache = {
1149
- version: health.version,
1150
- timestamp: now
1151
- };
1152
- return health.version;
1153
- } catch (error) {
1154
- const errMsg = error instanceof Error ? error.message : "Unknown error";
1155
- throw new Error(`Failed to fetch backend version: ${errMsg}`);
1156
- }
1157
- }
1158
- function compareVersions(v1, v2) {
1159
- const clean1 = v1.replace(/^v/, "").split("-")[0];
1160
- const clean2 = v2.replace(/^v/, "").split("-")[0];
1161
- const parts1 = clean1.split(".").map(Number);
1162
- const parts2 = clean2.split(".").map(Number);
1163
- for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
1164
- const part1 = parts1[i] || 0;
1165
- const part2 = parts2[i] || 0;
1166
- if (part1 > part2) return 1;
1167
- if (part1 < part2) return -1;
1168
- }
1169
- return 0;
1170
- }
1171
- async function checkToolVersion(toolName) {
1172
- const requiredVersion = TOOL_VERSION_REQUIREMENTS[toolName];
1173
- if (!requiredVersion) {
1174
- return;
1175
- }
1176
- try {
1177
- const currentVersion = await getBackendVersion();
1178
- if (compareVersions(currentVersion, requiredVersion) < 0) {
1179
- throw new Error(
1180
- `Tool '${toolName}' requires backend version ${requiredVersion} or higher, but current version is ${currentVersion}. Please upgrade your Insforge backend server.`
1181
- );
1182
- }
1183
- } catch (error) {
1184
- if (error instanceof Error && error.message.includes("requires backend version")) {
1185
- throw error;
1186
- }
1187
- console.warn(`Warning: Could not verify backend version for tool '${toolName}': ${error instanceof Error ? error.message : "Unknown error"}`);
1188
- }
1189
- }
1190
- async function trackToolUsage(toolName, success = true) {
1191
- if (GLOBAL_API_KEY) {
1192
- await usageTracker.trackUsage(toolName, success);
1193
- }
1194
- }
1195
- function withUsageTracking(toolName, handler) {
1196
- return async (...args) => {
1197
- try {
1198
- const result = await handler(...args);
1199
- await trackToolUsage(toolName, true);
1200
- return result;
1201
- } catch (error) {
1202
- await trackToolUsage(toolName, false);
1203
- throw error;
1204
- }
1205
- };
1206
- }
1207
- const getApiKey = (_toolApiKey) => {
1208
- if (!GLOBAL_API_KEY) {
1209
- throw new Error("API key is required. Pass --api_key when starting the MCP server.");
1210
- }
1211
- return GLOBAL_API_KEY;
1212
- };
1213
- const fetchDocumentation = async (docType) => {
1214
- try {
1215
- const response = await fetch2(`${API_BASE_URL}/api/docs/${docType}`, {
1216
- method: "GET",
1217
- headers: {
1218
- "Content-Type": "application/json"
1219
- }
1220
- });
1221
- if (response.status === 404) {
1222
- throw new Error("Documentation not found. This feature may not be supported in your project version. Please contact the Insforge team for assistance.");
1223
- }
1224
- const result = await handleApiResponse(response);
1225
- if (result && typeof result === "object" && "content" in result) {
1226
- let content = result.content;
1227
- content = content.replace(/http:\/\/localhost:7130/g, API_BASE_URL);
1228
- content = content.replace(/https:\/\/your-app\.region\.insforge\.app/g, API_BASE_URL);
1229
- return content;
1230
- }
1231
- throw new Error("Invalid response format from documentation endpoint");
1232
- } catch (error) {
1233
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1234
- throw new Error(`Unable to retrieve ${docType} documentation: ${errMsg}`);
1235
- }
1236
- };
1237
- const fetchInsforgeInstructionsContext = async () => {
1238
- try {
1239
- return await fetchDocumentation("instructions");
1240
- } catch (error) {
1241
- console.error("Failed to fetch insforge-instructions.md:", error);
1242
- return null;
1243
- }
1244
- };
1245
- const addBackgroundContext = async (response) => {
1246
- try {
1247
- const currentVersion = await getBackendVersion();
1248
- const isLegacyVersion = compareVersions(currentVersion, "1.1.7") < 0;
1249
- if (isLegacyVersion) {
1250
- const context = await fetchInsforgeInstructionsContext();
1251
- if (context && response.content && Array.isArray(response.content)) {
1252
- response.content.push({
1253
- type: "text",
1254
- text: `
1255
-
1256
- ---
1257
- \u{1F527} INSFORGE DEVELOPMENT RULES (Auto-loaded):
1258
- ${context}`
1259
- });
1260
- }
1261
- }
1262
- } catch {
1263
- console.warn("Could not determine backend version, skipping background context");
1264
- }
1265
- return response;
1266
- };
1267
- server.tool(
1268
- "fetch-docs",
1269
- 'Fetch Insforge documentation. Use "instructions" for essential backend setup (MANDATORY FIRST), or select specific SDK docs for database, auth, storage, functions, or AI integration.',
1270
- {
1271
- docType: docTypeSchema
1272
- },
1273
- withUsageTracking("fetch-docs", async ({ docType }) => {
1274
- try {
1275
- const content = await fetchDocumentation(docType);
1276
- return await addBackgroundContext({
1277
- content: [
1278
- {
1279
- type: "text",
1280
- text: content
1281
- }
1282
- ]
1283
- });
1284
- } catch (error) {
1285
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1286
- if (errMsg.includes("404") || errMsg.toLowerCase().includes("not found")) {
1287
- return {
1288
- content: [{
1289
- type: "text",
1290
- text: `Documentation for "${docType}" is not available. This is likely because your backend version is too old and doesn't support this documentation endpoint yet. This won't affect the functionality of the tools - they will still work correctly.`
1291
- }]
1292
- };
1293
- }
1294
- return {
1295
- content: [{ type: "text", text: `Error fetching ${docType} documentation: ${errMsg}` }]
1296
- };
1297
- }
1298
- })
1299
- );
1300
- server.tool(
1301
- "get-anon-key",
1302
- "Generate an anonymous JWT token that never expires. Requires admin API key. Use this for client-side applications that need public access.",
1303
- {
1304
- apiKey: z19.string().optional().describe("API key for authentication (optional if provided via --api_key)")
1305
- },
1306
- withUsageTracking("get-anon-key", async ({ apiKey }) => {
1307
- try {
1308
- const actualApiKey = getApiKey(apiKey);
1309
- const response = await fetch2(`${API_BASE_URL}/api/auth/tokens/anon`, {
1310
- method: "POST",
1311
- headers: {
1312
- "x-api-key": actualApiKey,
1313
- "Content-Type": "application/json"
1314
- }
1315
- });
1316
- const result = await handleApiResponse(response);
1317
- return await addBackgroundContext({
1318
- content: [
1319
- {
1320
- type: "text",
1321
- text: formatSuccessMessage("Anonymous token generated", result)
1322
- }
1323
- ]
1324
- });
1325
- } catch (error) {
1326
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1327
- return {
1328
- content: [
1329
- {
1330
- type: "text",
1331
- text: `Error generating anonymous token: ${errMsg}`
1332
- }
1333
- ],
1334
- isError: true
1335
- };
1336
- }
1337
- })
1338
- );
1339
- server.tool(
1340
- "get-table-schema",
1341
- "Returns the detailed schema(including RLS, indexes, constraints, etc.) of a specific table",
1342
- {
1343
- apiKey: z19.string().optional().describe("API key for authentication (optional if provided via --api_key)"),
1344
- tableName: z19.string().describe("Name of the table")
1345
- },
1346
- withUsageTracking("get-table-schema", async ({ apiKey, tableName }) => {
1347
- try {
1348
- const actualApiKey = getApiKey(apiKey);
1349
- const response = await fetch2(`${API_BASE_URL}/api/metadata/${tableName}`, {
1350
- method: "GET",
1351
- headers: {
1352
- "x-api-key": actualApiKey
1353
- }
1354
- });
1355
- const result = await handleApiResponse(response);
1356
- return await addBackgroundContext({
1357
- content: [
1358
- {
1359
- type: "text",
1360
- text: formatSuccessMessage("Schema retrieved", result)
1361
- }
1362
- ]
1363
- });
1364
- } catch (error) {
1365
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1366
- return {
1367
- content: [
1368
- {
1369
- type: "text",
1370
- text: `Error getting table schema: ${errMsg}`
1371
- }
1372
- ],
1373
- isError: true
1374
- };
1375
- }
1376
- })
1377
- );
1378
- server.tool(
1379
- "get-backend-metadata",
1380
- "Index all backend metadata",
1381
- {
1382
- apiKey: z19.string().optional().describe("API key for authentication (optional if provided via --api_key)")
1383
- },
1384
- withUsageTracking("get-backend-metadata", async ({ apiKey }) => {
1385
- try {
1386
- const actualApiKey = getApiKey(apiKey);
1387
- const response = await fetch2(`${API_BASE_URL}/api/metadata?mcp=true`, {
1388
- method: "GET",
1389
- headers: {
1390
- "x-api-key": actualApiKey
1391
- }
1392
- });
1393
- const metadata = await handleApiResponse(response);
1394
- return await addBackgroundContext({
1395
- content: [
1396
- {
1397
- type: "text",
1398
- text: `Backend metadata:
1399
-
1400
- ${JSON.stringify(metadata, null, 2)}`
1401
- }
1402
- ]
1403
- });
1404
- } catch (error) {
1405
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1406
- return {
1407
- content: [
1408
- {
1409
- type: "text",
1410
- text: `Error retrieving backend metadata: ${errMsg}`
1411
- }
1412
- ],
1413
- isError: true
1414
- };
1415
- }
1416
- })
1417
- );
1418
- server.tool(
1419
- "run-raw-sql",
1420
- "Execute raw SQL query with optional parameters. Admin access required. Use with caution as it can modify data directly.",
1421
- {
1422
- apiKey: z19.string().optional().describe("API key for authentication (optional if provided via --api_key)"),
1423
- ...rawSQLRequestSchema.shape
1424
- },
1425
- withUsageTracking("run-raw-sql", async ({ apiKey, query, params }) => {
1426
- try {
1427
- const actualApiKey = getApiKey(apiKey);
1428
- const requestBody = {
1429
- query,
1430
- params: params || []
1431
- };
1432
- const response = await fetch2(`${API_BASE_URL}/api/database/advance/rawsql`, {
1433
- method: "POST",
1434
- headers: {
1435
- "x-api-key": actualApiKey,
1436
- "Content-Type": "application/json"
1437
- },
1438
- body: JSON.stringify(requestBody)
1439
- });
1440
- const result = await handleApiResponse(response);
1441
- return await addBackgroundContext({
1442
- content: [
1443
- {
1444
- type: "text",
1445
- text: formatSuccessMessage("SQL query executed", result)
1446
- }
1447
- ]
1448
- });
1449
- } catch (error) {
1450
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1451
- return {
1452
- content: [
1453
- {
1454
- type: "text",
1455
- text: `Error executing SQL query: ${errMsg}`
1456
- }
1457
- ],
1458
- isError: true
1459
- };
1460
- }
1461
- })
1462
- );
1463
- server.tool(
1464
- "create-bucket",
1465
- "Create new storage bucket",
1466
- {
1467
- apiKey: z19.string().optional().describe("API key for authentication (optional if provided via --api_key)"),
1468
- ...createBucketRequestSchema.shape
1469
- },
1470
- withUsageTracking("create-bucket", async ({ apiKey, bucketName, isPublic }) => {
1471
- try {
1472
- const actualApiKey = getApiKey(apiKey);
1473
- const response = await fetch2(`${API_BASE_URL}/api/storage/buckets`, {
1474
- method: "POST",
1475
- headers: {
1476
- "x-api-key": actualApiKey,
1477
- "Content-Type": "application/json"
1478
- },
1479
- body: JSON.stringify({ bucketName, isPublic })
1480
- });
1481
- const result = await handleApiResponse(response);
1482
- return await addBackgroundContext({
1483
- content: [
1484
- {
1485
- type: "text",
1486
- text: formatSuccessMessage("Bucket created", result)
1487
- }
1488
- ]
1489
- });
1490
- } catch (error) {
1491
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1492
- return {
1493
- content: [
1494
- {
1495
- type: "text",
1496
- text: `Error creating bucket: ${errMsg}`
1497
- }
1498
- ],
1499
- isError: true
1500
- };
1501
- }
1502
- })
1503
- );
1504
- server.tool(
1505
- "list-buckets",
1506
- "Lists all storage buckets",
1507
- {},
1508
- withUsageTracking("list-buckets", async () => {
1509
- try {
1510
- const response = await fetch2(`${API_BASE_URL}/api/storage/buckets`, {
1511
- method: "GET",
1512
- headers: {
1513
- "x-api-key": getApiKey()
1514
- }
1515
- });
1516
- const result = await handleApiResponse(response);
1517
- return await addBackgroundContext({
1518
- content: [
1519
- {
1520
- type: "text",
1521
- text: formatSuccessMessage("Buckets retrieved", result)
1522
- }
1523
- ]
1524
- });
1525
- } catch (error) {
1526
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1527
- return {
1528
- content: [
1529
- {
1530
- type: "text",
1531
- text: `Error listing buckets: ${errMsg}`
1532
- }
1533
- ],
1534
- isError: true
1535
- };
1536
- }
1537
- })
1538
- );
1539
- server.tool(
1540
- "delete-bucket",
1541
- "Deletes a storage bucket",
1542
- {
1543
- apiKey: z19.string().optional().describe("API key for authentication (optional if provided via --api_key)"),
1544
- bucketName: z19.string().describe("Name of the bucket to delete")
1545
- },
1546
- withUsageTracking("delete-bucket", async ({ apiKey, bucketName }) => {
1547
- try {
1548
- const actualApiKey = getApiKey(apiKey);
1549
- const response = await fetch2(`${API_BASE_URL}/api/storage/buckets/${bucketName}`, {
1550
- method: "DELETE",
1551
- headers: {
1552
- "x-api-key": actualApiKey
1553
- }
1554
- });
1555
- const result = await handleApiResponse(response);
1556
- return await addBackgroundContext({
1557
- content: [
1558
- {
1559
- type: "text",
1560
- text: formatSuccessMessage("Bucket deleted", result)
1561
- }
1562
- ]
1563
- });
1564
- } catch (error) {
1565
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1566
- return {
1567
- content: [
1568
- {
1569
- type: "text",
1570
- text: `Error deleting bucket: ${errMsg}`
1571
- }
1572
- ],
1573
- isError: true
1574
- };
1575
- }
1576
- })
1577
- );
1578
- server.tool(
1579
- "create-function",
1580
- "Create a new edge function that runs in Deno runtime. The code must be written to a file first for version control",
1581
- {
1582
- ...functionUploadRequestSchema.omit({ code: true }).shape,
1583
- codeFile: z19.string().describe(
1584
- "Path to JavaScript file containing the function code. Must export: module.exports = async function(request) { return new Response(...) }"
1585
- )
1586
- },
1587
- withUsageTracking("create-function", async (args) => {
1588
- try {
1589
- let code;
1590
- try {
1591
- code = await fs.readFile(args.codeFile, "utf-8");
1592
- } catch (fileError) {
1593
- throw new Error(
1594
- `Failed to read code file '${args.codeFile}': ${fileError instanceof Error ? fileError.message : "Unknown error"}`
1595
- );
1596
- }
1597
- const response = await fetch2(`${API_BASE_URL}/api/functions`, {
1598
- method: "POST",
1599
- headers: {
1600
- "Content-Type": "application/json",
1601
- "x-api-key": getApiKey()
1602
- },
1603
- body: JSON.stringify({
1604
- slug: args.slug,
1605
- name: args.name,
1606
- code,
1607
- description: args.description,
1608
- status: args.status
1609
- })
1610
- });
1611
- const result = await handleApiResponse(response);
1612
- return await addBackgroundContext({
1613
- content: [
1614
- {
1615
- type: "text",
1616
- text: formatSuccessMessage(
1617
- `Edge function '${args.slug}' created successfully from ${args.codeFile}`,
1618
- result
1619
- )
1620
- }
1621
- ]
1622
- });
1623
- } catch (error) {
1624
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1625
- return {
1626
- content: [
1627
- {
1628
- type: "text",
1629
- text: `Error creating function: ${errMsg}`
1630
- }
1631
- ],
1632
- isError: true
1633
- };
1634
- }
1635
- })
1636
- );
1637
- server.tool(
1638
- "get-function",
1639
- "Get details of a specific edge function including its code",
1640
- {
1641
- slug: z19.string().describe("The slug identifier of the function")
1642
- },
1643
- withUsageTracking("get-function", async (args) => {
1644
- try {
1645
- const response = await fetch2(`${API_BASE_URL}/api/functions/${args.slug}`, {
1646
- method: "GET",
1647
- headers: {
1648
- "x-api-key": getApiKey()
1649
- }
1650
- });
1651
- const result = await handleApiResponse(response);
1652
- return await addBackgroundContext({
1653
- content: [
1654
- {
1655
- type: "text",
1656
- text: formatSuccessMessage(`Edge function '${args.slug}' details`, result)
1657
- }
1658
- ]
1659
- });
1660
- } catch (error) {
1661
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1662
- return {
1663
- content: [
1664
- {
1665
- type: "text",
1666
- text: `Error getting function: ${errMsg}`
1667
- }
1668
- ],
1669
- isError: true
1670
- };
1671
- }
1672
- })
1673
- );
1674
- server.tool(
1675
- "update-function",
1676
- "Update an existing edge function code or metadata",
1677
- {
1678
- slug: z19.string().describe("The slug identifier of the function to update"),
1679
- ...functionUpdateRequestSchema.omit({ code: true }).shape,
1680
- codeFile: z19.string().optional().describe(
1681
- "Path to JavaScript file containing the new function code. Must export: module.exports = async function(request) { return new Response(...) }"
1682
- )
1683
- },
1684
- withUsageTracking("update-function", async (args) => {
1685
- try {
1686
- const updateData = {};
1687
- if (args.name) {
1688
- updateData.name = args.name;
1689
- }
1690
- if (args.codeFile) {
1691
- try {
1692
- updateData.code = await fs.readFile(args.codeFile, "utf-8");
1693
- } catch (fileError) {
1694
- throw new Error(
1695
- `Failed to read code file '${args.codeFile}': ${fileError instanceof Error ? fileError.message : "Unknown error"}`
1696
- );
1697
- }
1698
- }
1699
- if (args.description !== void 0) {
1700
- updateData.description = args.description;
1701
- }
1702
- if (args.status) {
1703
- updateData.status = args.status;
1704
- }
1705
- const response = await fetch2(`${API_BASE_URL}/api/functions/${args.slug}`, {
1706
- method: "PUT",
1707
- headers: {
1708
- "Content-Type": "application/json",
1709
- "x-api-key": getApiKey()
1710
- },
1711
- body: JSON.stringify(updateData)
1712
- });
1713
- const result = await handleApiResponse(response);
1714
- const fileInfo = args.codeFile ? ` from ${args.codeFile}` : "";
1715
- return await addBackgroundContext({
1716
- content: [
1717
- {
1718
- type: "text",
1719
- text: formatSuccessMessage(
1720
- `Edge function '${args.slug}' updated successfully${fileInfo}`,
1721
- result
1722
- )
1723
- }
1724
- ]
1725
- });
1726
- } catch (error) {
1727
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1728
- return {
1729
- content: [
1730
- {
1731
- type: "text",
1732
- text: `Error updating function: ${errMsg}`
1733
- }
1734
- ],
1735
- isError: true
1736
- };
1737
- }
1738
- })
1739
- );
1740
- server.tool(
1741
- "delete-function",
1742
- "Delete an edge function permanently",
1743
- {
1744
- slug: z19.string().describe("The slug identifier of the function to delete")
1745
- },
1746
- withUsageTracking("delete-function", async (args) => {
1747
- try {
1748
- const response = await fetch2(`${API_BASE_URL}/api/functions/${args.slug}`, {
1749
- method: "DELETE",
1750
- headers: {
1751
- "x-api-key": getApiKey()
1752
- }
1753
- });
1754
- const result = await handleApiResponse(response);
1755
- return await addBackgroundContext({
1756
- content: [
1757
- {
1758
- type: "text",
1759
- text: formatSuccessMessage(`Edge function '${args.slug}' deleted successfully`, result)
1760
- }
1761
- ]
1762
- });
1763
- } catch (error) {
1764
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1765
- return {
1766
- content: [
1767
- {
1768
- type: "text",
1769
- text: `Error deleting function: ${errMsg}`
1770
- }
1771
- ],
1772
- isError: true
1773
- };
1774
- }
1775
- })
1776
- );
1777
- server.tool(
1778
- "get-container-logs",
1779
- "Get latest logs from a specific container/service. Use this to help debug problems with your app.",
1780
- {
1781
- apiKey: z19.string().optional().describe("API key for authentication (optional if provided via --api_key)"),
1782
- source: z19.enum(["insforge.logs", "postgREST.logs", "postgres.logs", "function.logs"]).describe("Log source to retrieve"),
1783
- limit: z19.number().optional().default(20).describe("Number of logs to return (default: 20)")
1784
- },
1785
- withUsageTracking("get-container-logs", async ({ apiKey, source, limit }) => {
1786
- try {
1787
- const actualApiKey = getApiKey(apiKey);
1788
- const queryParams = new URLSearchParams();
1789
- if (limit) queryParams.append("limit", limit.toString());
1790
- let response = await fetch2(`${API_BASE_URL}/api/logs/${source}?${queryParams}`, {
1791
- method: "GET",
1792
- headers: {
1793
- "x-api-key": actualApiKey
1794
- }
1795
- });
1796
- if (response.status === 404) {
1797
- response = await fetch2(`${API_BASE_URL}/api/logs/analytics/${source}?${queryParams}`, {
1798
- method: "GET",
1799
- headers: {
1800
- "x-api-key": actualApiKey
1801
- }
1802
- });
1803
- }
1804
- const result = await handleApiResponse(response);
1805
- return await addBackgroundContext({
1806
- content: [
1807
- {
1808
- type: "text",
1809
- text: formatSuccessMessage(`Latest logs from ${source}`, result)
1810
- }
1811
- ]
1812
- });
1813
- } catch (error) {
1814
- const errMsg = error instanceof Error ? error.message : "Unknown error occurred";
1815
- return {
1816
- content: [
1817
- {
1818
- type: "text",
1819
- text: `Error retrieving container logs: ${errMsg}`
1820
- }
1821
- ],
1822
- isError: true
1823
- };
1824
- }
1825
- })
1826
- );
1827
- return {
1828
- apiKey: GLOBAL_API_KEY,
1829
- apiBaseUrl: API_BASE_URL,
1830
- toolCount: 15
1831
- };
1832
- }
1833
-
1834
- export {
1835
- registerInsforgeTools
1836
- };