@mgsoftwarebv/mcp-server-bridge 2.1.0 → 2.2.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.
package/dist/index.js CHANGED
@@ -148,6 +148,165 @@ var TOOLS = [
148
148
  },
149
149
  required: ["name"]
150
150
  }
151
+ },
152
+ // === NEW AI SESSION TOOLS ===
153
+ {
154
+ name: "start-ai-session-smart",
155
+ description: "Start a new AI development session with automatic time estimation",
156
+ inputSchema: {
157
+ type: "object",
158
+ properties: {
159
+ ticketId: { type: "string" },
160
+ ticketUrl: { type: "string", description: "URL to the ticket" },
161
+ cursorSessionId: { type: "string", description: "Cursor session identifier" },
162
+ codebaseContext: {
163
+ type: "array",
164
+ items: { type: "string" },
165
+ description: "Relevant files for complexity analysis"
166
+ },
167
+ aiTimeEstimateMinutes: {
168
+ type: "number",
169
+ description: "AI estimate in minutes without AI assistance"
170
+ },
171
+ complexityScore: {
172
+ type: "number",
173
+ minimum: 1,
174
+ maximum: 10,
175
+ description: "Estimated complexity from 1-10"
176
+ }
177
+ },
178
+ required: ["ticketId", "aiTimeEstimateMinutes"]
179
+ }
180
+ },
181
+ {
182
+ name: "track-manual-follow-up",
183
+ description: "Track manual follow-up prompt by developer",
184
+ inputSchema: {
185
+ type: "object",
186
+ properties: {
187
+ aiSessionId: { type: "string" },
188
+ originalPrompt: { type: "string" },
189
+ aiResponse: { type: "string" },
190
+ developerFollowUp: { type: "string" },
191
+ followUpReason: {
192
+ type: "string",
193
+ enum: ["incomplete_result", "wrong_approach", "needs_clarification", "error_in_code"]
194
+ },
195
+ outcome: {
196
+ type: "string",
197
+ enum: ["success", "partial_success", "still_failed"],
198
+ default: "success"
199
+ },
200
+ timeSpentMinutes: { type: "number" }
201
+ },
202
+ required: ["aiSessionId", "originalPrompt", "aiResponse", "developerFollowUp", "followUpReason"]
203
+ }
204
+ },
205
+ {
206
+ name: "get-session-context",
207
+ description: "Get current session context for follow-up continuity",
208
+ inputSchema: {
209
+ type: "object",
210
+ properties: {
211
+ aiSessionId: { type: "string" },
212
+ includeTicketData: { type: "boolean", default: true },
213
+ includeTodoProgress: { type: "boolean", default: true },
214
+ includeFollowUpHistory: { type: "boolean", default: false }
215
+ },
216
+ required: ["aiSessionId"]
217
+ }
218
+ },
219
+ {
220
+ name: "sync-session-todos",
221
+ description: "Synchronize todo list with AI session (replace existing) or add new todos",
222
+ inputSchema: {
223
+ type: "object",
224
+ properties: {
225
+ aiSessionId: { type: "string" },
226
+ todos: {
227
+ type: "array",
228
+ items: {
229
+ type: "object",
230
+ properties: {
231
+ todoId: { type: "string", description: "Optional external todo ID for tracking" },
232
+ content: { type: "string" },
233
+ status: { type: "string", enum: ["pending", "in_progress", "completed", "cancelled"] },
234
+ estimatedMinutes: { type: "number" }
235
+ },
236
+ required: ["content", "status"]
237
+ }
238
+ },
239
+ replaceAll: {
240
+ type: "boolean",
241
+ default: true,
242
+ description: "If true, replace all existing todos. If false, add new todos to existing ones"
243
+ }
244
+ },
245
+ required: ["aiSessionId", "todos"]
246
+ }
247
+ },
248
+ {
249
+ name: "add-follow-up-todos",
250
+ description: "Add new todos from follow-up (without replacing existing ones)",
251
+ inputSchema: {
252
+ type: "object",
253
+ properties: {
254
+ aiSessionId: { type: "string" },
255
+ newTodos: {
256
+ type: "array",
257
+ items: {
258
+ type: "object",
259
+ properties: {
260
+ content: { type: "string" },
261
+ status: { type: "string", enum: ["pending", "in_progress"], default: "pending" },
262
+ estimatedMinutes: { type: "number" },
263
+ addedInFollowUp: { type: "boolean", default: true }
264
+ },
265
+ required: ["content"]
266
+ }
267
+ },
268
+ followUpReason: {
269
+ type: "string",
270
+ description: "Why were these todos added in follow-up"
271
+ }
272
+ },
273
+ required: ["aiSessionId", "newTodos"]
274
+ }
275
+ },
276
+ {
277
+ name: "log-activity-time",
278
+ description: "Log time spent per activity type",
279
+ inputSchema: {
280
+ type: "object",
281
+ properties: {
282
+ aiSessionId: { type: "string" },
283
+ activityType: {
284
+ type: "string",
285
+ enum: ["thinking", "coding", "debugging", "testing", "documenting"]
286
+ },
287
+ durationSeconds: { type: "number" },
288
+ description: { type: "string" },
289
+ productivityScore: { type: "number", minimum: 1, maximum: 10 }
290
+ },
291
+ required: ["aiSessionId", "activityType", "durationSeconds"]
292
+ }
293
+ },
294
+ {
295
+ name: "update-session-status",
296
+ description: "Update AI session status and completion info",
297
+ inputSchema: {
298
+ type: "object",
299
+ properties: {
300
+ aiSessionId: { type: "string" },
301
+ status: {
302
+ type: "string",
303
+ enum: ["started", "in_progress", "paused", "completed", "failed"]
304
+ },
305
+ actualTimeMinutes: { type: "number" },
306
+ completionNotes: { type: "string" }
307
+ },
308
+ required: ["aiSessionId", "status"]
309
+ }
151
310
  }
152
311
  ];
153
312
  var RESOURCES = [
@@ -379,6 +538,252 @@ ${project.description ? `Description: ${project.description}
379
538
  Name: ${name2}
380
539
  Status: ${status}
381
540
  ${description ? `Description: ${description}
541
+ ` : ""}`
542
+ }]
543
+ };
544
+ }
545
+ // === AI SESSION TOOLS ===
546
+ case "start-ai-session-smart": {
547
+ const { ticketId, ticketUrl, cursorSessionId, codebaseContext, aiTimeEstimateMinutes, complexityScore } = args2;
548
+ const { data: sessionData, error } = await supabase.from("ai_sessions").insert({
549
+ ticket_id: ticketId,
550
+ provider_user_id: authContext.userId,
551
+ team_id: authContext.teamId,
552
+ cursor_session_id: cursorSessionId || null,
553
+ ai_time_estimate_minutes: aiTimeEstimateMinutes,
554
+ complexity_score: complexityScore || null,
555
+ status: "started"
556
+ }).select("id, ticket_id, cursor_session_id, created_at").single();
557
+ if (error) throw error;
558
+ const sessionId = `ai-sess-${sessionData.id.substring(0, 8)}`;
559
+ return {
560
+ content: [{
561
+ type: "text",
562
+ text: `\u{1F680} **AI Session Started Successfully!**
563
+
564
+ Session ID: **${sessionId}**
565
+ Ticket: ${ticketId}
566
+ Time Estimate: ${aiTimeEstimateMinutes} minutes
567
+ ${complexityScore ? `Complexity: ${complexityScore}/10
568
+ ` : ""}${cursorSessionId ? `Cursor Session: ${cursorSessionId}
569
+ ` : ""}Created: ${(/* @__PURE__ */ new Date()).toLocaleString()}
570
+
571
+ \u2705 Ready for development and follow-up tracking!`
572
+ }]
573
+ };
574
+ }
575
+ case "track-manual-follow-up": {
576
+ const { aiSessionId, originalPrompt, aiResponse, developerFollowUp, followUpReason, outcome = "success", timeSpentMinutes } = args2;
577
+ const sessionUuid = aiSessionId.replace("ai-sess-", "");
578
+ const { data: session, error: sessionError } = await supabase.from("ai_sessions").select("id").eq("team_id", authContext.teamId).ilike("id", `${sessionUuid}%`).single();
579
+ if (sessionError || !session) {
580
+ throw new Error(`Session not found: ${aiSessionId}`);
581
+ }
582
+ const { data, error } = await supabase.from("manual_follow_ups").insert({
583
+ ai_session_id: session.id,
584
+ developer_id: authContext.userId,
585
+ team_id: authContext.teamId,
586
+ original_prompt: originalPrompt,
587
+ ai_response: aiResponse,
588
+ follow_up_prompt: developerFollowUp,
589
+ follow_up_reason: followUpReason,
590
+ outcome,
591
+ time_spent_minutes: timeSpentMinutes || null,
592
+ resolved_at: outcome === "success" ? (/* @__PURE__ */ new Date()).toISOString() : null
593
+ }).select().single();
594
+ if (error) throw error;
595
+ return {
596
+ content: [{
597
+ type: "text",
598
+ text: `\u2705 **Follow-up Tracked Successfully!**
599
+
600
+ Session: ${aiSessionId}
601
+ Reason: ${followUpReason.replace("_", " ")}
602
+ Outcome: ${outcome}
603
+ ${timeSpentMinutes ? `Time spent: ${timeSpentMinutes} minutes
604
+ ` : ""}
605
+ \u{1F4CA} This data will improve future AI interactions!`
606
+ }]
607
+ };
608
+ }
609
+ case "get-session-context": {
610
+ const { aiSessionId, includeTicketData = true, includeTodoProgress = true, includeFollowUpHistory = false } = args2;
611
+ const sessionUuid = aiSessionId.replace("ai-sess-", "");
612
+ let query = supabase.from("ai_sessions").select(`
613
+ id,
614
+ ticket_id,
615
+ status,
616
+ ai_time_estimate_minutes,
617
+ actual_time_minutes,
618
+ complexity_score,
619
+ created_at,
620
+ cursor_session_id
621
+ `).eq("team_id", authContext.teamId).ilike("id", `${sessionUuid}%`).single();
622
+ const { data: session, error: sessionError } = await query;
623
+ if (sessionError || !session) {
624
+ throw new Error(`Session not found: ${aiSessionId}`);
625
+ }
626
+ let context = {
627
+ sessionId: aiSessionId,
628
+ status: session.status,
629
+ timeEstimate: session.ai_time_estimate_minutes,
630
+ actualTime: session.actual_time_minutes,
631
+ complexity: session.complexity_score,
632
+ createdAt: session.created_at
633
+ };
634
+ if (includeTicketData) {
635
+ const { data: ticket } = await supabase.from("tickets").select("id, ticket_number, title, description, status, priority, type").eq("id", session.ticket_id).single();
636
+ context.ticketData = ticket;
637
+ }
638
+ if (includeTodoProgress) {
639
+ const { data: todos } = await supabase.from("ai_todos").select("id, content, status, estimated_minutes, actual_minutes").eq("ai_session_id", session.id).order("sequence_order");
640
+ context.todos = todos || [];
641
+ context.todoProgress = {
642
+ total: todos?.length || 0,
643
+ completed: todos?.filter((t) => t.status === "completed").length || 0,
644
+ inProgress: todos?.filter((t) => t.status === "in_progress").length || 0
645
+ };
646
+ }
647
+ if (includeFollowUpHistory) {
648
+ const { data: followUps } = await supabase.from("manual_follow_ups").select("follow_up_reason, outcome, time_spent_minutes, created_at").eq("ai_session_id", session.id).order("created_at");
649
+ context.followUpHistory = followUps || [];
650
+ }
651
+ return {
652
+ content: [{
653
+ type: "text",
654
+ text: `\u{1F3AF} **Session Context Retrieved**
655
+
656
+ Session: ${aiSessionId}
657
+ Status: ${session.status}
658
+ ${context.ticketData ? `Ticket: ${context.ticketData.ticket_number} - ${context.ticketData.title}
659
+ ` : ""}${context.todoProgress ? `Todo Progress: ${context.todoProgress.completed}/${context.todoProgress.total} completed
660
+ ` : ""}${context.followUpHistory ? `Follow-ups: ${context.followUpHistory.length}
661
+ ` : ""}
662
+ \u{1F4CB} Full context preserved for seamless continuation!`
663
+ }]
664
+ };
665
+ }
666
+ case "sync-session-todos": {
667
+ const { aiSessionId, todos, replaceAll = true } = args2;
668
+ const sessionUuid = aiSessionId.replace("ai-sess-", "");
669
+ const { data: session, error: sessionError } = await supabase.from("ai_sessions").select("id").eq("team_id", authContext.teamId).ilike("id", `${sessionUuid}%`).single();
670
+ if (sessionError || !session) {
671
+ throw new Error(`Session not found: ${aiSessionId}`);
672
+ }
673
+ if (replaceAll) {
674
+ await supabase.from("ai_todos").delete().eq("ai_session_id", session.id);
675
+ }
676
+ if (todos && todos.length > 0) {
677
+ let startSequence = 0;
678
+ if (!replaceAll) {
679
+ const { data: maxTodo } = await supabase.from("ai_todos").select("sequence_order").eq("ai_session_id", session.id).order("sequence_order", { ascending: false }).limit(1).single();
680
+ startSequence = (maxTodo?.sequence_order || 0) + 1;
681
+ }
682
+ const todoInserts = todos.map((todo, index) => ({
683
+ ai_session_id: session.id,
684
+ content: todo.content,
685
+ status: todo.status,
686
+ cursor_todo_id: todo.todoId || null,
687
+ estimated_minutes: todo.estimatedMinutes || null,
688
+ sequence_order: startSequence + index
689
+ }));
690
+ const { error: insertError } = await supabase.from("ai_todos").insert(todoInserts);
691
+ if (insertError) throw insertError;
692
+ }
693
+ return {
694
+ content: [{
695
+ type: "text",
696
+ text: `\u2705 **Todos ${replaceAll ? "Synced" : "Added"} Successfully!**
697
+
698
+ Session: ${aiSessionId}
699
+ ${replaceAll ? "Synced" : "Added"} ${todos?.length || 0} todos
700
+ ${replaceAll ? "" : "\u2795 Added to existing todo list\n"}
701
+ \u{1F4DD} Todo list updated and tracked for progress monitoring!`
702
+ }]
703
+ };
704
+ }
705
+ case "add-follow-up-todos": {
706
+ const { aiSessionId, newTodos, followUpReason } = args2;
707
+ const sessionUuid = aiSessionId.replace("ai-sess-", "");
708
+ const { data: session, error: sessionError } = await supabase.from("ai_sessions").select("id").eq("team_id", authContext.teamId).ilike("id", `${sessionUuid}%`).single();
709
+ if (sessionError || !session) {
710
+ throw new Error(`Session not found: ${aiSessionId}`);
711
+ }
712
+ if (newTodos && newTodos.length > 0) {
713
+ const { data: maxTodo } = await supabase.from("ai_todos").select("sequence_order").eq("ai_session_id", session.id).order("sequence_order", { ascending: false }).limit(1).single();
714
+ const startSequence = (maxTodo?.sequence_order || 0) + 1;
715
+ const todoInserts = newTodos.map((todo, index) => ({
716
+ ai_session_id: session.id,
717
+ content: `[Follow-up] ${todo.content}`,
718
+ status: todo.status || "pending",
719
+ estimated_minutes: todo.estimatedMinutes || null,
720
+ sequence_order: startSequence + index
721
+ }));
722
+ const { error: insertError } = await supabase.from("ai_todos").insert(todoInserts);
723
+ if (insertError) throw insertError;
724
+ }
725
+ return {
726
+ content: [{
727
+ type: "text",
728
+ text: `\u2705 **Follow-up Todos Added Successfully!**
729
+
730
+ Session: ${aiSessionId}
731
+ Added ${newTodos?.length || 0} new todos from follow-up
732
+ ${followUpReason ? `Reason: ${followUpReason}
733
+ ` : ""}
734
+ \u{1F4DD} New tasks identified and added to existing workflow!`
735
+ }]
736
+ };
737
+ }
738
+ case "log-activity-time": {
739
+ const { aiSessionId, activityType, durationSeconds, description, productivityScore } = args2;
740
+ const sessionUuid = aiSessionId.replace("ai-sess-", "");
741
+ const { data: session, error: sessionError } = await supabase.from("ai_sessions").select("id").eq("team_id", authContext.teamId).ilike("id", `${sessionUuid}%`).single();
742
+ if (sessionError || !session) {
743
+ throw new Error(`Session not found: ${aiSessionId}`);
744
+ }
745
+ const { data, error } = await supabase.from("ai_time_logs").insert({
746
+ ai_session_id: session.id,
747
+ activity_type: activityType,
748
+ duration_seconds: durationSeconds,
749
+ description: description || null,
750
+ productivity_score: productivityScore || null,
751
+ ended_at: (/* @__PURE__ */ new Date()).toISOString()
752
+ }).select().single();
753
+ if (error) throw error;
754
+ return {
755
+ content: [{
756
+ type: "text",
757
+ text: `\u23F1\uFE0F **Activity Time Logged!**
758
+
759
+ Session: ${aiSessionId}
760
+ Activity: ${activityType}
761
+ Duration: ${Math.round(durationSeconds / 60)} minutes
762
+ ${productivityScore ? `Productivity: ${productivityScore}/10
763
+ ` : ""}
764
+ \u{1F4CA} Time tracking data saved for analysis!`
765
+ }]
766
+ };
767
+ }
768
+ case "update-session-status": {
769
+ const { aiSessionId, status, actualTimeMinutes, completionNotes } = args2;
770
+ const sessionUuid = aiSessionId.replace("ai-sess-", "");
771
+ const { data, error } = await supabase.from("ai_sessions").update({
772
+ status,
773
+ actual_time_minutes: actualTimeMinutes || null,
774
+ completed_at: status === "completed" ? (/* @__PURE__ */ new Date()).toISOString() : null
775
+ }).eq("team_id", authContext.teamId).ilike("id", `${sessionUuid}%`).select().single();
776
+ if (error) throw error;
777
+ return {
778
+ content: [{
779
+ type: "text",
780
+ text: `\u{1F3AF} **Session Status Updated!**
781
+
782
+ Session: ${aiSessionId}
783
+ Status: ${status}
784
+ ${actualTimeMinutes ? `Actual Time: ${actualTimeMinutes} minutes
785
+ ` : ""}${status === "completed" ? `\u2705 Session completed successfully!
786
+ ` : ""}${completionNotes ? `Notes: ${completionNotes}
382
787
  ` : ""}`
383
788
  }]
384
789
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["args","name"],"mappings":";;;;;;;AASA,IAAM,IAAA,GAAO,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AACjC,IAAM,MAAA,GAAS,IAAA,CAAK,IAAA,CAAK,CAAA,GAAA,KAAO,IAAI,UAAA,CAAW,YAAY,CAAC,CAAA,EAAG,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IAAK,QAAQ,GAAA,CAAI,kBAAA;AAE5F,IAAM,cAAc,IAAA,CAAK,IAAA,CAAK,CAAA,GAAA,KAAO,GAAA,CAAI,WAAW,iBAAiB,CAAC,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IACnF,OAAA,CAAQ,IAAI,YAAA,IACZ,0CAAA;AAEF,IAAM,cAAc,IAAA,CAAK,IAAA,CAAK,CAAA,GAAA,KAAO,GAAA,CAAI,WAAW,iBAAiB,CAAC,CAAA,EAAG,KAAA,CAAM,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AAA,CAAE,CAAA;AAC3F,EAAA,OAAA,CAAQ,MAAM,CAAA,4BAAA,EAAwB,WAAA,CAAY,OAAO,IAAA,CAAK,IAAI,CAAC,CAAA,CAAE,CAAA;AACrE,EAAA,OAAA,CAAQ,MAAM,mDAA4C,CAAA;AAE1D,EAAA,MAAM,SAAA,GAAY,IAAI,oBAAA,EAAqB;AAC3C,EAAA,MAAM,MAAA,CAAO,QAAQ,SAAS,CAAA;AAChC;AAGA,OAAA,CAAQ,EAAA,CAAG,UAAU,YAAY;AAC/B,EAAA,OAAA,CAAQ,MAAM,8CAAuC,CAAA;AACrD,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA;AAED,OAAA,CAAQ,EAAA,CAAG,WAAW,YAAY;AAChC,EAAA,OAAA,CAAQ,MAAM,8CAAuC,CAAA;AACrD,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA;AAGD,IAAA,EAAK,CAAE,KAAA,CAAM,CAAC,KAAA,KAAU;AACtB,EAAA,OAAA,CAAQ,KAAA,CAAM,0BAAmB,KAAK,CAAA;AACtC,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA","file":"index.js","sourcesContent":["#!/usr/bin/env node\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport { createClient } from '@supabase/supabase-js';\nimport { createHash } from 'crypto';\n\n// Parse command line arguments and environment\nconst args = process.argv.slice(2);\nconst apiKey = args.find(arg => arg.startsWith('--api-key='))?.split('=')[1] || process.env.MG_TICKETS_API_KEY;\n// Default to MG Software's Supabase for SaaS customers\nconst supabaseUrl = args.find(arg => arg.startsWith('--supabase-url='))?.split('=')[1] || \n process.env.SUPABASE_URL || \n 'https://cvjdbczxyczjnatuolsk.supabase.co';\n\nconst supabaseKey = args.find(arg => arg.startsWith('--supabase-key='))?.split('=')[1] || \n process.env.SUPABASE_SERVICE_ROLE_KEY || \n 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImN2amRiY3p4eWN6am5hdHVvbHNrIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc1NjE0NzcyNCwiZXhwIjoyMDcxNzIzNzI0fQ.LljuNdCZXDcSIVTeIVOSNsvGNBfWsIM1QIswBJmGXKE';\n\nif (!apiKey) {\n console.error('❌ API key is required. Use --api-key=your_key or set MG_TICKETS_API_KEY environment variable');\n process.exit(1);\n}\n\n// Supabase credentials validation (optional with defaults)\nif (!supabaseUrl || !supabaseKey) {\n console.error('❌ Supabase credentials missing. Using defaults for MG Software SaaS.');\n}\n\n// Initialize Supabase client with service role\nconst supabase = createClient(supabaseUrl, supabaseKey);\n\ninterface AuthContext {\n userId: string;\n teamId: string;\n scopes: string[];\n}\n\n// API Key validation - direct database access\nasync function validateApiKey(key: string): Promise<AuthContext | null> {\n if (!key.startsWith('mid_') || key.length !== 68) {\n console.error('🔑 Invalid API key format');\n return null;\n }\n\n try {\n // Hash the API key\n const keyHash = createHash('sha256').update(key).digest('hex');\n console.error(`🔍 Validating API key hash: ${keyHash.substring(0, 16)}...`);\n \n // Query database for API key\n const { data: apiKeyData, error } = await supabase\n .from('api_keys')\n .select('id, user_id, team_id, scopes, last_used_at')\n .eq('key_hash', keyHash)\n .single();\n\n if (error || !apiKeyData) {\n console.error('❌ API key not found or invalid:', error?.message);\n return null;\n }\n\n // Update last used timestamp\n await supabase\n .from('api_keys')\n .update({ last_used_at: new Date().toISOString() })\n .eq('id', apiKeyData.id);\n\n console.error(`✅ API key validated for user ${apiKeyData.user_id} in team ${apiKeyData.team_id}`);\n \n return {\n userId: apiKeyData.user_id,\n teamId: apiKeyData.team_id,\n scopes: apiKeyData.scopes || []\n };\n } catch (error) {\n console.error('💥 API key validation error:', error);\n return null;\n }\n}\n\n// Validate auth context once at startup\nlet authContext: AuthContext | null = null;\n\n// MCP Server setup\nconst server = new Server(\n {\n name: 'mg-tickets-mcp-bridge',\n version: '1.0.0',\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n }\n);\n\n// Available tools definition\nconst TOOLS = [\n {\n name: 'get-tickets',\n description: 'Get tickets with optional filtering by status, priority, project, customer, or search query',\n inputSchema: {\n type: 'object',\n properties: {\n status: { type: 'string', enum: ['open', 'in_progress', 'review', 'resolved', 'closed', 'backlog'] },\n priority: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },\n projectId: { type: 'string' },\n customerId: { type: 'string' },\n q: { type: 'string', description: 'Search query for title or description' },\n pageSize: { type: 'number', default: 20, maximum: 100 }\n },\n required: []\n }\n },\n {\n name: 'get-ticket-by-id',\n description: 'Get a specific ticket by its ID',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Ticket ID' }\n },\n required: ['id']\n }\n },\n {\n name: 'create-ticket',\n description: 'Create a new ticket',\n inputSchema: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'Ticket title' },\n description: { type: 'string' },\n status: { type: 'string', enum: ['open', 'in_progress', 'review', 'resolved', 'closed', 'backlog'], default: 'open' },\n priority: { type: 'string', enum: ['low', 'medium', 'high', 'critical'], default: 'medium' },\n type: { type: 'string', enum: ['task', 'bug', 'feature', 'support', 'question', 'improvement'], default: 'task' },\n projectId: { type: 'string' },\n customerId: { type: 'string' }\n },\n required: ['title']\n }\n },\n {\n name: 'get-customers',\n description: 'Get customers with optional search',\n inputSchema: {\n type: 'object',\n properties: {\n q: { type: 'string', description: 'Search query for customer name or email' },\n pageSize: { type: 'number', default: 20, maximum: 100 }\n },\n required: []\n }\n },\n {\n name: 'create-customer',\n description: 'Create a new customer',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Customer name' },\n email: { type: 'string' },\n website: { type: 'string' }\n },\n required: ['name']\n }\n },\n {\n name: 'get-projects',\n description: 'Get projects with optional filtering',\n inputSchema: {\n type: 'object',\n properties: {\n customerId: { type: 'string', description: 'Filter by customer ID' },\n q: { type: 'string', description: 'Search query for project name' },\n pageSize: { type: 'number', default: 20, maximum: 100 }\n },\n required: []\n }\n },\n {\n name: 'create-project',\n description: 'Create a new project',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Project name' },\n description: { type: 'string' },\n customerId: { type: 'string' },\n status: { type: 'string', enum: ['active', 'on_hold', 'completed', 'cancelled'], default: 'active' }\n },\n required: ['name']\n }\n }\n];\n\n// Available resources\nconst RESOURCES = [\n {\n uri: 'tickets://recent',\n name: 'Recent Tickets',\n description: 'Most recently created tickets',\n mimeType: 'application/json'\n },\n {\n uri: 'customers://all',\n name: 'All Customers', \n description: 'Complete customer directory',\n mimeType: 'application/json'\n },\n {\n uri: 'projects://active',\n name: 'Active Projects',\n description: 'Currently active projects',\n mimeType: 'application/json'\n }\n];\n\n// List tools handler\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n return { tools: TOOLS };\n});\n\n// List resources handler\nserver.setRequestHandler(ListResourcesRequestSchema, async () => {\n return { resources: RESOURCES };\n});\n\n// Tool execution handler\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n if (!authContext) {\n return {\n content: [{ type: 'text', text: 'Error: Not authenticated. API key validation failed.' }],\n };\n }\n\n const { name, arguments: args } = request.params;\n console.error(`🛠️ Executing tool: ${name} for team ${authContext.teamId}`);\n \n try {\n switch (name) {\n case 'get-tickets': {\n const { status, priority, projectId, customerId, q, pageSize = 20 } = args as any;\n \n let query = supabase\n .from('tickets')\n .select(`\n id,\n ticket_number,\n title,\n description,\n status,\n priority,\n type,\n created_at,\n project_id,\n customer_id,\n projects:project_id(id, name),\n customers:customer_id(id, name)\n `)\n .eq('team_id', authContext.teamId)\n .limit(Math.min(pageSize, 100));\n \n if (status) query = query.eq('status', status);\n if (priority) query = query.eq('priority', priority);\n if (projectId) query = query.eq('project_id', projectId);\n if (customerId) query = query.eq('customer_id', customerId);\n if (q) query = query.or(`title.ilike.%${q}%,description.ilike.%${q}%`);\n \n const { data, error } = await query.order('created_at', { ascending: false });\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `Found ${data?.length || 0} tickets:\\n\\n${data?.map(ticket => \n `**${ticket.ticket_number}**: ${ticket.title}\\n` +\n `Status: ${ticket.status} | Priority: ${ticket.priority}\\n` +\n `${(ticket.projects as any)?.name ? `Project: ${(ticket.projects as any).name}\\n` : ''}` +\n `${(ticket.customers as any)?.name ? `Customer: ${(ticket.customers as any).name}\\n` : ''}` +\n `Created: ${new Date(ticket.created_at).toLocaleDateString()}\\n`\n ).join('\\n') || 'No tickets found.'}`\n }]\n };\n }\n \n case 'get-ticket-by-id': {\n const { id } = args as any;\n \n const { data, error } = await supabase\n .from('tickets')\n .select(`\n *,\n projects:project_id(id, name),\n customers:customer_id(id, name),\n assignee:assignee_id(id, full_name, email),\n requester:requester_id(id, full_name, email)\n `)\n .eq('id', id)\n .eq('team_id', authContext.teamId)\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `**Ticket Details:**\\n\\n` +\n `**${data.ticket_number}**: ${data.title}\\n` +\n `Status: ${data.status}\\n` +\n `Priority: ${data.priority}\\n` +\n `Type: ${data.type}\\n` +\n `${data.description ? `Description: ${data.description}\\n` : ''}` +\n `${(data.projects as any)?.name ? `Project: ${(data.projects as any).name}\\n` : ''}` +\n `${(data.customers as any)?.name ? `Customer: ${(data.customers as any).name}\\n` : ''}` +\n `${data.assignee?.full_name ? `Assignee: ${data.assignee.full_name}\\n` : ''}` +\n `Requester: ${data.requester?.full_name || 'Unknown'}\\n` +\n `Created: ${new Date(data.created_at).toLocaleDateString()}\\n`\n }]\n };\n }\n \n case 'create-ticket': {\n const { title, description, status = 'open', priority = 'medium', type = 'task', projectId, customerId } = args as any;\n \n // Generate ticket number\n const year = new Date().getFullYear();\n const { count } = await supabase\n .from('tickets')\n .select('*', { count: 'exact', head: true })\n .eq('team_id', authContext.teamId);\n \n const ticketNumber = `${year}-${String((count || 0) + 1).padStart(3, '0')}`;\n \n const { data, error } = await supabase\n .from('tickets')\n .insert({\n team_id: authContext.teamId,\n ticket_number: ticketNumber,\n title,\n description,\n status,\n priority,\n type,\n project_id: projectId || null,\n customer_id: customerId || null,\n requester_id: authContext.userId\n })\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Ticket Created Successfully!**\\n\\n` +\n `Ticket Number: **${ticketNumber}**\\n` +\n `Title: ${title}\\n` +\n `Status: ${status}\\n` +\n `Priority: ${priority}\\n` +\n `Type: ${type}\\n`\n }]\n };\n }\n \n case 'get-customers': {\n const { q, pageSize = 20 } = args as any;\n \n let query = supabase\n .from('customers')\n .select('id, name, email, website, created_at')\n .eq('team_id', authContext.teamId)\n .limit(Math.min(pageSize, 100));\n \n if (q) query = query.or(`name.ilike.%${q}%,email.ilike.%${q}%`);\n \n const { data, error } = await query.order('name');\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `Found ${data?.length || 0} customers:\\n\\n${data?.map(customer => \n `**${customer.name}**\\n` +\n `${customer.email ? `Email: ${customer.email}\\n` : ''}` +\n `${customer.website ? `Website: ${customer.website}\\n` : ''}` +\n `Created: ${new Date(customer.created_at).toLocaleDateString()}\\n`\n ).join('\\n') || 'No customers found.'}`\n }]\n };\n }\n \n case 'create-customer': {\n const { name, email, website } = args as any;\n \n const { data, error } = await supabase\n .from('customers')\n .insert({\n team_id: authContext.teamId,\n name,\n email: email || null,\n website: website || null,\n user_id: authContext.userId\n })\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Customer Created Successfully!**\\n\\n` +\n `Name: ${name}\\n` +\n `${email ? `Email: ${email}\\n` : ''}` +\n `${website ? `Website: ${website}\\n` : ''}`\n }]\n };\n }\n \n case 'get-projects': {\n const { customerId, q, pageSize = 20 } = args as any;\n \n let query = supabase\n .from('projects')\n .select(`\n id,\n name,\n description,\n customer_id,\n status,\n created_at,\n customers:customer_id(id, name)\n `)\n .eq('team_id', authContext.teamId)\n .limit(Math.min(pageSize, 100));\n \n if (customerId) query = query.eq('customer_id', customerId);\n if (q) query = query.ilike('name', `%${q}%`);\n \n const { data, error } = await query.order('name');\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `Found ${data?.length || 0} projects:\\n\\n${data?.map(project => \n `**${project.name}**\\n` +\n `Status: ${project.status}\\n` +\n `${project.description ? `Description: ${project.description}\\n` : ''}` +\n `${(project.customers as any)?.name ? `Customer: ${(project.customers as any).name}\\n` : ''}` +\n `Created: ${new Date(project.created_at).toLocaleDateString()}\\n`\n ).join('\\n') || 'No projects found.'}`\n }]\n };\n }\n \n case 'create-project': {\n const { name, description, customerId, status = 'active' } = args as any;\n \n const { data, error } = await supabase\n .from('projects')\n .insert({\n team_id: authContext.teamId,\n name,\n description: description || null,\n customer_id: customerId || null,\n status,\n user_id: authContext.userId\n })\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Project Created Successfully!**\\n\\n` +\n `Name: ${name}\\n` +\n `Status: ${status}\\n` +\n `${description ? `Description: ${description}\\n` : ''}`\n }]\n };\n }\n \n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n \n } catch (error) {\n console.error(`❌ Tool execution error:`, error);\n return {\n content: [{\n type: 'text',\n text: `Error executing ${name}: ${error instanceof Error ? error.message : 'Unknown error'}`\n }]\n };\n }\n});\n\n// Resource read handler\nserver.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n if (!authContext) {\n return {\n contents: [{\n uri: request.params.uri,\n mimeType: 'text/plain',\n text: 'Error: Not authenticated. API key validation failed.'\n }]\n };\n }\n\n const { uri } = request.params;\n console.error(`📚 Reading resource: ${uri}`);\n \n try {\n switch (uri) {\n case 'tickets://recent': {\n const { data, error } = await supabase\n .from('tickets')\n .select(`\n id,\n ticket_number,\n title,\n status,\n priority,\n created_at\n `)\n .eq('team_id', authContext.teamId)\n .order('created_at', { ascending: false })\n .limit(20);\n \n if (error) throw error;\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(data, null, 2)\n }]\n };\n }\n \n case 'customers://all': {\n const { data, error } = await supabase\n .from('customers')\n .select('id, name, email, website, created_at')\n .eq('team_id', authContext.teamId)\n .order('name')\n .limit(50);\n \n if (error) throw error;\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(data, null, 2)\n }]\n };\n }\n \n case 'projects://active': {\n const { data, error } = await supabase\n .from('projects')\n .select(`\n id,\n name,\n description,\n status,\n created_at,\n customers:customer_id(id, name)\n `)\n .eq('team_id', authContext.teamId)\n .eq('status', 'active')\n .order('name')\n .limit(50);\n \n if (error) throw error;\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(data, null, 2)\n }]\n };\n }\n \n default:\n throw new Error(`Unknown resource: ${uri}`);\n }\n \n } catch (error) {\n console.error(`❌ Resource read error:`, error);\n return {\n contents: [{\n uri,\n mimeType: 'text/plain',\n text: `Error reading ${uri}: ${error instanceof Error ? error.message : 'Unknown error'}`\n }]\n };\n }\n});\n\n// Main function\nasync function main() {\n console.error('🚀 Starting MG Tickets MCP Bridge Server...');\n console.error(`🔑 API Key: ${apiKey?.substring(0, 10)}...`);\n \n // Validate API key\n authContext = await validateApiKey(apiKey!);\n if (!authContext) {\n console.error('❌ API key validation failed. Please check your key and try again.');\n process.exit(1);\n }\n \n console.error(`✅ Authenticated as user ${authContext.userId} in team ${authContext.teamId}`);\n console.error(`📋 Available scopes: ${authContext.scopes.join(', ')}`);\n console.error('📡 MCP Bridge Server ready for connections');\n \n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\n// Handle graceful shutdown\nprocess.on('SIGINT', async () => {\n console.error('👋 Shutting down MCP Bridge Server...');\n process.exit(0);\n});\n\nprocess.on('SIGTERM', async () => {\n console.error('👋 Shutting down MCP Bridge Server...');\n process.exit(0);\n});\n\n// Start the server\nmain().catch((error) => {\n console.error('💥 Fatal error:', error);\n process.exit(1);\n});"]}
1
+ {"version":3,"sources":["../src/index.ts"],"names":["args","name"],"mappings":";;;;;;;AASA,IAAM,IAAA,GAAO,OAAA,CAAQ,IAAA,CAAK,KAAA,CAAM,CAAC,CAAA;AACjC,IAAM,MAAA,GAAS,IAAA,CAAK,IAAA,CAAK,CAAA,GAAA,KAAO,IAAI,UAAA,CAAW,YAAY,CAAC,CAAA,EAAG,MAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IAAK,QAAQ,GAAA,CAAI,kBAAA;AAE5F,IAAM,cAAc,IAAA,CAAK,IAAA,CAAK,CAAA,GAAA,KAAO,GAAA,CAAI,WAAW,iBAAiB,CAAC,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IACnF,OAAA,CAAQ,IAAI,YAAA,IACZ,0CAAA;AAEF,IAAM,cAAc,IAAA,CAAK,IAAA,CAAK,CAAA,GAAA,KAAO,GAAA,CAAI,WAAW,iBAAiB,CAAC,CAAA,EAAG,KAAA,CAAM,GAAG,CAAA,CAAE,CAAC,CAAA,IACnF,OAAA,CAAQ,IAAI,yBAAA,IACZ,6NAAA;AAEF,IAAI,CAAC,MAAA,EAAQ;AACX,EAAA,OAAA,CAAQ,MAAM,mGAA8F,CAAA;AAC5G,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB;AAQA,IAAM,QAAA,GAAW,YAAA,CAAa,WAAA,EAAa,WAAW,CAAA;AAStD,eAAe,eAAe,GAAA,EAA0C;AACtE,EAAA,IAAI,CAAC,GAAA,CAAI,UAAA,CAAW,MAAM,CAAA,IAAK,GAAA,CAAI,WAAW,EAAA,EAAI;AAChD,IAAA,OAAA,CAAQ,MAAM,kCAA2B,CAAA;AACzC,IAAA,OAAO,IAAA;AAAA,EACT;AAEA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AAK,CAAA;AACtC,EAAA,OAAA,CAAQ,KAAK,CAAC,CAAA;AAChB,CAAC,CAAA","file":"index.js","sourcesContent":["#!/usr/bin/env node\n\nimport { Server } from '@modelcontextprotocol/sdk/server/index.js';\nimport { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';\nimport { CallToolRequestSchema, ListToolsRequestSchema, ListResourcesRequestSchema, ReadResourceRequestSchema } from '@modelcontextprotocol/sdk/types.js';\nimport { createClient } from '@supabase/supabase-js';\nimport { createHash } from 'crypto';\n\n// Parse command line arguments and environment\nconst args = process.argv.slice(2);\nconst apiKey = args.find(arg => arg.startsWith('--api-key='))?.split('=')[1] || process.env.MG_TICKETS_API_KEY;\n// Default to MG Software's Supabase for SaaS customers\nconst supabaseUrl = args.find(arg => arg.startsWith('--supabase-url='))?.split('=')[1] || \n process.env.SUPABASE_URL || \n 'https://cvjdbczxyczjnatuolsk.supabase.co';\n\nconst supabaseKey = args.find(arg => arg.startsWith('--supabase-key='))?.split('=')[1] || \n process.env.SUPABASE_SERVICE_ROLE_KEY || \n 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImN2amRiY3p4eWN6am5hdHVvbHNrIiwicm9sZSI6InNlcnZpY2Vfcm9sZSIsImlhdCI6MTc1NjE0NzcyNCwiZXhwIjoyMDcxNzIzNzI0fQ.LljuNdCZXDcSIVTeIVOSNsvGNBfWsIM1QIswBJmGXKE';\n\nif (!apiKey) {\n console.error('❌ API key is required. Use --api-key=your_key or set MG_TICKETS_API_KEY environment variable');\n process.exit(1);\n}\n\n// Supabase credentials validation (optional with defaults)\nif (!supabaseUrl || !supabaseKey) {\n console.error('❌ Supabase credentials missing. Using defaults for MG Software SaaS.');\n}\n\n// Initialize Supabase client with service role\nconst supabase = createClient(supabaseUrl, supabaseKey);\n\ninterface AuthContext {\n userId: string;\n teamId: string;\n scopes: string[];\n}\n\n// API Key validation - direct database access\nasync function validateApiKey(key: string): Promise<AuthContext | null> {\n if (!key.startsWith('mid_') || key.length !== 68) {\n console.error('🔑 Invalid API key format');\n return null;\n }\n\n try {\n // Hash the API key\n const keyHash = createHash('sha256').update(key).digest('hex');\n console.error(`🔍 Validating API key hash: ${keyHash.substring(0, 16)}...`);\n \n // Query database for API key\n const { data: apiKeyData, error } = await supabase\n .from('api_keys')\n .select('id, user_id, team_id, scopes, last_used_at')\n .eq('key_hash', keyHash)\n .single();\n\n if (error || !apiKeyData) {\n console.error('❌ API key not found or invalid:', error?.message);\n return null;\n }\n\n // Update last used timestamp\n await supabase\n .from('api_keys')\n .update({ last_used_at: new Date().toISOString() })\n .eq('id', apiKeyData.id);\n\n console.error(`✅ API key validated for user ${apiKeyData.user_id} in team ${apiKeyData.team_id}`);\n \n return {\n userId: apiKeyData.user_id,\n teamId: apiKeyData.team_id,\n scopes: apiKeyData.scopes || []\n };\n } catch (error) {\n console.error('💥 API key validation error:', error);\n return null;\n }\n}\n\n// Validate auth context once at startup\nlet authContext: AuthContext | null = null;\n\n// MCP Server setup\nconst server = new Server(\n {\n name: 'mg-tickets-mcp-bridge',\n version: '1.0.0',\n },\n {\n capabilities: {\n tools: {},\n resources: {},\n },\n }\n);\n\n// Available tools definition\nconst TOOLS = [\n {\n name: 'get-tickets',\n description: 'Get tickets with optional filtering by status, priority, project, customer, or search query',\n inputSchema: {\n type: 'object',\n properties: {\n status: { type: 'string', enum: ['open', 'in_progress', 'review', 'resolved', 'closed', 'backlog'] },\n priority: { type: 'string', enum: ['low', 'medium', 'high', 'critical'] },\n projectId: { type: 'string' },\n customerId: { type: 'string' },\n q: { type: 'string', description: 'Search query for title or description' },\n pageSize: { type: 'number', default: 20, maximum: 100 }\n },\n required: []\n }\n },\n {\n name: 'get-ticket-by-id',\n description: 'Get a specific ticket by its ID',\n inputSchema: {\n type: 'object',\n properties: {\n id: { type: 'string', description: 'Ticket ID' }\n },\n required: ['id']\n }\n },\n {\n name: 'create-ticket',\n description: 'Create a new ticket',\n inputSchema: {\n type: 'object',\n properties: {\n title: { type: 'string', description: 'Ticket title' },\n description: { type: 'string' },\n status: { type: 'string', enum: ['open', 'in_progress', 'review', 'resolved', 'closed', 'backlog'], default: 'open' },\n priority: { type: 'string', enum: ['low', 'medium', 'high', 'critical'], default: 'medium' },\n type: { type: 'string', enum: ['task', 'bug', 'feature', 'support', 'question', 'improvement'], default: 'task' },\n projectId: { type: 'string' },\n customerId: { type: 'string' }\n },\n required: ['title']\n }\n },\n {\n name: 'get-customers',\n description: 'Get customers with optional search',\n inputSchema: {\n type: 'object',\n properties: {\n q: { type: 'string', description: 'Search query for customer name or email' },\n pageSize: { type: 'number', default: 20, maximum: 100 }\n },\n required: []\n }\n },\n {\n name: 'create-customer',\n description: 'Create a new customer',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Customer name' },\n email: { type: 'string' },\n website: { type: 'string' }\n },\n required: ['name']\n }\n },\n {\n name: 'get-projects',\n description: 'Get projects with optional filtering',\n inputSchema: {\n type: 'object',\n properties: {\n customerId: { type: 'string', description: 'Filter by customer ID' },\n q: { type: 'string', description: 'Search query for project name' },\n pageSize: { type: 'number', default: 20, maximum: 100 }\n },\n required: []\n }\n },\n {\n name: 'create-project',\n description: 'Create a new project',\n inputSchema: {\n type: 'object',\n properties: {\n name: { type: 'string', description: 'Project name' },\n description: { type: 'string' },\n customerId: { type: 'string' },\n status: { type: 'string', enum: ['active', 'on_hold', 'completed', 'cancelled'], default: 'active' }\n },\n required: ['name']\n }\n },\n // === NEW AI SESSION TOOLS ===\n {\n name: 'start-ai-session-smart',\n description: 'Start a new AI development session with automatic time estimation',\n inputSchema: {\n type: 'object',\n properties: {\n ticketId: { type: 'string' },\n ticketUrl: { type: 'string', description: 'URL to the ticket' },\n cursorSessionId: { type: 'string', description: 'Cursor session identifier' },\n codebaseContext: { \n type: 'array', \n items: { type: 'string' },\n description: 'Relevant files for complexity analysis'\n },\n aiTimeEstimateMinutes: { \n type: 'number', \n description: 'AI estimate in minutes without AI assistance' \n },\n complexityScore: {\n type: 'number',\n minimum: 1,\n maximum: 10,\n description: 'Estimated complexity from 1-10'\n }\n },\n required: ['ticketId', 'aiTimeEstimateMinutes']\n }\n },\n {\n name: 'track-manual-follow-up',\n description: 'Track manual follow-up prompt by developer',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n originalPrompt: { type: 'string' },\n aiResponse: { type: 'string' },\n developerFollowUp: { type: 'string' },\n followUpReason: { \n type: 'string', \n enum: ['incomplete_result', 'wrong_approach', 'needs_clarification', 'error_in_code']\n },\n outcome: {\n type: 'string',\n enum: ['success', 'partial_success', 'still_failed'],\n default: 'success'\n },\n timeSpentMinutes: { type: 'number' }\n },\n required: ['aiSessionId', 'originalPrompt', 'aiResponse', 'developerFollowUp', 'followUpReason']\n }\n },\n {\n name: 'get-session-context',\n description: 'Get current session context for follow-up continuity',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n includeTicketData: { type: 'boolean', default: true },\n includeTodoProgress: { type: 'boolean', default: true },\n includeFollowUpHistory: { type: 'boolean', default: false }\n },\n required: ['aiSessionId']\n }\n },\n {\n name: 'sync-session-todos',\n description: 'Synchronize todo list with AI session (replace existing) or add new todos',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n todos: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n todoId: { type: 'string', description: 'Optional external todo ID for tracking' },\n content: { type: 'string' },\n status: { type: 'string', enum: ['pending', 'in_progress', 'completed', 'cancelled'] },\n estimatedMinutes: { type: 'number' }\n },\n required: ['content', 'status']\n }\n },\n replaceAll: { \n type: 'boolean', \n default: true, \n description: 'If true, replace all existing todos. If false, add new todos to existing ones' \n }\n },\n required: ['aiSessionId', 'todos']\n }\n },\n {\n name: 'add-follow-up-todos',\n description: 'Add new todos from follow-up (without replacing existing ones)',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n newTodos: {\n type: 'array',\n items: {\n type: 'object',\n properties: {\n content: { type: 'string' },\n status: { type: 'string', enum: ['pending', 'in_progress'], default: 'pending' },\n estimatedMinutes: { type: 'number' },\n addedInFollowUp: { type: 'boolean', default: true }\n },\n required: ['content']\n }\n },\n followUpReason: { \n type: 'string', \n description: 'Why were these todos added in follow-up' \n }\n },\n required: ['aiSessionId', 'newTodos']\n }\n },\n {\n name: 'log-activity-time',\n description: 'Log time spent per activity type',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n activityType: { \n type: 'string', \n enum: ['thinking', 'coding', 'debugging', 'testing', 'documenting'] \n },\n durationSeconds: { type: 'number' },\n description: { type: 'string' },\n productivityScore: { type: 'number', minimum: 1, maximum: 10 }\n },\n required: ['aiSessionId', 'activityType', 'durationSeconds']\n }\n },\n {\n name: 'update-session-status',\n description: 'Update AI session status and completion info',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n status: {\n type: 'string',\n enum: ['started', 'in_progress', 'paused', 'completed', 'failed']\n },\n actualTimeMinutes: { type: 'number' },\n completionNotes: { type: 'string' }\n },\n required: ['aiSessionId', 'status']\n }\n }\n];\n\n// Available resources\nconst RESOURCES = [\n {\n uri: 'tickets://recent',\n name: 'Recent Tickets',\n description: 'Most recently created tickets',\n mimeType: 'application/json'\n },\n {\n uri: 'customers://all',\n name: 'All Customers', \n description: 'Complete customer directory',\n mimeType: 'application/json'\n },\n {\n uri: 'projects://active',\n name: 'Active Projects',\n description: 'Currently active projects',\n mimeType: 'application/json'\n }\n];\n\n// List tools handler\nserver.setRequestHandler(ListToolsRequestSchema, async () => {\n return { tools: TOOLS };\n});\n\n// List resources handler\nserver.setRequestHandler(ListResourcesRequestSchema, async () => {\n return { resources: RESOURCES };\n});\n\n// Tool execution handler\nserver.setRequestHandler(CallToolRequestSchema, async (request) => {\n if (!authContext) {\n return {\n content: [{ type: 'text', text: 'Error: Not authenticated. API key validation failed.' }],\n };\n }\n\n const { name, arguments: args } = request.params;\n console.error(`🛠️ Executing tool: ${name} for team ${authContext.teamId}`);\n \n try {\n switch (name) {\n case 'get-tickets': {\n const { status, priority, projectId, customerId, q, pageSize = 20 } = args as any;\n \n let query = supabase\n .from('tickets')\n .select(`\n id,\n ticket_number,\n title,\n description,\n status,\n priority,\n type,\n created_at,\n project_id,\n customer_id,\n projects:project_id(id, name),\n customers:customer_id(id, name)\n `)\n .eq('team_id', authContext.teamId)\n .limit(Math.min(pageSize, 100));\n \n if (status) query = query.eq('status', status);\n if (priority) query = query.eq('priority', priority);\n if (projectId) query = query.eq('project_id', projectId);\n if (customerId) query = query.eq('customer_id', customerId);\n if (q) query = query.or(`title.ilike.%${q}%,description.ilike.%${q}%`);\n \n const { data, error } = await query.order('created_at', { ascending: false });\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `Found ${data?.length || 0} tickets:\\n\\n${data?.map(ticket => \n `**${ticket.ticket_number}**: ${ticket.title}\\n` +\n `Status: ${ticket.status} | Priority: ${ticket.priority}\\n` +\n `${(ticket.projects as any)?.name ? `Project: ${(ticket.projects as any).name}\\n` : ''}` +\n `${(ticket.customers as any)?.name ? `Customer: ${(ticket.customers as any).name}\\n` : ''}` +\n `Created: ${new Date(ticket.created_at).toLocaleDateString()}\\n`\n ).join('\\n') || 'No tickets found.'}`\n }]\n };\n }\n \n case 'get-ticket-by-id': {\n const { id } = args as any;\n \n const { data, error } = await supabase\n .from('tickets')\n .select(`\n *,\n projects:project_id(id, name),\n customers:customer_id(id, name),\n assignee:assignee_id(id, full_name, email),\n requester:requester_id(id, full_name, email)\n `)\n .eq('id', id)\n .eq('team_id', authContext.teamId)\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `**Ticket Details:**\\n\\n` +\n `**${data.ticket_number}**: ${data.title}\\n` +\n `Status: ${data.status}\\n` +\n `Priority: ${data.priority}\\n` +\n `Type: ${data.type}\\n` +\n `${data.description ? `Description: ${data.description}\\n` : ''}` +\n `${(data.projects as any)?.name ? `Project: ${(data.projects as any).name}\\n` : ''}` +\n `${(data.customers as any)?.name ? `Customer: ${(data.customers as any).name}\\n` : ''}` +\n `${data.assignee?.full_name ? `Assignee: ${data.assignee.full_name}\\n` : ''}` +\n `Requester: ${data.requester?.full_name || 'Unknown'}\\n` +\n `Created: ${new Date(data.created_at).toLocaleDateString()}\\n`\n }]\n };\n }\n \n case 'create-ticket': {\n const { title, description, status = 'open', priority = 'medium', type = 'task', projectId, customerId } = args as any;\n \n // Generate ticket number\n const year = new Date().getFullYear();\n const { count } = await supabase\n .from('tickets')\n .select('*', { count: 'exact', head: true })\n .eq('team_id', authContext.teamId);\n \n const ticketNumber = `${year}-${String((count || 0) + 1).padStart(3, '0')}`;\n \n const { data, error } = await supabase\n .from('tickets')\n .insert({\n team_id: authContext.teamId,\n ticket_number: ticketNumber,\n title,\n description,\n status,\n priority,\n type,\n project_id: projectId || null,\n customer_id: customerId || null,\n requester_id: authContext.userId\n })\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Ticket Created Successfully!**\\n\\n` +\n `Ticket Number: **${ticketNumber}**\\n` +\n `Title: ${title}\\n` +\n `Status: ${status}\\n` +\n `Priority: ${priority}\\n` +\n `Type: ${type}\\n`\n }]\n };\n }\n \n case 'get-customers': {\n const { q, pageSize = 20 } = args as any;\n \n let query = supabase\n .from('customers')\n .select('id, name, email, website, created_at')\n .eq('team_id', authContext.teamId)\n .limit(Math.min(pageSize, 100));\n \n if (q) query = query.or(`name.ilike.%${q}%,email.ilike.%${q}%`);\n \n const { data, error } = await query.order('name');\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `Found ${data?.length || 0} customers:\\n\\n${data?.map(customer => \n `**${customer.name}**\\n` +\n `${customer.email ? `Email: ${customer.email}\\n` : ''}` +\n `${customer.website ? `Website: ${customer.website}\\n` : ''}` +\n `Created: ${new Date(customer.created_at).toLocaleDateString()}\\n`\n ).join('\\n') || 'No customers found.'}`\n }]\n };\n }\n \n case 'create-customer': {\n const { name, email, website } = args as any;\n \n const { data, error } = await supabase\n .from('customers')\n .insert({\n team_id: authContext.teamId,\n name,\n email: email || null,\n website: website || null,\n user_id: authContext.userId\n })\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Customer Created Successfully!**\\n\\n` +\n `Name: ${name}\\n` +\n `${email ? `Email: ${email}\\n` : ''}` +\n `${website ? `Website: ${website}\\n` : ''}`\n }]\n };\n }\n \n case 'get-projects': {\n const { customerId, q, pageSize = 20 } = args as any;\n \n let query = supabase\n .from('projects')\n .select(`\n id,\n name,\n description,\n customer_id,\n status,\n created_at,\n customers:customer_id(id, name)\n `)\n .eq('team_id', authContext.teamId)\n .limit(Math.min(pageSize, 100));\n \n if (customerId) query = query.eq('customer_id', customerId);\n if (q) query = query.ilike('name', `%${q}%`);\n \n const { data, error } = await query.order('name');\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `Found ${data?.length || 0} projects:\\n\\n${data?.map(project => \n `**${project.name}**\\n` +\n `Status: ${project.status}\\n` +\n `${project.description ? `Description: ${project.description}\\n` : ''}` +\n `${(project.customers as any)?.name ? `Customer: ${(project.customers as any).name}\\n` : ''}` +\n `Created: ${new Date(project.created_at).toLocaleDateString()}\\n`\n ).join('\\n') || 'No projects found.'}`\n }]\n };\n }\n \n case 'create-project': {\n const { name, description, customerId, status = 'active' } = args as any;\n \n const { data, error } = await supabase\n .from('projects')\n .insert({\n team_id: authContext.teamId,\n name,\n description: description || null,\n customer_id: customerId || null,\n status,\n user_id: authContext.userId\n })\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Project Created Successfully!**\\n\\n` +\n `Name: ${name}\\n` +\n `Status: ${status}\\n` +\n `${description ? `Description: ${description}\\n` : ''}`\n }]\n };\n }\n \n // === AI SESSION TOOLS ===\n case 'start-ai-session-smart': {\n const { ticketId, ticketUrl, cursorSessionId, codebaseContext, aiTimeEstimateMinutes, complexityScore } = args as any;\n \n // Generate session ID\n const { data: sessionData, error } = await supabase\n .from('ai_sessions')\n .insert({\n ticket_id: ticketId,\n provider_user_id: authContext.userId,\n team_id: authContext.teamId,\n cursor_session_id: cursorSessionId || null,\n ai_time_estimate_minutes: aiTimeEstimateMinutes,\n complexity_score: complexityScore || null,\n status: 'started'\n })\n .select('id, ticket_id, cursor_session_id, created_at')\n .single();\n \n if (error) throw error;\n \n // Generate a readable session ID for UI\n const sessionId = `ai-sess-${sessionData.id.substring(0, 8)}`;\n \n return {\n content: [{\n type: 'text',\n text: `🚀 **AI Session Started Successfully!**\\n\\n` +\n `Session ID: **${sessionId}**\\n` +\n `Ticket: ${ticketId}\\n` +\n `Time Estimate: ${aiTimeEstimateMinutes} minutes\\n` +\n `${complexityScore ? `Complexity: ${complexityScore}/10\\n` : ''}` +\n `${cursorSessionId ? `Cursor Session: ${cursorSessionId}\\n` : ''}` +\n `Created: ${new Date().toLocaleString()}\\n\\n` +\n `✅ Ready for development and follow-up tracking!`\n }]\n };\n }\n \n case 'track-manual-follow-up': {\n const { aiSessionId, originalPrompt, aiResponse, developerFollowUp, followUpReason, outcome = 'success', timeSpentMinutes } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Find the full session ID\n const { data: session, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .eq('team_id', authContext.teamId)\n .ilike('id', `${sessionUuid}%`)\n .single();\n \n if (sessionError || !session) {\n throw new Error(`Session not found: ${aiSessionId}`);\n }\n \n const { data, error } = await supabase\n .from('manual_follow_ups')\n .insert({\n ai_session_id: session.id,\n developer_id: authContext.userId,\n team_id: authContext.teamId,\n original_prompt: originalPrompt,\n ai_response: aiResponse,\n follow_up_prompt: developerFollowUp,\n follow_up_reason: followUpReason,\n outcome: outcome,\n time_spent_minutes: timeSpentMinutes || null,\n resolved_at: outcome === 'success' ? new Date().toISOString() : null\n })\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Follow-up Tracked Successfully!**\\n\\n` +\n `Session: ${aiSessionId}\\n` +\n `Reason: ${followUpReason.replace('_', ' ')}\\n` +\n `Outcome: ${outcome}\\n` +\n `${timeSpentMinutes ? `Time spent: ${timeSpentMinutes} minutes\\n` : ''}` +\n `\\n📊 This data will improve future AI interactions!`\n }]\n };\n }\n \n case 'get-session-context': {\n const { aiSessionId, includeTicketData = true, includeTodoProgress = true, includeFollowUpHistory = false } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Get session data with related info\n let query = supabase\n .from('ai_sessions')\n .select(`\n id,\n ticket_id,\n status,\n ai_time_estimate_minutes,\n actual_time_minutes,\n complexity_score,\n created_at,\n cursor_session_id\n `)\n .eq('team_id', authContext.teamId)\n .ilike('id', `${sessionUuid}%`)\n .single();\n \n const { data: session, error: sessionError } = await query;\n \n if (sessionError || !session) {\n throw new Error(`Session not found: ${aiSessionId}`);\n }\n \n let context: any = {\n sessionId: aiSessionId,\n status: session.status,\n timeEstimate: session.ai_time_estimate_minutes,\n actualTime: session.actual_time_minutes,\n complexity: session.complexity_score,\n createdAt: session.created_at\n };\n \n // Include ticket data if requested\n if (includeTicketData) {\n const { data: ticket } = await supabase\n .from('tickets')\n .select('id, ticket_number, title, description, status, priority, type')\n .eq('id', session.ticket_id)\n .single();\n \n context.ticketData = ticket;\n }\n \n // Include todo progress if requested\n if (includeTodoProgress) {\n const { data: todos } = await supabase\n .from('ai_todos')\n .select('id, content, status, estimated_minutes, actual_minutes')\n .eq('ai_session_id', session.id)\n .order('sequence_order');\n \n context.todos = todos || [];\n context.todoProgress = {\n total: todos?.length || 0,\n completed: todos?.filter(t => t.status === 'completed').length || 0,\n inProgress: todos?.filter(t => t.status === 'in_progress').length || 0\n };\n }\n \n // Include follow-up history if requested\n if (includeFollowUpHistory) {\n const { data: followUps } = await supabase\n .from('manual_follow_ups')\n .select('follow_up_reason, outcome, time_spent_minutes, created_at')\n .eq('ai_session_id', session.id)\n .order('created_at');\n \n context.followUpHistory = followUps || [];\n }\n \n return {\n content: [{\n type: 'text',\n text: `🎯 **Session Context Retrieved**\\n\\n` +\n `Session: ${aiSessionId}\\n` +\n `Status: ${session.status}\\n` +\n `${context.ticketData ? `Ticket: ${context.ticketData.ticket_number} - ${context.ticketData.title}\\n` : ''}` +\n `${context.todoProgress ? `Todo Progress: ${context.todoProgress.completed}/${context.todoProgress.total} completed\\n` : ''}` +\n `${context.followUpHistory ? `Follow-ups: ${context.followUpHistory.length}\\n` : ''}` +\n `\\n📋 Full context preserved for seamless continuation!`\n }]\n };\n }\n \n case 'sync-session-todos': {\n const { aiSessionId, todos, replaceAll = true } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Find the session\n const { data: session, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .eq('team_id', authContext.teamId)\n .ilike('id', `${sessionUuid}%`)\n .single();\n \n if (sessionError || !session) {\n throw new Error(`Session not found: ${aiSessionId}`);\n }\n \n // If replacing all, clear existing todos first\n if (replaceAll) {\n await supabase\n .from('ai_todos')\n .delete()\n .eq('ai_session_id', session.id);\n }\n \n if (todos && todos.length > 0) {\n // Get current max sequence order if adding to existing\n let startSequence = 0;\n if (!replaceAll) {\n const { data: maxTodo } = await supabase\n .from('ai_todos')\n .select('sequence_order')\n .eq('ai_session_id', session.id)\n .order('sequence_order', { ascending: false })\n .limit(1)\n .single();\n startSequence = (maxTodo?.sequence_order || 0) + 1;\n }\n \n const todoInserts = todos.map((todo: any, index: number) => ({\n ai_session_id: session.id,\n content: todo.content,\n status: todo.status,\n cursor_todo_id: todo.todoId || null,\n estimated_minutes: todo.estimatedMinutes || null,\n sequence_order: startSequence + index\n }));\n \n const { error: insertError } = await supabase\n .from('ai_todos')\n .insert(todoInserts);\n \n if (insertError) throw insertError;\n }\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Todos ${replaceAll ? 'Synced' : 'Added'} Successfully!**\\n\\n` +\n `Session: ${aiSessionId}\\n` +\n `${replaceAll ? 'Synced' : 'Added'} ${todos?.length || 0} todos\\n` +\n `${replaceAll ? '' : '➕ Added to existing todo list\\n'}` +\n `\\n📝 Todo list updated and tracked for progress monitoring!`\n }]\n };\n }\n \n case 'add-follow-up-todos': {\n const { aiSessionId, newTodos, followUpReason } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Find the session\n const { data: session, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .eq('team_id', authContext.teamId)\n .ilike('id', `${sessionUuid}%`)\n .single();\n \n if (sessionError || !session) {\n throw new Error(`Session not found: ${aiSessionId}`);\n }\n \n if (newTodos && newTodos.length > 0) {\n // Get current max sequence order\n const { data: maxTodo } = await supabase\n .from('ai_todos')\n .select('sequence_order')\n .eq('ai_session_id', session.id)\n .order('sequence_order', { ascending: false })\n .limit(1)\n .single();\n const startSequence = (maxTodo?.sequence_order || 0) + 1;\n \n const todoInserts = newTodos.map((todo: any, index: number) => ({\n ai_session_id: session.id,\n content: `[Follow-up] ${todo.content}`,\n status: todo.status || 'pending',\n estimated_minutes: todo.estimatedMinutes || null,\n sequence_order: startSequence + index\n }));\n \n const { error: insertError } = await supabase\n .from('ai_todos')\n .insert(todoInserts);\n \n if (insertError) throw insertError;\n }\n \n return {\n content: [{\n type: 'text',\n text: `✅ **Follow-up Todos Added Successfully!**\\n\\n` +\n `Session: ${aiSessionId}\\n` +\n `Added ${newTodos?.length || 0} new todos from follow-up\\n` +\n `${followUpReason ? `Reason: ${followUpReason}\\n` : ''}` +\n `\\n📝 New tasks identified and added to existing workflow!`\n }]\n };\n }\n \n case 'log-activity-time': {\n const { aiSessionId, activityType, durationSeconds, description, productivityScore } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Find the session\n const { data: session, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .eq('team_id', authContext.teamId)\n .ilike('id', `${sessionUuid}%`)\n .single();\n \n if (sessionError || !session) {\n throw new Error(`Session not found: ${aiSessionId}`);\n }\n \n const { data, error } = await supabase\n .from('ai_time_logs')\n .insert({\n ai_session_id: session.id,\n activity_type: activityType,\n duration_seconds: durationSeconds,\n description: description || null,\n productivity_score: productivityScore || null,\n ended_at: new Date().toISOString()\n })\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `⏱️ **Activity Time Logged!**\\n\\n` +\n `Session: ${aiSessionId}\\n` +\n `Activity: ${activityType}\\n` +\n `Duration: ${Math.round(durationSeconds / 60)} minutes\\n` +\n `${productivityScore ? `Productivity: ${productivityScore}/10\\n` : ''}` +\n `\\n📊 Time tracking data saved for analysis!`\n }]\n };\n }\n \n case 'update-session-status': {\n const { aiSessionId, status, actualTimeMinutes, completionNotes } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Find and update the session\n const { data, error } = await supabase\n .from('ai_sessions')\n .update({\n status: status,\n actual_time_minutes: actualTimeMinutes || null,\n completed_at: status === 'completed' ? new Date().toISOString() : null\n })\n .eq('team_id', authContext.teamId)\n .ilike('id', `${sessionUuid}%`)\n .select()\n .single();\n \n if (error) throw error;\n \n return {\n content: [{\n type: 'text',\n text: `🎯 **Session Status Updated!**\\n\\n` +\n `Session: ${aiSessionId}\\n` +\n `Status: ${status}\\n` +\n `${actualTimeMinutes ? `Actual Time: ${actualTimeMinutes} minutes\\n` : ''}` +\n `${status === 'completed' ? `✅ Session completed successfully!\\n` : ''}` +\n `${completionNotes ? `Notes: ${completionNotes}\\n` : ''}`\n }]\n };\n }\n \n default:\n throw new Error(`Unknown tool: ${name}`);\n }\n \n } catch (error) {\n console.error(`❌ Tool execution error:`, error);\n return {\n content: [{\n type: 'text',\n text: `Error executing ${name}: ${error instanceof Error ? error.message : 'Unknown error'}`\n }]\n };\n }\n});\n\n// Resource read handler\nserver.setRequestHandler(ReadResourceRequestSchema, async (request) => {\n if (!authContext) {\n return {\n contents: [{\n uri: request.params.uri,\n mimeType: 'text/plain',\n text: 'Error: Not authenticated. API key validation failed.'\n }]\n };\n }\n\n const { uri } = request.params;\n console.error(`📚 Reading resource: ${uri}`);\n \n try {\n switch (uri) {\n case 'tickets://recent': {\n const { data, error } = await supabase\n .from('tickets')\n .select(`\n id,\n ticket_number,\n title,\n status,\n priority,\n created_at\n `)\n .eq('team_id', authContext.teamId)\n .order('created_at', { ascending: false })\n .limit(20);\n \n if (error) throw error;\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(data, null, 2)\n }]\n };\n }\n \n case 'customers://all': {\n const { data, error } = await supabase\n .from('customers')\n .select('id, name, email, website, created_at')\n .eq('team_id', authContext.teamId)\n .order('name')\n .limit(50);\n \n if (error) throw error;\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(data, null, 2)\n }]\n };\n }\n \n case 'projects://active': {\n const { data, error } = await supabase\n .from('projects')\n .select(`\n id,\n name,\n description,\n status,\n created_at,\n customers:customer_id(id, name)\n `)\n .eq('team_id', authContext.teamId)\n .eq('status', 'active')\n .order('name')\n .limit(50);\n \n if (error) throw error;\n \n return {\n contents: [{\n uri,\n mimeType: 'application/json',\n text: JSON.stringify(data, null, 2)\n }]\n };\n }\n \n default:\n throw new Error(`Unknown resource: ${uri}`);\n }\n \n } catch (error) {\n console.error(`❌ Resource read error:`, error);\n return {\n contents: [{\n uri,\n mimeType: 'text/plain',\n text: `Error reading ${uri}: ${error instanceof Error ? error.message : 'Unknown error'}`\n }]\n };\n }\n});\n\n// Main function\nasync function main() {\n console.error('🚀 Starting MG Tickets MCP Bridge Server...');\n console.error(`🔑 API Key: ${apiKey?.substring(0, 10)}...`);\n \n // Validate API key\n authContext = await validateApiKey(apiKey!);\n if (!authContext) {\n console.error('❌ API key validation failed. Please check your key and try again.');\n process.exit(1);\n }\n \n console.error(`✅ Authenticated as user ${authContext.userId} in team ${authContext.teamId}`);\n console.error(`📋 Available scopes: ${authContext.scopes.join(', ')}`);\n console.error('📡 MCP Bridge Server ready for connections');\n \n const transport = new StdioServerTransport();\n await server.connect(transport);\n}\n\n// Handle graceful shutdown\nprocess.on('SIGINT', async () => {\n console.error('👋 Shutting down MCP Bridge Server...');\n process.exit(0);\n});\n\nprocess.on('SIGTERM', async () => {\n console.error('👋 Shutting down MCP Bridge Server...');\n process.exit(0);\n});\n\n// Start the server\nmain().catch((error) => {\n console.error('💥 Fatal error:', error);\n process.exit(1);\n});"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mgsoftwarebv/mcp-server-bridge",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "MCP Server bridge for MG Tickets - connects Cursor to HTTP MCP server",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",