@mgsoftwarebv/mcp-server-bridge 2.18.0 → 2.18.2

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
@@ -15,6 +15,10 @@ if (!apiKey) {
15
15
  process.exit(1);
16
16
  }
17
17
  var supabase = createClient(supabaseUrl, supabaseKey);
18
+ function roundToNearest15Minutes(minutes) {
19
+ if (minutes <= 0) return 0;
20
+ return Math.round(minutes / 15) * 15;
21
+ }
18
22
  async function getAccessibleTeamIds(teamId) {
19
23
  const { data: accessibleTeams } = await supabase.from("teams").select("id").or(`id.eq.${teamId},parent_team_id.eq.${teamId}`);
20
24
  return accessibleTeams?.map((t) => t.id) || [teamId];
@@ -328,9 +332,13 @@ var TOOLS = [
328
332
  estimatedMinutes: {
329
333
  type: "number",
330
334
  description: "Estimated time needed for this follow-up work (think as senior dev WITHOUT AI, in minutes)"
335
+ },
336
+ workDescription: {
337
+ type: "string",
338
+ description: "Detailed work description generated by AI (2-3 sentences, summarizing all work done in session including follow-ups)"
331
339
  }
332
340
  },
333
- required: ["aiSessionId", "originalPrompt", "aiResponse", "developerFollowUp", "followUpReason", "estimatedMinutes"]
341
+ required: ["aiSessionId", "originalPrompt", "aiResponse", "developerFollowUp", "followUpReason", "estimatedMinutes", "workDescription"]
334
342
  }
335
343
  },
336
344
  {
@@ -888,7 +896,13 @@ ${description ? `Description: ${description}
888
896
  if (!timeBreakdown || !timeBreakdown.analysisMinutes || timeBreakdown.developmentMinutes === void 0) {
889
897
  throw new Error("timeBreakdown is required with all phases: analysisMinutes, investigationMinutes, developmentMinutes, communicationMinutes");
890
898
  }
891
- const totalEstimateMinutes = (timeBreakdown.analysisMinutes || 0) + (timeBreakdown.investigationMinutes || 0) + (timeBreakdown.developmentMinutes || 0) + (timeBreakdown.communicationMinutes || 0);
899
+ const roundedTimeBreakdown = {
900
+ analysisMinutes: roundToNearest15Minutes(timeBreakdown.analysisMinutes || 0),
901
+ investigationMinutes: roundToNearest15Minutes(timeBreakdown.investigationMinutes || 0),
902
+ developmentMinutes: roundToNearest15Minutes(timeBreakdown.developmentMinutes || 0),
903
+ communicationMinutes: roundToNearest15Minutes(timeBreakdown.communicationMinutes || 0)
904
+ };
905
+ const totalEstimateMinutes = roundedTimeBreakdown.analysisMinutes + roundedTimeBreakdown.investigationMinutes + roundedTimeBreakdown.developmentMinutes + roundedTimeBreakdown.communicationMinutes;
892
906
  const sessionStartTime = /* @__PURE__ */ new Date();
893
907
  const { data: sessionData, error } = await supabase.from("ai_sessions").insert({
894
908
  ticket_id: ticketId,
@@ -906,7 +920,7 @@ ${description ? `Description: ${description}
906
920
  activity_type: "analysis",
907
921
  description: "Ticket analysis and context understanding",
908
922
  duration_seconds: 0,
909
- estimated_duration_seconds: timeBreakdown.analysisMinutes * 60,
923
+ estimated_duration_seconds: roundedTimeBreakdown.analysisMinutes * 60,
910
924
  status: "in_progress",
911
925
  // Analysis starts immediately
912
926
  productivity_score: 8,
@@ -917,7 +931,7 @@ ${description ? `Description: ${description}
917
931
  activity_type: "bug_investigation",
918
932
  description: "Bug investigation and root cause analysis",
919
933
  duration_seconds: 0,
920
- estimated_duration_seconds: timeBreakdown.investigationMinutes * 60,
934
+ estimated_duration_seconds: roundedTimeBreakdown.investigationMinutes * 60,
921
935
  status: "pending",
922
936
  productivity_score: null
923
937
  },
@@ -926,7 +940,7 @@ ${description ? `Description: ${description}
926
940
  activity_type: "development",
927
941
  description: "Implementation and coding",
928
942
  duration_seconds: 0,
929
- estimated_duration_seconds: timeBreakdown.developmentMinutes * 60,
943
+ estimated_duration_seconds: roundedTimeBreakdown.developmentMinutes * 60,
930
944
  status: "pending",
931
945
  productivity_score: null
932
946
  },
@@ -935,7 +949,7 @@ ${description ? `Description: ${description}
935
949
  activity_type: "communication",
936
950
  description: "Customer response and documentation",
937
951
  duration_seconds: 0,
938
- estimated_duration_seconds: timeBreakdown.communicationMinutes * 60,
952
+ estimated_duration_seconds: roundedTimeBreakdown.communicationMinutes * 60,
939
953
  status: "pending",
940
954
  productivity_score: null
941
955
  }
@@ -951,10 +965,10 @@ ${description ? `Description: ${description}
951
965
  \u{1F3AB} Ticket: ${ticketId}
952
966
 
953
967
  \u{1F4CA} **Time Breakdown:**
954
- \u2022 Analysis: ${timeBreakdown.analysisMinutes} min
955
- \u2022 Investigation: ${timeBreakdown.investigationMinutes} min
956
- \u2022 Development: ${timeBreakdown.developmentMinutes} min
957
- \u2022 Communication: ${timeBreakdown.communicationMinutes} min
968
+ \u2022 Analysis: ${roundedTimeBreakdown.analysisMinutes} min
969
+ \u2022 Investigation: ${roundedTimeBreakdown.investigationMinutes} min
970
+ \u2022 Development: ${roundedTimeBreakdown.developmentMinutes} min
971
+ \u2022 Communication: ${roundedTimeBreakdown.communicationMinutes} min
958
972
  \u2022 **Total: ${totalEstimateMinutes} min**
959
973
 
960
974
  ${complexityScore ? `\u{1F3AF} Complexity: ${complexityScore}/10
@@ -968,7 +982,7 @@ ${cursorSessionId ? `\u{1F517} Cursor Session: ${cursorSessionId}
968
982
  };
969
983
  }
970
984
  case "track-manual-follow-up": {
971
- const { aiSessionId, originalPrompt, aiResponse, developerFollowUp, followUpReason, outcome = "success", estimatedMinutes } = args2;
985
+ const { aiSessionId, originalPrompt, aiResponse, developerFollowUp, followUpReason, outcome = "success", estimatedMinutes, workDescription } = args2;
972
986
  const sessionUuid = aiSessionId.replace("ai-sess-", "");
973
987
  const teamIds = await getAccessibleTeamIds(authContext.teamId);
974
988
  const { data: allSessions, error: sessionError } = await supabase.from("ai_sessions").select("id, status, created_at, ai_time_estimate_minutes").in("team_id", teamIds);
@@ -981,7 +995,8 @@ ${cursorSessionId ? `\u{1F517} Cursor Session: ${cursorSessionId}
981
995
  }
982
996
  const followUpTime = /* @__PURE__ */ new Date();
983
997
  const oldEstimate = session.ai_time_estimate_minutes || 60;
984
- const newEstimate = oldEstimate + (estimatedMinutes || 0);
998
+ const roundedFollowUpMinutes = roundToNearest15Minutes(estimatedMinutes || 0);
999
+ const newEstimate = oldEstimate + roundedFollowUpMinutes;
985
1000
  await supabase.from("ai_sessions").update({
986
1001
  status: "in_progress",
987
1002
  // Restart active tracking
@@ -1020,6 +1035,43 @@ ${cursorSessionId ? `\u{1F517} Cursor Session: ${cursorSessionId}
1020
1035
  efficiency_score: currentEfficiency.toFixed(2),
1021
1036
  actual_time_minutes: totalMinutesElapsed
1022
1037
  }).eq("id", session.id);
1038
+ const { data: existingEntry, error: entryError } = await supabase.from("agenda_events").select("id, tracked_duration, title, description, start_time").eq("ai_session_id", session.id).eq("status", "draft").single();
1039
+ let trackerAction = "";
1040
+ let trackerDetails = "";
1041
+ if (existingEntry && !entryError) {
1042
+ const newDuration = (existingEntry.tracked_duration || 0) + roundedFollowUpMinutes * 60;
1043
+ await supabase.from("agenda_events").update({
1044
+ tracked_duration: newDuration,
1045
+ end_time: followUpTime.toISOString(),
1046
+ title: workDescription,
1047
+ description: workDescription
1048
+ }).eq("id", existingEntry.id);
1049
+ trackerAction = "Updated existing tracker";
1050
+ trackerDetails = ` \u2022 Total tracked time: ${Math.round(newDuration / 60)} minutes (+${roundedFollowUpMinutes} min)
1051
+ \u2022 Description: ${workDescription}
1052
+ `;
1053
+ } else {
1054
+ const durationSeconds = roundedFollowUpMinutes * 60;
1055
+ const startTime = new Date(followUpTime.getTime() - durationSeconds * 1e3);
1056
+ await supabase.from("agenda_events").insert({
1057
+ team_id: authContext.teamId,
1058
+ user_id: authContext.userId,
1059
+ ai_session_id: session.id,
1060
+ title: workDescription,
1061
+ description: workDescription,
1062
+ start_time: startTime.toISOString(),
1063
+ end_time: followUpTime.toISOString(),
1064
+ type: "work",
1065
+ status: "draft",
1066
+ all_day: false,
1067
+ is_tracked: true,
1068
+ tracked_duration: durationSeconds
1069
+ });
1070
+ trackerAction = "Created new tracker";
1071
+ trackerDetails = ` \u2022 Tracked time: ${roundedFollowUpMinutes} minutes
1072
+ \u2022 Description: ${workDescription}
1073
+ `;
1074
+ }
1023
1075
  return {
1024
1076
  content: [{
1025
1077
  type: "text",
@@ -1031,13 +1083,15 @@ ${cursorSessionId ? `\u{1F517} Cursor Session: ${cursorSessionId}
1031
1083
 
1032
1084
  \u{1F4CA} **Time Estimate Updated:**
1033
1085
  \u2022 Old estimate: ${oldEstimate} minutes
1034
- \u2022 Follow-up estimate: +${estimatedMinutes || 0} minutes
1086
+ \u2022 Follow-up estimate: +${roundedFollowUpMinutes} minutes (rounded to 15min)
1035
1087
  \u2022 New estimate: ${newEstimate} minutes
1036
1088
 
1037
1089
  \u{1F4C8} **Current Progress:**
1038
1090
  \u2022 Total time elapsed: ${totalMinutesElapsed} minutes
1039
1091
  \u2022 Efficiency: ${currentEfficiency < 1 ? "\u{1F680} " : currentEfficiency > 1.5 ? "\u26A0\uFE0F " : "\u23F1\uFE0F "}${(currentEfficiency * 100).toFixed(0)}%
1040
1092
 
1093
+ \u23F1\uFE0F **Tracker Entry: ${trackerAction}**
1094
+ ` + trackerDetails + `
1041
1095
  \u26A1 **Time tracking resumed** - continue with confidence!`
1042
1096
  }]
1043
1097
  };
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"names":["args","name"],"mappings":";;;;;;;;AAUA,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,I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,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';\nimport { Octokit } from '@octokit/rest';\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// Smart time estimation and codebase analysis is now handled by Cursor AI\n// MCP bridge focuses on data storage and session management only\n\n// Helper function to get accessible team IDs (own team + child teams)\nasync function getAccessibleTeamIds(teamId: string): Promise<string[]> {\n const { data: accessibleTeams } = await supabase\n .from('teams')\n .select('id')\n .or(`id.eq.${teamId},parent_team_id.eq.${teamId}`);\n \n return accessibleTeams?.map(t => t.id) || [teamId];\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// Helper function to check if a file is an image\nfunction isImageFile(mimeType: string): boolean {\n return mimeType.startsWith('image/') && \n ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'].includes(mimeType);\n}\n\n// Helper function to download and convert image to base64\nasync function downloadImageAsBase64(storageKey: string): Promise<string | null> {\n try {\n // Get signed URL for the file (1 hour expiry)\n const { data: urlData, error: urlError } = await supabase.storage\n .from('vault')\n .createSignedUrl(storageKey, 3600);\n \n if (urlError || !urlData?.signedUrl) {\n console.error(`Failed to create signed URL for ${storageKey}:`, urlError);\n return null;\n }\n \n // Download the file\n const response = await fetch(urlData.signedUrl);\n if (!response.ok) {\n console.error(`Failed to download file ${storageKey}: ${response.status}`);\n return null;\n }\n \n // Convert to base64\n const arrayBuffer = await response.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n return buffer.toString('base64');\n } catch (error) {\n console.error(`Error downloading image ${storageKey}:`, error);\n return null;\n }\n}\n\n/**\n * Convert TipTap JSON format to plain text for timetrack/agenda display\n * @param description - The description in TipTap JSON format or plain text\n * @returns Plain text version of the description\n */\nfunction convertTipTapToPlainText(description?: string | null): string {\n if (!description) {\n return \"\";\n }\n\n // If it's already plain text, return as is\n if (!description.startsWith('{\"type\":\"doc\"')) {\n return description;\n }\n\n try {\n const parsed = JSON.parse(description);\n \n // Recursively extract text from TipTap JSON structure\n const extractText = (node: any): string => {\n if (!node) return \"\";\n\n // Text nodes contain the actual text\n if (node.type === \"text\") {\n return node.text || \"\";\n }\n\n // Handle hard breaks\n if (node.type === \"hardBreak\") {\n return \"\\n\";\n }\n\n // Handle mentions\n if (node.type === \"mention\") {\n return `@${node.attrs?.label || node.attrs?.id || \"\"}`;\n }\n\n // Handle ticket mentions\n if (node.type === \"ticketMention\") {\n return `#${node.attrs?.label || node.attrs?.id || \"\"}`;\n }\n\n // Handle images\n if (node.type === \"image\") {\n return \"[afbeelding]\";\n }\n\n // Process children recursively\n if (node.content && Array.isArray(node.content)) {\n const childrenText = node.content.map(extractText).join(\"\");\n \n // Add appropriate spacing based on node type\n switch (node.type) {\n case \"paragraph\":\n return childrenText + \"\\n\";\n case \"heading\":\n return childrenText + \"\\n\\n\";\n case \"listItem\":\n return \"• \" + childrenText + \"\\n\";\n case \"blockquote\":\n return \"> \" + childrenText + \"\\n\";\n default:\n return childrenText;\n }\n }\n \n // For nodes without content (like empty paragraphs without content array)\n if (node.type === \"paragraph\") {\n return \"\\n\";\n }\n\n return \"\";\n };\n\n const plainText = extractText(parsed);\n return plainText.trim();\n } catch (error) {\n // If parsing fails, return original string\n return description;\n }\n}\n\n/**\n * Get GitHub OAuth token and repository info for a project\n * @param projectId - Project UUID\n * @param teamId - Team UUID\n * @returns GitHub token and repository info or null if not found\n */\nasync function getGithubTokenForProject(projectId: string, teamId: string): Promise<{\n token: string;\n repositoryFullName: string;\n owner: string;\n repo: string;\n} | null> {\n try {\n // 1. Get repository info for project\n const { data: repoData, error: repoError } = await supabase\n .from('project_github_repositories')\n .select('repository_full_name')\n .eq('project_id', projectId)\n .eq('team_id', teamId)\n .single();\n \n if (repoError || !repoData) {\n console.error(`No GitHub repository linked to project ${projectId}`);\n return null;\n }\n \n // 2. Get GitHub OAuth token from apps table\n const { data: appData, error: appError } = await supabase\n .from('apps')\n .select('config')\n .eq('team_id', teamId)\n .eq('app_id', 'github')\n .single();\n \n if (appError || !appData?.config?.access_token) {\n console.error(`GitHub app not connected for team ${teamId}`);\n return null;\n }\n \n const accessToken = appData.config.access_token;\n const repositoryFullName = repoData.repository_full_name;\n \n // Parse owner/repo from full name (e.g., \"midday-ai/midday\" -> owner=\"midday-ai\", repo=\"midday\")\n const [owner, repo] = repositoryFullName.split('/');\n \n if (!owner || !repo) {\n console.error(`Invalid repository full name: ${repositoryFullName}`);\n return null;\n }\n \n return {\n token: accessToken,\n repositoryFullName,\n owner,\n repo\n };\n } catch (error) {\n console.error('Error getting GitHub token for project:', error);\n return null;\n }\n}\n\n/**\n * Automatically transition to the next phase when current phase is completed\n * Phase order: analysis -> bug_investigation -> development -> communication\n * @param sessionId - The AI session UUID\n * @param currentPhase - The phase that just completed (optional, auto-detect if not provided)\n */\nasync function transitionToNextPhase(sessionId: string, currentPhase?: string): Promise<void> {\n try {\n const now = new Date();\n \n // Define phase order\n const phaseOrder = ['analysis', 'bug_investigation', 'development', 'communication'];\n \n // Get all phases for this session\n const { data: allPhases, error: fetchError } = await supabase\n .from('ai_time_logs')\n .select('*')\n .eq('ai_session_id', sessionId)\n .order('activity_type');\n \n if (fetchError || !allPhases) {\n console.error('Failed to fetch phases for transition:', fetchError);\n return;\n }\n \n // Find current active phase if not provided\n let currentPhaseType = currentPhase;\n if (!currentPhaseType) {\n const activePhase = allPhases.find(p => p.status === 'in_progress');\n currentPhaseType = activePhase?.activity_type;\n }\n \n // If no current phase found, start with analysis\n if (!currentPhaseType) {\n const analysisPhase = allPhases.find(p => p.activity_type === 'analysis');\n if (analysisPhase && analysisPhase.status === 'pending' && analysisPhase.estimated_duration_seconds > 0) {\n await supabase\n .from('ai_time_logs')\n .update({\n status: 'in_progress',\n started_at: now.toISOString()\n })\n .eq('id', analysisPhase.id);\n console.error('āœ… Started analysis phase');\n }\n return;\n }\n \n // Complete current phase if it's still in progress\n const currentPhaseRecord = allPhases.find(p => p.activity_type === currentPhaseType && p.status === 'in_progress');\n if (currentPhaseRecord) {\n const duration = Math.round((now.getTime() - new Date(currentPhaseRecord.started_at).getTime()) / 1000);\n await supabase\n .from('ai_time_logs')\n .update({\n status: 'completed',\n ended_at: now.toISOString(),\n duration_seconds: duration\n })\n .eq('id', currentPhaseRecord.id);\n console.error(`āœ… Completed phase: ${currentPhaseType} (${duration}s)`);\n }\n \n // Find next phase in order\n const currentIndex = phaseOrder.indexOf(currentPhaseType);\n if (currentIndex === -1 || currentIndex === phaseOrder.length - 1) {\n console.error('No next phase to transition to');\n return;\n }\n \n // Look for the next valid phase (skip phases with 0 estimated time)\n for (let i = currentIndex + 1; i < phaseOrder.length; i++) {\n const nextPhaseType = phaseOrder[i];\n const nextPhase = allPhases.find(p => p.activity_type === nextPhaseType);\n \n if (!nextPhase) continue;\n \n // Skip phases with 0 estimated time\n if (nextPhase.estimated_duration_seconds === 0) {\n await supabase\n .from('ai_time_logs')\n .update({ status: 'skipped' })\n .eq('id', nextPhase.id);\n console.error(`ā­ļø Skipped phase: ${nextPhaseType} (0 minutes estimated)`);\n continue;\n }\n \n // Start the next phase\n if (nextPhase.status === 'pending') {\n await supabase\n .from('ai_time_logs')\n .update({\n status: 'in_progress',\n started_at: now.toISOString()\n })\n .eq('id', nextPhase.id);\n console.error(`āœ… Started next phase: ${nextPhaseType}`);\n return;\n }\n }\n \n console.error('All remaining phases skipped or completed');\n } catch (error) {\n console.error('Error transitioning to next phase:', error);\n }\n}\n\n// MCP Server setup\nconst server = new Server(\n {\n name: 'mg-tickets-mcp-bridge',\n version: '2.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, including all attachments, comments, and images. Images from ticket attachments and comment attachments are automatically downloaded and returned as base64-encoded content that can be analyzed by AI.',\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 tracking (time breakdown provided by Cursor AI)',\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 timeBreakdown: {\n type: 'object',\n description: 'Time estimate breakdown by development phase (REQUIRED)',\n properties: {\n analysisMinutes: { type: 'number', description: 'Ticket/context analysis time' },\n investigationMinutes: { type: 'number', description: 'Bug investigation/reproduction (0 if not a bug)' },\n developmentMinutes: { type: 'number', description: 'Actual coding/fixing time' },\n communicationMinutes: { type: 'number', description: 'Customer response writing time' }\n },\n required: ['analysisMinutes', 'investigationMinutes', 'developmentMinutes', 'communicationMinutes']\n },\n complexityScore: {\n type: 'number',\n minimum: 1,\n maximum: 10,\n description: 'Estimated complexity from 1-10'\n }\n },\n required: ['ticketId', 'timeBreakdown']\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 estimatedMinutes: { \n type: 'number',\n description: 'Estimated time needed for this follow-up work (think as senior dev WITHOUT AI, in minutes)'\n }\n },\n required: ['aiSessionId', 'originalPrompt', 'aiResponse', 'developerFollowUp', 'followUpReason', 'estimatedMinutes']\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: '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 name: 'get-completion-context',\n description: 'Get all context needed for Cursor AI to generate customer response',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n includeFollowUps: { type: 'boolean', default: true },\n includeTimeMetrics: { type: 'boolean', default: true },\n includeTodos: { type: 'boolean', default: true }\n },\n required: ['aiSessionId']\n }\n },\n {\n name: 'save-customer-response',\n description: 'Save customer response generated by Cursor AI',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n customerResponse: { type: 'string', description: 'Customer response generated by Cursor AI' },\n responseType: { \n type: 'string', \n enum: ['completion', 'progress_update', 'needs_clarification'],\n default: 'completion'\n }\n },\n required: ['aiSessionId', 'customerResponse']\n }\n },\n {\n name: 'complete-ai-session',\n description: 'Complete AI session with work summary - time calculated automatically',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n workCompleted: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of completed tasks/todos in English'\n },\n technicalSummary: {\n type: 'string',\n description: 'Technical summary of work done in English'\n },\n invoiceDescription: {\n type: 'string',\n description: 'Short invoice-friendly description in the language of the ticket (2-3 sentences max, suitable for billing)'\n },\n efficiencyNotes: { type: 'string' }\n },\n required: ['aiSessionId', 'workCompleted']\n }\n },\n {\n name: 'log-hours',\n description: 'Analyze current chat conversation and log hours as draft tracker entry. AI analyzes chat context to estimate hours as a senior developer would (without AI assistance). Cursor AI matches workspace name to correct project from list (optional).',\n inputSchema: {\n type: 'object',\n properties: {\n projectId: {\n type: 'string',\n description: 'Project ID (UUID) - Optional. Cursor AI should call get-projects first to try matching workspace name. If no clear match, omit this field.'\n },\n ticketId: {\n type: 'string',\n description: 'Ticket ID (UUID) - Optional. Cursor AI should call get-tickets (filtered by project) to try matching chat context to an open ticket. Only include if a clear match is found.'\n },\n aiSessionId: {\n type: 'string',\n description: 'AI Session ID - Optional. If a ticket has an active AI dev session, include this ID to link the hours to that session.'\n },\n workDescription: {\n type: 'string',\n description: 'Short description of the work done (for the tracker entry)'\n },\n estimatedHours: {\n type: 'number',\n description: 'AI-estimated hours as senior developer would spend WITHOUT AI (e.g., 2.5 for 2.5 hours)'\n },\n chatContextSummary: {\n type: 'string',\n description: 'Brief summary of chat context for internal logging (optional)'\n }\n },\n required: ['workDescription', 'estimatedHours']\n }\n },\n // === GITHUB TOOLS ===\n {\n name: 'get-github-file',\n description: 'Get the contents of a specific file from a GitHub repository. Use this after finding relevant files to read their full content.',\n inputSchema: {\n type: 'object',\n properties: {\n projectId: { \n type: 'string', \n description: 'Project ID (UUID)' \n },\n filePath: { \n type: 'string', \n description: 'Full path to the file in the repository (e.g., \"src/components/Button.tsx\")' \n },\n ref: {\n type: 'string',\n description: 'Optional: Git reference (branch, tag, or commit SHA). Defaults to repository default branch.'\n }\n },\n required: ['projectId', 'filePath']\n }\n },\n {\n name: 'list-github-directory',\n description: 'List files and directories in a GitHub repository directory. Use this to explore repository structure.',\n inputSchema: {\n type: 'object',\n properties: {\n projectId: { \n type: 'string', \n description: 'Project ID (UUID)' \n },\n directoryPath: { \n type: 'string', \n description: 'Path to directory (e.g., \"src/components\"). Use empty string or \"/\" for root directory.' \n },\n ref: {\n type: 'string',\n description: 'Optional: Git reference (branch, tag, or commit SHA). Defaults to repository default branch.'\n }\n },\n required: ['projectId', 'directoryPath']\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// Helper function to update phase transitions\n// DEPRECATED: Use transitionToNextPhase instead\n// This function is kept for backward compatibility but now delegates to transitionToNextPhase\nasync function updatePhaseTransition(\n sessionId: string, \n fromPhase: string, \n toPhase: string\n): Promise<void> {\n // Use the new automatic transition system that handles all phases correctly\n await transitionToNextPhase(sessionId, fromPhase);\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 // Get all accessible team IDs (own team + child teams)\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\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 .in('team_id', teamIds)\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 // Get ticket data - include tickets from provider's team AND child customer teams\n const { data: ticketData, 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 .single();\n \n if (error) throw error;\n \n // Check if user has access to this ticket (own team or child team)\n const { data: teamAccess } = await supabase\n .from('teams')\n .select('id')\n .or(`id.eq.${ticketData.team_id},parent_team_id.eq.${authContext.teamId}`)\n .eq('id', ticketData.team_id)\n .single();\n \n if (!teamAccess && ticketData.team_id !== authContext.teamId) {\n throw new Error('Access denied: You do not have permission to view this ticket');\n }\n \n const data = ticketData;\n \n // Get ticket attachments (no team filter needed - already validated ticket access)\n const { data: attachments, error: attachmentsError } = await supabase\n .from('ticket_attachments')\n .select(`\n id,\n file_name,\n file_size,\n mime_type,\n storage_key,\n created_at,\n users:user_id(id, full_name)\n `)\n .eq('ticket_id', id)\n .order('created_at', { ascending: true });\n \n if (attachmentsError) {\n console.error('Error fetching attachments:', attachmentsError);\n }\n \n // Get ticket comments\n const { data: comments, error: commentsError } = await supabase\n .from('ticket_comments')\n .select(`\n id,\n content,\n created_at,\n users:user_id(id, full_name)\n `)\n .eq('ticket_id', id)\n .order('created_at', { ascending: true });\n \n if (commentsError) {\n console.error('Error fetching comments:', commentsError);\n }\n \n // Get comment attachments (no team filter needed - already validated ticket access)\n const commentIds = comments?.map(c => c.id) || [];\n let commentAttachments: any[] = [];\n \n if (commentIds.length > 0) {\n const { data: commAttachments, error: commAttachmentsError } = await supabase\n .from('ticket_comment_attachments')\n .select(`\n id,\n comment_id,\n file_name,\n file_size,\n mime_type,\n storage_key,\n created_at\n `)\n .in('comment_id', commentIds);\n \n if (commAttachmentsError) {\n console.error('Error fetching comment attachments:', commAttachmentsError);\n } else {\n commentAttachments = commAttachments || [];\n }\n }\n \n // Build content array starting with text\n const content: any[] = [{\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 `${attachments && attachments.length > 0 ? `\\nšŸ“Ž Attachments: ${attachments.length}\\n` : ''}` +\n `${comments && comments.length > 0 ? `šŸ’¬ Comments: ${comments.length}\\n` : ''}`\n }];\n \n // Process ticket attachments - download images\n if (attachments && attachments.length > 0) {\n console.error(`šŸ“Ž Processing ${attachments.length} ticket attachments...`);\n \n for (const attachment of attachments) {\n if (isImageFile(attachment.mime_type)) {\n console.error(`šŸ–¼ļø Downloading image: ${attachment.file_name}`);\n const base64Data = await downloadImageAsBase64(attachment.storage_key);\n \n if (base64Data) {\n content.push({\n type: 'image',\n data: base64Data,\n mimeType: attachment.mime_type\n });\n \n // Add text context about the image\n content.push({\n type: 'text',\n text: `\\nšŸ“ø **Image from ticket**: ${attachment.file_name} (${Math.round(attachment.file_size / 1024)}KB, uploaded by ${(attachment.users as any)?.full_name || 'Unknown'} on ${new Date(attachment.created_at).toLocaleDateString()})\\n`\n });\n }\n }\n }\n }\n \n // Process comment attachments - download images\n if (commentAttachments.length > 0) {\n console.error(`šŸ“Ž Processing ${commentAttachments.length} comment attachments...`);\n \n for (const attachment of commentAttachments) {\n if (isImageFile(attachment.mime_type)) {\n console.error(`šŸ–¼ļø Downloading comment image: ${attachment.file_name}`);\n const base64Data = await downloadImageAsBase64(attachment.storage_key);\n \n if (base64Data) {\n // Find the comment this attachment belongs to\n const comment = comments?.find(c => c.id === attachment.comment_id);\n \n content.push({\n type: 'image',\n data: base64Data,\n mimeType: attachment.mime_type\n });\n \n // Add text context about the image\n content.push({\n type: 'text',\n text: `\\nšŸ“ø **Image from comment** by ${(comment?.users as any)?.full_name || 'Unknown'} on ${new Date(attachment.created_at).toLocaleDateString()}: ${attachment.file_name} (${Math.round(attachment.file_size / 1024)}KB)\\n` +\n (comment?.content ? `Comment text: \"${comment.content.substring(0, 100)}${comment.content.length > 100 ? '...' : ''}\"\\n` : '')\n });\n }\n }\n }\n }\n \n console.error(`āœ… Returning ticket with ${content.filter(c => c.type === 'image').length} images`);\n \n return { content };\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 // Get all accessible team IDs (own team + child teams)\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n \n let query = supabase\n .from('customers')\n .select('id, name, email, website, created_at')\n .in('team_id', teamIds)\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 // Get all accessible team IDs (own team + child teams)\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n \n let query = supabase\n .from('projects')\n .select(`\n id,\n name,\n description,\n customer_id,\n created_at\n `)\n .in('team_id', teamIds)\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}** (ID: ${project.id})\\n` +\n `${project.description ? `Description: ${project.description}\\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, timeBreakdown, complexityScore } = args as any;\n \n // Validate timeBreakdown is provided\n if (!timeBreakdown || !timeBreakdown.analysisMinutes || timeBreakdown.developmentMinutes === undefined) {\n throw new Error('timeBreakdown is required with all phases: analysisMinutes, investigationMinutes, developmentMinutes, communicationMinutes');\n }\n \n // Calculate total time from breakdown\n const totalEstimateMinutes = \n (timeBreakdown.analysisMinutes || 0) +\n (timeBreakdown.investigationMinutes || 0) +\n (timeBreakdown.developmentMinutes || 0) +\n (timeBreakdown.communicationMinutes || 0);\n \n const sessionStartTime = new Date();\n \n // Create AI session with calculated total\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: totalEstimateMinutes,\n complexity_score: complexityScore || null,\n status: 'in_progress'\n })\n .select('id, ticket_id, cursor_session_id, created_at')\n .single();\n \n if (error) throw error;\n \n // CREATE PHASE TIME LOGS: Store breakdown as separate phase activities\n const phaseActivities = [\n {\n ai_session_id: sessionData.id,\n activity_type: 'analysis',\n description: 'Ticket analysis and context understanding',\n duration_seconds: 0,\n estimated_duration_seconds: timeBreakdown.analysisMinutes * 60,\n status: 'in_progress', // Analysis starts immediately\n productivity_score: 8,\n started_at: sessionStartTime.toISOString()\n },\n {\n ai_session_id: sessionData.id,\n activity_type: 'bug_investigation',\n description: 'Bug investigation and root cause analysis',\n duration_seconds: 0,\n estimated_duration_seconds: timeBreakdown.investigationMinutes * 60,\n status: 'pending',\n productivity_score: null\n },\n {\n ai_session_id: sessionData.id,\n activity_type: 'development',\n description: 'Implementation and coding',\n duration_seconds: 0,\n estimated_duration_seconds: timeBreakdown.developmentMinutes * 60,\n status: 'pending',\n productivity_score: null\n },\n {\n ai_session_id: sessionData.id,\n activity_type: 'communication',\n description: 'Customer response and documentation',\n duration_seconds: 0,\n estimated_duration_seconds: timeBreakdown.communicationMinutes * 60,\n status: 'pending',\n productivity_score: null\n }\n ];\n \n // Insert all phase activities\n await supabase.from('ai_time_logs').insert(phaseActivities);\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 `\\nšŸ“Š **Time Breakdown:**\\n` +\n ` • Analysis: ${timeBreakdown.analysisMinutes} min\\n` +\n ` • Investigation: ${timeBreakdown.investigationMinutes} min\\n` +\n ` • Development: ${timeBreakdown.developmentMinutes} min\\n` +\n ` • Communication: ${timeBreakdown.communicationMinutes} min\\n` +\n ` • **Total: ${totalEstimateMinutes} min**\\n\\n` +\n `${complexityScore ? `šŸŽÆ Complexity: ${complexityScore}/10\\n` : ''}` +\n `ā±ļø **Phase Tracking Started** (Analysis in progress)\\n` +\n `${cursorSessionId ? `šŸ”— Cursor Session: ${cursorSessionId}\\n` : ''}` +\n `šŸ“… Started: ${sessionStartTime.toLocaleString()}\\n\\n` +\n `āœ… Session initialized with phase breakdown!\\n` +\n `šŸ“ Timetrack entry will be created when you complete the session.`\n }]\n };\n }\n \n case 'track-manual-follow-up': {\n const { aiSessionId, originalPrompt, aiResponse, developerFollowUp, followUpReason, outcome = 'success', estimatedMinutes } = 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 and current session data\n // Find the session - get all sessions for accessible teams and filter in JS\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id, status, created_at, ai_time_estimate_minutes')\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n \n const followUpTime = new Date();\n \n // Store old estimate for reporting\n const oldEstimate = session.ai_time_estimate_minutes || 60;\n \n // Calculate new estimate: add follow-up estimate to existing estimate\n const newEstimate = oldEstimate + (estimatedMinutes || 0);\n \n // RESTART SESSION & UPDATE ESTIMATE: Set status back to in_progress and adjust time estimate\n await supabase\n .from('ai_sessions')\n .update({\n status: 'in_progress', // Restart active tracking\n ai_time_estimate_minutes: newEstimate, // Increase estimate based on follow-up work\n // Don't update completed_at - session continues\n })\n .eq('id', session.id);\n \n // LOG FOLLOW-UP: Track the manual follow-up interaction\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: null, // Calculated automatically from session timestamps\n resolved_at: outcome === 'success' ? new Date().toISOString() : null\n })\n .select()\n .single();\n \n if (error) throw error;\n \n // RESTART TIME TRACKING: Log follow-up activity start (duration calculated at completion)\n await supabase\n .from('ai_time_logs')\n .insert({\n ai_session_id: session.id,\n activity_type: 'debugging', // Follow-ups are typically debugging/fixing\n description: `Follow-up: ${followUpReason.replace('_', ' ')} - ${outcome}`,\n duration_seconds: 0, // Duration calculated automatically from timestamps\n productivity_score: outcome === 'success' ? 9 : outcome === 'partial_success' ? 6 : 4,\n started_at: followUpTime.toISOString()\n });\n \n // CALCULATE CURRENT EFFICIENCY: Compare time spent vs NEW estimated time\n const sessionStartTime = new Date(session.created_at);\n const totalMinutesElapsed = Math.round((followUpTime.getTime() - sessionStartTime.getTime()) / 60000);\n const currentEfficiency = totalMinutesElapsed > 0 ? (totalMinutesElapsed / newEstimate) : 1;\n \n // UPDATE EFFICIENCY TRACKING: Update running efficiency score with adjusted estimate\n await supabase\n .from('ai_sessions')\n .update({\n efficiency_score: currentEfficiency.toFixed(2),\n actual_time_minutes: totalMinutesElapsed\n })\n .eq('id', session.id);\n \n return {\n content: [{\n type: 'text',\n text: `šŸ”„ **Follow-up Tracked & Session Restarted!**\\n\\n` +\n `šŸ†” Session: ${aiSessionId} (back to active)\\n` +\n `šŸ” Reason: ${followUpReason.replace('_', ' ')}\\n` +\n `āœ… Outcome: ${outcome}\\n` +\n `\\nšŸ“Š **Time Estimate Updated:**\\n` +\n ` • Old estimate: ${oldEstimate} minutes\\n` +\n ` • Follow-up estimate: +${estimatedMinutes || 0} minutes\\n` +\n ` • New estimate: ${newEstimate} minutes\\n` +\n `\\nšŸ“ˆ **Current Progress:**\\n` +\n ` • Total time elapsed: ${totalMinutesElapsed} minutes\\n` +\n ` • Efficiency: ${currentEfficiency < 1 ? 'šŸš€ ' : currentEfficiency > 1.5 ? 'āš ļø ' : 'ā±ļø '}${(currentEfficiency * 100).toFixed(0)}%\\n` +\n `\\n⚔ **Time tracking resumed** - continue with confidence!`\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 - find by JavaScript filtering\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await 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 .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\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 - get all sessions for accessible teams and filter in JS\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\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 // AUTOMATIC PHASE TRANSITION\n let phaseTransition: string | null = null;\n \n // Get all current todos for this session\n const { data: currentTodos } = await supabase\n .from('ai_todos')\n .select('status')\n .eq('ai_session_id', session.id);\n \n if (currentTodos && currentTodos.length > 0) {\n const hasInProgress = currentTodos.some(t => t.status === 'in_progress');\n const allCompleted = currentTodos.every(t => t.status === 'completed');\n \n // Get current phase status\n const { data: currentPhase } = await supabase\n .from('ai_time_logs')\n .select('activity_type, status')\n .eq('ai_session_id', session.id)\n .eq('status', 'in_progress')\n .single();\n \n // Analysis → Next Phase: When first todo moves to in_progress (work starts)\n if (hasInProgress && currentPhase?.activity_type === 'analysis') {\n await transitionToNextPhase(session.id, 'analysis');\n phaseTransition = 'Analysis completed → Next phase started (Investigation/Development)';\n }\n \n // Investigation → Development: When todos progress during investigation phase\n // This typically happens after initial analysis, when actual coding begins\n if (hasInProgress && currentPhase?.activity_type === 'bug_investigation') {\n // Check if any development-related work has started (indicated by todo progress)\n const completedCount = currentTodos.filter(t => t.status === 'completed').length;\n if (completedCount > 0) {\n // Some work completed, likely moving from investigation to actual fixing\n await transitionToNextPhase(session.id, 'bug_investigation');\n phaseTransition = 'Investigation completed → Development phase started';\n }\n }\n \n // Development → Communication: When all todos are completed (implementation done)\n if (allCompleted && currentPhase?.activity_type === 'development') {\n await transitionToNextPhase(session.id, 'development');\n phaseTransition = 'Development completed → Communication phase started';\n }\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 `${phaseTransition ? `šŸ”„ Phase Transition: ${phaseTransition}\\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 - get all sessions for accessible teams and filter in JS\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\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 '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 // First find the session\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: findError } = await supabase\n .from('ai_sessions')\n .select('id')\n .in('team_id', teamIds);\n \n if (findError) {\n throw new Error(`Database error: ${findError.message}`);\n }\n \n const foundSession = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!foundSession) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n \n // Now update the found 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('id', foundSession.id)\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 case 'get-completion-context': {\n const { aiSessionId, includeFollowUps = true, includeTimeMetrics = true, includeTodos = true } = 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 ticket info\n // Get comprehensive session context - find by JavaScript filtering\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select(`\n id,\n ticket_id,\n ai_time_estimate_minutes,\n actual_time_minutes,\n efficiency_score,\n created_at,\n completed_at,\n status,\n complexity_score\n `)\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n \n // Get ticket data\n const { data: ticket, error: ticketError } = await supabase\n .from('tickets')\n .select('ticket_number, title, description, type, priority')\n .eq('id', session.ticket_id)\n .single();\n \n if (ticketError || !ticket) {\n throw new Error('Ticket not found for session');\n }\n \n let contextData: any = {\n session: {\n id: aiSessionId,\n status: session.status,\n complexity: session.complexity_score,\n createdAt: session.created_at,\n completedAt: session.completed_at\n },\n ticket: {\n number: ticket.ticket_number,\n title: ticket.title,\n description: ticket.description,\n type: ticket.type,\n priority: ticket.priority\n }\n };\n \n // Add time metrics if requested\n if (includeTimeMetrics) {\n const timeSaved = session.ai_time_estimate_minutes && session.actual_time_minutes \n ? Math.max(0, session.ai_time_estimate_minutes - session.actual_time_minutes)\n : null;\n \n contextData.timeMetrics = {\n estimatedMinutes: session.ai_time_estimate_minutes,\n actualMinutes: session.actual_time_minutes,\n timeSaved: timeSaved,\n efficiency: session.efficiency_score,\n sessionDuration: session.completed_at && session.created_at \n ? Math.round((new Date(session.completed_at).getTime() - new Date(session.created_at).getTime()) / 60000)\n : null\n };\n }\n \n // Add todos if requested\n if (includeTodos) {\n const { data: todos } = await supabase\n .from('ai_todos')\n .select('content, status, estimated_minutes, actual_minutes, completed_at')\n .eq('ai_session_id', session.id)\n .order('created_at', { ascending: true });\n \n contextData.todos = todos || [];\n }\n \n // Add follow-ups if requested\n if (includeFollowUps) {\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', { ascending: true });\n \n contextData.followUps = followUps || [];\n }\n \n return {\n content: [{\n type: 'text',\n text: `šŸ“‹ **Completion Context Retrieved!**\\n\\n` +\n `šŸŽ« **Ticket:** ${ticket.ticket_number} - ${ticket.title}\\n` +\n `šŸ†” **Session:** ${aiSessionId} (${session.status})\\n` +\n `ā±ļø **Time:** ${session.actual_time_minutes || 'N/A'}/${session.ai_time_estimate_minutes || 'N/A'} minutes\\n` +\n `šŸ“‹ **Todos:** ${contextData.todos?.filter((t: any) => t.status === 'completed').length || 0}/${contextData.todos?.length || 0} completed\\n` +\n `šŸ”„ **Follow-ups:** ${contextData.followUps?.length || 0}\\n\\n` +\n `āœ… **Full context ready for Cursor AI to generate customer response!**\\n\\n` +\n `**Context Data:**\\n\\`\\`\\`json\\n${JSON.stringify(contextData, null, 2)}\\`\\`\\``\n }]\n };\n }\n \n case 'save-customer-response': {\n const { aiSessionId, customerResponse, responseType = 'completion' } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Get session to validate it exists - find by JavaScript filtering\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n \n // Save the response in database\n const { data: responseData, error: responseError } = await supabase\n .from('ai_responses')\n .insert({\n ai_session_id: session.id,\n response_type: responseType,\n content: customerResponse,\n is_ready_for_customer: true,\n provider_approved: false // Needs manual approval\n })\n .select()\n .single();\n \n if (responseError) throw responseError;\n \n return {\n content: [{\n type: 'text',\n text: `šŸ’¾ **Customer Response Saved!**\\n\\n` +\n `šŸ†” Session: ${aiSessionId}\\n` +\n `šŸ“ Response Type: ${responseType}\\n` +\n `šŸ“„ Length: ${customerResponse.length} characters\\n\\n` +\n `āœ… **Response ready for provider approval**\\n` +\n `šŸ” Provider can review in AI tab before sending to customer\\n\\n` +\n `**Preview:**\\n\\`\\`\\`\\n${customerResponse.substring(0, 200)}${customerResponse.length > 200 ? '...' : ''}\\`\\`\\``\n }]\n };\n }\n \n case 'complete-ai-session': {\n const { aiSessionId, workCompleted, technicalSummary, invoiceDescription, efficiencyNotes } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Get session to calculate actual time spent - find by JavaScript filtering\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: getSessionError } = await supabase\n .from('ai_sessions')\n .select('id, ticket_id, ai_time_estimate_minutes, created_at')\n .in('team_id', teamIds);\n \n if (getSessionError) {\n throw new Error(`Database error: ${getSessionError.message}`);\n }\n \n // Find session with matching prefix\n const existingSession = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!existingSession) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n\n // Calculate actual time spent automatically\n const completionTime = new Date();\n const sessionStartTime = new Date(existingSession.created_at);\n const timeSpentMinutes = Math.round((completionTime.getTime() - sessionStartTime.getTime()) / 60000);\n \n // Update session to completed with calculated time\n const { data: session, error: sessionError } = await supabase\n .from('ai_sessions')\n .update({\n status: 'completed',\n actual_time_minutes: timeSpentMinutes,\n completed_at: completionTime.toISOString(),\n efficiency_score: null // Will be calculated\n })\n .eq('id', existingSession.id)\n .select('id, ticket_id, ai_time_estimate_minutes, created_at')\n .single();\n \n if (sessionError || !session) {\n throw new Error(`Failed to update session: ${aiSessionId}`);\n }\n \n // Calculate efficiency score\n const efficiencyScore = session.ai_time_estimate_minutes \n ? (timeSpentMinutes / session.ai_time_estimate_minutes)\n : 1.0;\n \n // Update efficiency score\n await supabase\n .from('ai_sessions')\n .update({ efficiency_score: efficiencyScore.toFixed(2) })\n .eq('id', session.id);\n \n // CLOSE ALL REMAINING ACTIVE PHASES\n const { data: activePhases } = await supabase\n .from('ai_time_logs')\n .select('*')\n .eq('ai_session_id', existingSession.id)\n .eq('status', 'in_progress');\n\n for (const phase of activePhases || []) {\n const duration = Math.round(\n (completionTime.getTime() - new Date(phase.started_at).getTime()) / 1000\n );\n \n await supabase\n .from('ai_time_logs')\n .update({\n ended_at: completionTime.toISOString(),\n duration_seconds: duration,\n status: 'completed'\n })\n .eq('id', phase.id);\n }\n\n // Mark skipped phases (pending with 0 estimated time)\n await supabase\n .from('ai_time_logs')\n .update({ status: 'skipped' })\n .eq('ai_session_id', existingSession.id)\n .eq('status', 'pending')\n .eq('estimated_duration_seconds', 0);\n \n // Get session duration\n const sessionDuration = Math.round(\n (completionTime.getTime() - new Date(session.created_at).getTime()) / 60000\n );\n \n // Create work summary\n const workSummary = `Completed ${workCompleted.length} tasks including: ${workCompleted.slice(0, 3).join(', ')}${workCompleted.length > 3 ? ' and more' : ''}.`;\n \n // Get ticket details for agenda event creation\n const { data: ticketInfo } = await supabase\n .from('tickets')\n .select('ticket_number, title, project_id')\n .eq('id', session.ticket_id)\n .single();\n \n // CREATE AGENDA EVENT: Now that work is complete, create the timetrack entry\n // Use invoice description if provided, otherwise create a technical one\n let completionDescription: string;\n \n if (invoiceDescription) {\n // Use the invoice-friendly description provided by Cursor (in ticket language)\n completionDescription = `${ticketInfo?.ticket_number || 'Ticket'}: ${invoiceDescription}`;\n } else {\n // Fallback: Create a technical work description\n const workDescription = workCompleted.map((task: string, index: number) => `${index + 1}. ${task}`).join('\\n');\n completionDescription = `${ticketInfo?.ticket_number || 'Ticket'}: ${technicalSummary || workSummary}\\n\\nCompleted work:\\n${workDescription}`;\n }\n \n // Create the agenda event with AI estimated time\n // Use the original AI estimate for billing, not the actual AI completion time\n const estimatedMinutes = session.ai_time_estimate_minutes || timeSpentMinutes;\n const sessionStart = new Date(session.created_at);\n const estimatedEnd = new Date(sessionStart.getTime() + estimatedMinutes * 60000);\n \n const { data: agendaEvent, error: agendaError } = await supabase\n .from('agenda_events')\n .insert({\n team_id: authContext.teamId,\n user_id: authContext.userId,\n title: ticketInfo?.title || 'Development Work',\n description: completionDescription,\n start_time: sessionStart.toISOString(),\n end_time: estimatedEnd.toISOString(),\n project_id: ticketInfo?.project_id || null,\n ticket_id: session.ticket_id,\n ai_session_id: session.id, // Use the actual UUID, not the readable ID\n type: 'work',\n status: 'draft', // Mark as draft for manual approval\n all_day: false,\n is_tracked: true,\n tracked_duration: estimatedMinutes * 60 // Use AI estimate in seconds for billing\n })\n .select('id')\n .single();\n \n if (agendaError) {\n console.error('āš ļø Failed to create agenda event:', agendaError);\n // Don't fail the completion if agenda event creation fails\n }\n \n let responseText = `šŸŽ‰ **AI Session Completed Successfully!**\\n\\n`;\n responseText += `šŸ†” Session: ${aiSessionId}\\n`;\n responseText += `šŸ“Š **Performance Summary:**\\n`;\n responseText += ` • Tasks Completed: ${workCompleted.length}\\n`;\n responseText += ` • Time Spent: ${timeSpentMinutes} minutes\\n`;\n responseText += ` • Estimated Time: ${session.ai_time_estimate_minutes || 'N/A'} minutes\\n`;\n responseText += ` • Efficiency: ${efficiencyScore < 1 ? 'šŸš€' : efficiencyScore > 1.5 ? 'āš ļø' : 'ā±ļø'} ${(efficiencyScore * 100).toFixed(0)}%\\n`;\n responseText += ` • Session Duration: ${sessionDuration} minutes\\n\\n`;\n \n responseText += `āœ… **Work Completed:**\\n`;\n workCompleted.forEach((task: string, index: number) => {\n responseText += `${index + 1}. ${task}\\n`;\n });\n responseText += `\\n`;\n \n if (technicalSummary) {\n responseText += `šŸ”§ **Technical Summary:**\\n${technicalSummary}\\n\\n`;\n }\n \n if (efficiencyNotes) {\n responseText += `šŸ“ˆ **Efficiency Notes:**\\n${efficiencyNotes}\\n\\n`;\n }\n \n if (agendaEvent) {\n responseText += `šŸ“… **Timetrack Entry Created:**\\n`;\n responseText += ` • Agenda event created with work summary\\n`;\n responseText += ` • Status: DRAFT (requires approval in agenda)\\n`;\n responseText += ` • Duration: ${timeSpentMinutes} minutes\\n`;\n responseText += ` • Period: ${sessionStart.toLocaleString()} - ${completionTime.toLocaleString()}\\n\\n`;\n }\n \n // Provide context for Cursor AI to generate customer response\n responseText += `šŸ“‹ **Context for Customer Response:**\\n`;\n responseText += ` • Use \"get-completion-context\" to retrieve full context\\n`;\n responseText += ` • Generate customer-friendly response based on completed work\\n`;\n responseText += ` • Focus on business value and customer benefits\\n\\n`;\n \n responseText += `šŸŽÆ **Session archived successfully!**`;\n \n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n }\n \n case 'log-hours': {\n const { projectId, ticketId, aiSessionId, workDescription, estimatedHours, chatContextSummary } = args as any;\n \n let project = null;\n let ticket = null;\n let aiSession = null;\n \n // Verify project access if projectId is provided\n if (projectId) {\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: projectData, error: projectError } = await supabase\n .from('projects')\n .select('id, name, team_id')\n .eq('id', projectId)\n .in('team_id', teamIds)\n .single();\n \n if (projectError || !projectData) {\n throw new Error(`Project not found or no access: ${projectId}. Please call get-projects first to find the correct project.`);\n }\n \n project = projectData;\n }\n \n // Verify ticket access if ticketId is provided\n if (ticketId) {\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: ticketData, error: ticketError } = await supabase\n .from('tickets')\n .select('id, title, status')\n .eq('id', ticketId)\n .in('team_id', teamIds)\n .single();\n \n if (ticketError || !ticketData) {\n throw new Error(`Ticket not found or no access: ${ticketId}. Please call get-tickets first to find the correct ticket.`);\n }\n \n ticket = ticketData;\n }\n \n // Verify AI session if aiSessionId is provided\n if (aiSessionId) {\n const { data: sessionData, error: sessionError } = await supabase\n .from('ai_dev_sessions')\n .select('id, ticket_id, status')\n .eq('id', aiSessionId)\n .single();\n \n if (sessionError || !sessionData) {\n throw new Error(`AI Session not found: ${aiSessionId}.`);\n }\n \n aiSession = sessionData;\n }\n \n // Convert hours to seconds for agenda_events.tracked_duration\n const durationSeconds = Math.round(estimatedHours * 3600);\n \n // Create agenda event as time tracking entry (draft)\n const now = new Date();\n const startTime = new Date(now.getTime() - durationSeconds * 1000); // Back-calculate start time\n \n const { data: agendaEntry, error: agendaError } = await supabase\n .from('agenda_events')\n .insert({\n team_id: authContext.teamId,\n user_id: authContext.userId,\n project_id: project?.id || null,\n ticket_id: ticket?.id || null,\n ai_session_id: aiSession?.id || null,\n title: workDescription,\n description: chatContextSummary || workDescription,\n start_time: startTime.toISOString(),\n end_time: now.toISOString(),\n type: 'work',\n status: 'draft',\n all_day: false,\n is_tracked: true,\n tracked_duration: durationSeconds\n })\n .select('id, tracked_duration, project_id, ticket_id, ai_session_id')\n .single();\n \n if (agendaError || !agendaEntry) {\n throw new Error(`Failed to create time entry: ${agendaError?.message || 'Unknown error'}`);\n }\n \n let responseText = `ā±ļø **Hours Logged Successfully!**\\n\\n`;\n responseText += `šŸ“‹ **Entry Details:**\\n`;\n if (project) {\n responseText += ` • Project: ${project.name}\\n`;\n } else {\n responseText += ` • Project: (No project assigned)\\n`;\n }\n if (ticket) {\n responseText += ` • Ticket: ${ticket.title} (${ticket.status})\\n`;\n }\n if (aiSession) {\n responseText += ` • AI Session: ${aiSession.id} (${aiSession.status})\\n`;\n }\n responseText += ` • Description: ${workDescription}\\n`;\n responseText += ` • Estimated Hours: ${estimatedHours}h (${Math.floor(estimatedHours)}h ${Math.round((estimatedHours % 1) * 60)}m)\\n`;\n responseText += ` • Status: DRAFT (not billed yet)\\n`;\n responseText += ` • Entry ID: ${agendaEntry.id}\\n\\n`;\n \n if (chatContextSummary) {\n responseText += `šŸ“Š **Work Context:**\\n`;\n responseText += `${chatContextSummary.substring(0, 200)}${chatContextSummary.length > 200 ? '...' : ''}\\n\\n`;\n }\n \n responseText += `āœ… Time entry created and ready for review in the agenda!`;\n \n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n }\n \n // === GITHUB TOOLS ===\n case 'get-github-file': {\n const { projectId, filePath, ref } = args as any;\n \n // Get GitHub token for project\n const githubInfo = await getGithubTokenForProject(projectId, authContext.teamId);\n if (!githubInfo) {\n return {\n content: [{\n type: 'text',\n text: 'āŒ GitHub not configured for this project.'\n }]\n };\n }\n \n try {\n const octokit = new Octokit({ auth: githubInfo.token });\n \n console.error(`šŸ“„ Reading file: ${filePath} from ${githubInfo.repositoryFullName}`);\n \n const { data } = await octokit.rest.repos.getContent({\n owner: githubInfo.owner,\n repo: githubInfo.repo,\n path: filePath,\n ref: ref\n });\n \n // Check if it's a file (not directory)\n if (Array.isArray(data) || data.type !== 'file') {\n return {\n content: [{\n type: 'text',\n text: `āŒ \"${filePath}\" is not a file or contains multiple items.`\n }]\n };\n }\n \n // Decode base64 content\n const content = Buffer.from(data.content, 'base64').toString('utf-8');\n \n let responseText = `šŸ“„ **File: ${filePath}**\\n`;\n responseText += `Repository: ${githubInfo.repositoryFullName}\\n`;\n responseText += `Size: ${data.size} bytes\\n`;\n responseText += `URL: ${data.html_url}\\n\\n`;\n responseText += `**Content:**\\n\\`\\`\\`\\n${content}\\n\\`\\`\\``;\n \n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n } catch (error: any) {\n console.error('GitHub get file error:', error);\n \n if (error.status === 404) {\n return {\n content: [{\n type: 'text',\n text: `āŒ File not found: ${filePath}`\n }]\n };\n }\n \n return {\n content: [{\n type: 'text',\n text: `āŒ Failed to read file: ${error.message || 'Unknown error'}`\n }]\n };\n }\n }\n \n case 'list-github-directory': {\n const { projectId, directoryPath, ref } = args as any;\n \n // Get GitHub token for project\n const githubInfo = await getGithubTokenForProject(projectId, authContext.teamId);\n if (!githubInfo) {\n return {\n content: [{\n type: 'text',\n text: 'āŒ GitHub not configured for this project.'\n }]\n };\n }\n \n try {\n const octokit = new Octokit({ auth: githubInfo.token });\n \n // Normalize directory path (empty string or \"/\" for root)\n const normalizedPath = (!directoryPath || directoryPath === '/') ? '' : directoryPath;\n \n console.error(`šŸ“ Listing directory: ${normalizedPath || '(root)'} in ${githubInfo.repositoryFullName}`);\n \n const { data } = await octokit.rest.repos.getContent({\n owner: githubInfo.owner,\n repo: githubInfo.repo,\n path: normalizedPath,\n ref: ref\n });\n \n // Check if it's a directory\n if (!Array.isArray(data)) {\n return {\n content: [{\n type: 'text',\n text: `āŒ \"${directoryPath}\" is not a directory.`\n }]\n };\n }\n \n let responseText = `šŸ“ **Directory: ${directoryPath || '(root)'}**\\n`;\n responseText += `Repository: ${githubInfo.repositoryFullName}\\n`;\n responseText += `Items: ${data.length}\\n\\n`;\n \n // Group by type\n const directories = data.filter(item => item.type === 'dir');\n const files = data.filter(item => item.type === 'file');\n \n if (directories.length > 0) {\n responseText += `**šŸ“ Directories (${directories.length}):**\\n`;\n for (const dir of directories) {\n responseText += ` - ${dir.name}/\\n`;\n }\n responseText += `\\n`;\n }\n \n if (files.length > 0) {\n responseText += `**šŸ“„ Files (${files.length}):**\\n`;\n for (const file of files) {\n responseText += ` - ${file.name} (${file.size} bytes)\\n`;\n }\n }\n \n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n } catch (error: any) {\n console.error('GitHub list directory error:', error);\n \n if (error.status === 404) {\n return {\n content: [{\n type: 'text',\n text: `āŒ Directory not found: ${directoryPath}`\n }]\n };\n }\n \n return {\n content: [{\n type: 'text',\n text: `āŒ Failed to list directory: ${error.message || 'Unknown error'}`\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 teamIds = await getAccessibleTeamIds(authContext!.teamId);\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 .in('team_id', teamIds)\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 teamIds = await getAccessibleTeamIds(authContext!.teamId);\n const { data, error } = await supabase\n .from('customers')\n .select('id, name, email, website, created_at')\n .in('team_id', teamIds)\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 teamIds = await getAccessibleTeamIds(authContext!.teamId);\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 .in('team_id', teamIds)\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":";;;;;;;;AAUA,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;AA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AAuC,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';\nimport { Octokit } from '@octokit/rest';\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// Smart time estimation and codebase analysis is now handled by Cursor AI\n// MCP bridge focuses on data storage and session management only\n\n/**\n * Round minutes to the nearest 15-minute increment\n * @param minutes - The number of minutes to round\n * @returns The rounded number of minutes (always a multiple of 15)\n */\nfunction roundToNearest15Minutes(minutes: number): number {\n if (minutes <= 0) return 0;\n return Math.round(minutes / 15) * 15;\n}\n\n// Helper function to get accessible team IDs (own team + child teams)\nasync function getAccessibleTeamIds(teamId: string): Promise<string[]> {\n const { data: accessibleTeams } = await supabase\n .from('teams')\n .select('id')\n .or(`id.eq.${teamId},parent_team_id.eq.${teamId}`);\n \n return accessibleTeams?.map(t => t.id) || [teamId];\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// Helper function to check if a file is an image\nfunction isImageFile(mimeType: string): boolean {\n return mimeType.startsWith('image/') && \n ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'].includes(mimeType);\n}\n\n// Helper function to download and convert image to base64\nasync function downloadImageAsBase64(storageKey: string): Promise<string | null> {\n try {\n // Get signed URL for the file (1 hour expiry)\n const { data: urlData, error: urlError } = await supabase.storage\n .from('vault')\n .createSignedUrl(storageKey, 3600);\n \n if (urlError || !urlData?.signedUrl) {\n console.error(`Failed to create signed URL for ${storageKey}:`, urlError);\n return null;\n }\n \n // Download the file\n const response = await fetch(urlData.signedUrl);\n if (!response.ok) {\n console.error(`Failed to download file ${storageKey}: ${response.status}`);\n return null;\n }\n \n // Convert to base64\n const arrayBuffer = await response.arrayBuffer();\n const buffer = Buffer.from(arrayBuffer);\n return buffer.toString('base64');\n } catch (error) {\n console.error(`Error downloading image ${storageKey}:`, error);\n return null;\n }\n}\n\n/**\n * Convert TipTap JSON format to plain text for timetrack/agenda display\n * @param description - The description in TipTap JSON format or plain text\n * @returns Plain text version of the description\n */\nfunction convertTipTapToPlainText(description?: string | null): string {\n if (!description) {\n return \"\";\n }\n\n // If it's already plain text, return as is\n if (!description.startsWith('{\"type\":\"doc\"')) {\n return description;\n }\n\n try {\n const parsed = JSON.parse(description);\n \n // Recursively extract text from TipTap JSON structure\n const extractText = (node: any): string => {\n if (!node) return \"\";\n\n // Text nodes contain the actual text\n if (node.type === \"text\") {\n return node.text || \"\";\n }\n\n // Handle hard breaks\n if (node.type === \"hardBreak\") {\n return \"\\n\";\n }\n\n // Handle mentions\n if (node.type === \"mention\") {\n return `@${node.attrs?.label || node.attrs?.id || \"\"}`;\n }\n\n // Handle ticket mentions\n if (node.type === \"ticketMention\") {\n return `#${node.attrs?.label || node.attrs?.id || \"\"}`;\n }\n\n // Handle images\n if (node.type === \"image\") {\n return \"[afbeelding]\";\n }\n\n // Process children recursively\n if (node.content && Array.isArray(node.content)) {\n const childrenText = node.content.map(extractText).join(\"\");\n \n // Add appropriate spacing based on node type\n switch (node.type) {\n case \"paragraph\":\n return childrenText + \"\\n\";\n case \"heading\":\n return childrenText + \"\\n\\n\";\n case \"listItem\":\n return \"• \" + childrenText + \"\\n\";\n case \"blockquote\":\n return \"> \" + childrenText + \"\\n\";\n default:\n return childrenText;\n }\n }\n \n // For nodes without content (like empty paragraphs without content array)\n if (node.type === \"paragraph\") {\n return \"\\n\";\n }\n\n return \"\";\n };\n\n const plainText = extractText(parsed);\n return plainText.trim();\n } catch (error) {\n // If parsing fails, return original string\n return description;\n }\n}\n\n/**\n * Get GitHub OAuth token and repository info for a project\n * @param projectId - Project UUID\n * @param teamId - Team UUID\n * @returns GitHub token and repository info or null if not found\n */\nasync function getGithubTokenForProject(projectId: string, teamId: string): Promise<{\n token: string;\n repositoryFullName: string;\n owner: string;\n repo: string;\n} | null> {\n try {\n // 1. Get repository info for project\n const { data: repoData, error: repoError } = await supabase\n .from('project_github_repositories')\n .select('repository_full_name')\n .eq('project_id', projectId)\n .eq('team_id', teamId)\n .single();\n \n if (repoError || !repoData) {\n console.error(`No GitHub repository linked to project ${projectId}`);\n return null;\n }\n \n // 2. Get GitHub OAuth token from apps table\n const { data: appData, error: appError } = await supabase\n .from('apps')\n .select('config')\n .eq('team_id', teamId)\n .eq('app_id', 'github')\n .single();\n \n if (appError || !appData?.config?.access_token) {\n console.error(`GitHub app not connected for team ${teamId}`);\n return null;\n }\n \n const accessToken = appData.config.access_token;\n const repositoryFullName = repoData.repository_full_name;\n \n // Parse owner/repo from full name (e.g., \"midday-ai/midday\" -> owner=\"midday-ai\", repo=\"midday\")\n const [owner, repo] = repositoryFullName.split('/');\n \n if (!owner || !repo) {\n console.error(`Invalid repository full name: ${repositoryFullName}`);\n return null;\n }\n \n return {\n token: accessToken,\n repositoryFullName,\n owner,\n repo\n };\n } catch (error) {\n console.error('Error getting GitHub token for project:', error);\n return null;\n }\n}\n\n/**\n * Automatically transition to the next phase when current phase is completed\n * Phase order: analysis -> bug_investigation -> development -> communication\n * @param sessionId - The AI session UUID\n * @param currentPhase - The phase that just completed (optional, auto-detect if not provided)\n */\nasync function transitionToNextPhase(sessionId: string, currentPhase?: string): Promise<void> {\n try {\n const now = new Date();\n \n // Define phase order\n const phaseOrder = ['analysis', 'bug_investigation', 'development', 'communication'];\n \n // Get all phases for this session\n const { data: allPhases, error: fetchError } = await supabase\n .from('ai_time_logs')\n .select('*')\n .eq('ai_session_id', sessionId)\n .order('activity_type');\n \n if (fetchError || !allPhases) {\n console.error('Failed to fetch phases for transition:', fetchError);\n return;\n }\n \n // Find current active phase if not provided\n let currentPhaseType = currentPhase;\n if (!currentPhaseType) {\n const activePhase = allPhases.find(p => p.status === 'in_progress');\n currentPhaseType = activePhase?.activity_type;\n }\n \n // If no current phase found, start with analysis\n if (!currentPhaseType) {\n const analysisPhase = allPhases.find(p => p.activity_type === 'analysis');\n if (analysisPhase && analysisPhase.status === 'pending' && analysisPhase.estimated_duration_seconds > 0) {\n await supabase\n .from('ai_time_logs')\n .update({\n status: 'in_progress',\n started_at: now.toISOString()\n })\n .eq('id', analysisPhase.id);\n console.error('āœ… Started analysis phase');\n }\n return;\n }\n \n // Complete current phase if it's still in progress\n const currentPhaseRecord = allPhases.find(p => p.activity_type === currentPhaseType && p.status === 'in_progress');\n if (currentPhaseRecord) {\n const duration = Math.round((now.getTime() - new Date(currentPhaseRecord.started_at).getTime()) / 1000);\n await supabase\n .from('ai_time_logs')\n .update({\n status: 'completed',\n ended_at: now.toISOString(),\n duration_seconds: duration\n })\n .eq('id', currentPhaseRecord.id);\n console.error(`āœ… Completed phase: ${currentPhaseType} (${duration}s)`);\n }\n \n // Find next phase in order\n const currentIndex = phaseOrder.indexOf(currentPhaseType);\n if (currentIndex === -1 || currentIndex === phaseOrder.length - 1) {\n console.error('No next phase to transition to');\n return;\n }\n \n // Look for the next valid phase (skip phases with 0 estimated time)\n for (let i = currentIndex + 1; i < phaseOrder.length; i++) {\n const nextPhaseType = phaseOrder[i];\n const nextPhase = allPhases.find(p => p.activity_type === nextPhaseType);\n \n if (!nextPhase) continue;\n \n // Skip phases with 0 estimated time\n if (nextPhase.estimated_duration_seconds === 0) {\n await supabase\n .from('ai_time_logs')\n .update({ status: 'skipped' })\n .eq('id', nextPhase.id);\n console.error(`ā­ļø Skipped phase: ${nextPhaseType} (0 minutes estimated)`);\n continue;\n }\n \n // Start the next phase\n if (nextPhase.status === 'pending') {\n await supabase\n .from('ai_time_logs')\n .update({\n status: 'in_progress',\n started_at: now.toISOString()\n })\n .eq('id', nextPhase.id);\n console.error(`āœ… Started next phase: ${nextPhaseType}`);\n return;\n }\n }\n \n console.error('All remaining phases skipped or completed');\n } catch (error) {\n console.error('Error transitioning to next phase:', error);\n }\n}\n\n// MCP Server setup\nconst server = new Server(\n {\n name: 'mg-tickets-mcp-bridge',\n version: '2.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, including all attachments, comments, and images. Images from ticket attachments and comment attachments are automatically downloaded and returned as base64-encoded content that can be analyzed by AI.',\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 tracking (time breakdown provided by Cursor AI)',\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 timeBreakdown: {\n type: 'object',\n description: 'Time estimate breakdown by development phase (REQUIRED)',\n properties: {\n analysisMinutes: { type: 'number', description: 'Ticket/context analysis time' },\n investigationMinutes: { type: 'number', description: 'Bug investigation/reproduction (0 if not a bug)' },\n developmentMinutes: { type: 'number', description: 'Actual coding/fixing time' },\n communicationMinutes: { type: 'number', description: 'Customer response writing time' }\n },\n required: ['analysisMinutes', 'investigationMinutes', 'developmentMinutes', 'communicationMinutes']\n },\n complexityScore: {\n type: 'number',\n minimum: 1,\n maximum: 10,\n description: 'Estimated complexity from 1-10'\n }\n },\n required: ['ticketId', 'timeBreakdown']\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 estimatedMinutes: { \n type: 'number',\n description: 'Estimated time needed for this follow-up work (think as senior dev WITHOUT AI, in minutes)'\n },\n workDescription: {\n type: 'string',\n description: 'Detailed work description generated by AI (2-3 sentences, summarizing all work done in session including follow-ups)'\n }\n },\n required: ['aiSessionId', 'originalPrompt', 'aiResponse', 'developerFollowUp', 'followUpReason', 'estimatedMinutes', 'workDescription']\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: '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 name: 'get-completion-context',\n description: 'Get all context needed for Cursor AI to generate customer response',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n includeFollowUps: { type: 'boolean', default: true },\n includeTimeMetrics: { type: 'boolean', default: true },\n includeTodos: { type: 'boolean', default: true }\n },\n required: ['aiSessionId']\n }\n },\n {\n name: 'save-customer-response',\n description: 'Save customer response generated by Cursor AI',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n customerResponse: { type: 'string', description: 'Customer response generated by Cursor AI' },\n responseType: { \n type: 'string', \n enum: ['completion', 'progress_update', 'needs_clarification'],\n default: 'completion'\n }\n },\n required: ['aiSessionId', 'customerResponse']\n }\n },\n {\n name: 'complete-ai-session',\n description: 'Complete AI session with work summary - time calculated automatically',\n inputSchema: {\n type: 'object',\n properties: {\n aiSessionId: { type: 'string' },\n workCompleted: {\n type: 'array',\n items: { type: 'string' },\n description: 'List of completed tasks/todos in English'\n },\n technicalSummary: {\n type: 'string',\n description: 'Technical summary of work done in English'\n },\n invoiceDescription: {\n type: 'string',\n description: 'Short invoice-friendly description in the language of the ticket (2-3 sentences max, suitable for billing)'\n },\n efficiencyNotes: { type: 'string' }\n },\n required: ['aiSessionId', 'workCompleted']\n }\n },\n {\n name: 'log-hours',\n description: 'Analyze current chat conversation and log hours as draft tracker entry. AI analyzes chat context to estimate hours as a senior developer would (without AI assistance). Cursor AI matches workspace name to correct project from list (optional).',\n inputSchema: {\n type: 'object',\n properties: {\n projectId: {\n type: 'string',\n description: 'Project ID (UUID) - Optional. Cursor AI should call get-projects first to try matching workspace name. If no clear match, omit this field.'\n },\n ticketId: {\n type: 'string',\n description: 'Ticket ID (UUID) - Optional. Cursor AI should call get-tickets (filtered by project) to try matching chat context to an open ticket. Only include if a clear match is found.'\n },\n aiSessionId: {\n type: 'string',\n description: 'AI Session ID - Optional. If a ticket has an active AI dev session, include this ID to link the hours to that session.'\n },\n workDescription: {\n type: 'string',\n description: 'Short description of the work done (for the tracker entry)'\n },\n estimatedHours: {\n type: 'number',\n description: 'AI-estimated hours as senior developer would spend WITHOUT AI (e.g., 2.5 for 2.5 hours)'\n },\n chatContextSummary: {\n type: 'string',\n description: 'Brief summary of chat context for internal logging (optional)'\n }\n },\n required: ['workDescription', 'estimatedHours']\n }\n },\n // === GITHUB TOOLS ===\n {\n name: 'get-github-file',\n description: 'Get the contents of a specific file from a GitHub repository. Use this after finding relevant files to read their full content.',\n inputSchema: {\n type: 'object',\n properties: {\n projectId: { \n type: 'string', \n description: 'Project ID (UUID)' \n },\n filePath: { \n type: 'string', \n description: 'Full path to the file in the repository (e.g., \"src/components/Button.tsx\")' \n },\n ref: {\n type: 'string',\n description: 'Optional: Git reference (branch, tag, or commit SHA). Defaults to repository default branch.'\n }\n },\n required: ['projectId', 'filePath']\n }\n },\n {\n name: 'list-github-directory',\n description: 'List files and directories in a GitHub repository directory. Use this to explore repository structure.',\n inputSchema: {\n type: 'object',\n properties: {\n projectId: { \n type: 'string', \n description: 'Project ID (UUID)' \n },\n directoryPath: { \n type: 'string', \n description: 'Path to directory (e.g., \"src/components\"). Use empty string or \"/\" for root directory.' \n },\n ref: {\n type: 'string',\n description: 'Optional: Git reference (branch, tag, or commit SHA). Defaults to repository default branch.'\n }\n },\n required: ['projectId', 'directoryPath']\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// Helper function to update phase transitions\n// DEPRECATED: Use transitionToNextPhase instead\n// This function is kept for backward compatibility but now delegates to transitionToNextPhase\nasync function updatePhaseTransition(\n sessionId: string, \n fromPhase: string, \n toPhase: string\n): Promise<void> {\n // Use the new automatic transition system that handles all phases correctly\n await transitionToNextPhase(sessionId, fromPhase);\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 // Get all accessible team IDs (own team + child teams)\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\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 .in('team_id', teamIds)\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 // Get ticket data - include tickets from provider's team AND child customer teams\n const { data: ticketData, 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 .single();\n \n if (error) throw error;\n \n // Check if user has access to this ticket (own team or child team)\n const { data: teamAccess } = await supabase\n .from('teams')\n .select('id')\n .or(`id.eq.${ticketData.team_id},parent_team_id.eq.${authContext.teamId}`)\n .eq('id', ticketData.team_id)\n .single();\n \n if (!teamAccess && ticketData.team_id !== authContext.teamId) {\n throw new Error('Access denied: You do not have permission to view this ticket');\n }\n \n const data = ticketData;\n \n // Get ticket attachments (no team filter needed - already validated ticket access)\n const { data: attachments, error: attachmentsError } = await supabase\n .from('ticket_attachments')\n .select(`\n id,\n file_name,\n file_size,\n mime_type,\n storage_key,\n created_at,\n users:user_id(id, full_name)\n `)\n .eq('ticket_id', id)\n .order('created_at', { ascending: true });\n \n if (attachmentsError) {\n console.error('Error fetching attachments:', attachmentsError);\n }\n \n // Get ticket comments\n const { data: comments, error: commentsError } = await supabase\n .from('ticket_comments')\n .select(`\n id,\n content,\n created_at,\n users:user_id(id, full_name)\n `)\n .eq('ticket_id', id)\n .order('created_at', { ascending: true });\n \n if (commentsError) {\n console.error('Error fetching comments:', commentsError);\n }\n \n // Get comment attachments (no team filter needed - already validated ticket access)\n const commentIds = comments?.map(c => c.id) || [];\n let commentAttachments: any[] = [];\n \n if (commentIds.length > 0) {\n const { data: commAttachments, error: commAttachmentsError } = await supabase\n .from('ticket_comment_attachments')\n .select(`\n id,\n comment_id,\n file_name,\n file_size,\n mime_type,\n storage_key,\n created_at\n `)\n .in('comment_id', commentIds);\n \n if (commAttachmentsError) {\n console.error('Error fetching comment attachments:', commAttachmentsError);\n } else {\n commentAttachments = commAttachments || [];\n }\n }\n \n // Build content array starting with text\n const content: any[] = [{\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 `${attachments && attachments.length > 0 ? `\\nšŸ“Ž Attachments: ${attachments.length}\\n` : ''}` +\n `${comments && comments.length > 0 ? `šŸ’¬ Comments: ${comments.length}\\n` : ''}`\n }];\n \n // Process ticket attachments - download images\n if (attachments && attachments.length > 0) {\n console.error(`šŸ“Ž Processing ${attachments.length} ticket attachments...`);\n \n for (const attachment of attachments) {\n if (isImageFile(attachment.mime_type)) {\n console.error(`šŸ–¼ļø Downloading image: ${attachment.file_name}`);\n const base64Data = await downloadImageAsBase64(attachment.storage_key);\n \n if (base64Data) {\n content.push({\n type: 'image',\n data: base64Data,\n mimeType: attachment.mime_type\n });\n \n // Add text context about the image\n content.push({\n type: 'text',\n text: `\\nšŸ“ø **Image from ticket**: ${attachment.file_name} (${Math.round(attachment.file_size / 1024)}KB, uploaded by ${(attachment.users as any)?.full_name || 'Unknown'} on ${new Date(attachment.created_at).toLocaleDateString()})\\n`\n });\n }\n }\n }\n }\n \n // Process comment attachments - download images\n if (commentAttachments.length > 0) {\n console.error(`šŸ“Ž Processing ${commentAttachments.length} comment attachments...`);\n \n for (const attachment of commentAttachments) {\n if (isImageFile(attachment.mime_type)) {\n console.error(`šŸ–¼ļø Downloading comment image: ${attachment.file_name}`);\n const base64Data = await downloadImageAsBase64(attachment.storage_key);\n \n if (base64Data) {\n // Find the comment this attachment belongs to\n const comment = comments?.find(c => c.id === attachment.comment_id);\n \n content.push({\n type: 'image',\n data: base64Data,\n mimeType: attachment.mime_type\n });\n \n // Add text context about the image\n content.push({\n type: 'text',\n text: `\\nšŸ“ø **Image from comment** by ${(comment?.users as any)?.full_name || 'Unknown'} on ${new Date(attachment.created_at).toLocaleDateString()}: ${attachment.file_name} (${Math.round(attachment.file_size / 1024)}KB)\\n` +\n (comment?.content ? `Comment text: \"${comment.content.substring(0, 100)}${comment.content.length > 100 ? '...' : ''}\"\\n` : '')\n });\n }\n }\n }\n }\n \n console.error(`āœ… Returning ticket with ${content.filter(c => c.type === 'image').length} images`);\n \n return { content };\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 // Get all accessible team IDs (own team + child teams)\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n \n let query = supabase\n .from('customers')\n .select('id, name, email, website, created_at')\n .in('team_id', teamIds)\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 // Get all accessible team IDs (own team + child teams)\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n \n let query = supabase\n .from('projects')\n .select(`\n id,\n name,\n description,\n customer_id,\n created_at\n `)\n .in('team_id', teamIds)\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}** (ID: ${project.id})\\n` +\n `${project.description ? `Description: ${project.description}\\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, timeBreakdown, complexityScore } = args as any;\n \n // Validate timeBreakdown is provided\n if (!timeBreakdown || !timeBreakdown.analysisMinutes || timeBreakdown.developmentMinutes === undefined) {\n throw new Error('timeBreakdown is required with all phases: analysisMinutes, investigationMinutes, developmentMinutes, communicationMinutes');\n }\n \n // Round all time estimates to nearest 15 minutes\n const roundedTimeBreakdown = {\n analysisMinutes: roundToNearest15Minutes(timeBreakdown.analysisMinutes || 0),\n investigationMinutes: roundToNearest15Minutes(timeBreakdown.investigationMinutes || 0),\n developmentMinutes: roundToNearest15Minutes(timeBreakdown.developmentMinutes || 0),\n communicationMinutes: roundToNearest15Minutes(timeBreakdown.communicationMinutes || 0)\n };\n \n // Calculate total time from rounded breakdown\n const totalEstimateMinutes = \n roundedTimeBreakdown.analysisMinutes +\n roundedTimeBreakdown.investigationMinutes +\n roundedTimeBreakdown.developmentMinutes +\n roundedTimeBreakdown.communicationMinutes;\n \n const sessionStartTime = new Date();\n \n // Create AI session with calculated total\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: totalEstimateMinutes,\n complexity_score: complexityScore || null,\n status: 'in_progress'\n })\n .select('id, ticket_id, cursor_session_id, created_at')\n .single();\n \n if (error) throw error;\n \n // CREATE PHASE TIME LOGS: Store breakdown as separate phase activities\n const phaseActivities = [\n {\n ai_session_id: sessionData.id,\n activity_type: 'analysis',\n description: 'Ticket analysis and context understanding',\n duration_seconds: 0,\n estimated_duration_seconds: roundedTimeBreakdown.analysisMinutes * 60,\n status: 'in_progress', // Analysis starts immediately\n productivity_score: 8,\n started_at: sessionStartTime.toISOString()\n },\n {\n ai_session_id: sessionData.id,\n activity_type: 'bug_investigation',\n description: 'Bug investigation and root cause analysis',\n duration_seconds: 0,\n estimated_duration_seconds: roundedTimeBreakdown.investigationMinutes * 60,\n status: 'pending',\n productivity_score: null\n },\n {\n ai_session_id: sessionData.id,\n activity_type: 'development',\n description: 'Implementation and coding',\n duration_seconds: 0,\n estimated_duration_seconds: roundedTimeBreakdown.developmentMinutes * 60,\n status: 'pending',\n productivity_score: null\n },\n {\n ai_session_id: sessionData.id,\n activity_type: 'communication',\n description: 'Customer response and documentation',\n duration_seconds: 0,\n estimated_duration_seconds: roundedTimeBreakdown.communicationMinutes * 60,\n status: 'pending',\n productivity_score: null\n }\n ];\n \n // Insert all phase activities\n await supabase.from('ai_time_logs').insert(phaseActivities);\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 `\\nšŸ“Š **Time Breakdown:**\\n` +\n ` • Analysis: ${roundedTimeBreakdown.analysisMinutes} min\\n` +\n ` • Investigation: ${roundedTimeBreakdown.investigationMinutes} min\\n` +\n ` • Development: ${roundedTimeBreakdown.developmentMinutes} min\\n` +\n ` • Communication: ${roundedTimeBreakdown.communicationMinutes} min\\n` +\n ` • **Total: ${totalEstimateMinutes} min**\\n\\n` +\n `${complexityScore ? `šŸŽÆ Complexity: ${complexityScore}/10\\n` : ''}` +\n `ā±ļø **Phase Tracking Started** (Analysis in progress)\\n` +\n `${cursorSessionId ? `šŸ”— Cursor Session: ${cursorSessionId}\\n` : ''}` +\n `šŸ“… Started: ${sessionStartTime.toLocaleString()}\\n\\n` +\n `āœ… Session initialized with phase breakdown!\\n` +\n `šŸ“ Timetrack entry will be created when you complete the session.`\n }]\n };\n }\n \n case 'track-manual-follow-up': {\n const { aiSessionId, originalPrompt, aiResponse, developerFollowUp, followUpReason, outcome = 'success', estimatedMinutes, workDescription } = 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 and current session data\n // Find the session - get all sessions for accessible teams and filter in JS\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id, status, created_at, ai_time_estimate_minutes')\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n \n const followUpTime = new Date();\n \n // Store old estimate for reporting\n const oldEstimate = session.ai_time_estimate_minutes || 60;\n \n // Round follow-up estimate to nearest 15 minutes\n const roundedFollowUpMinutes = roundToNearest15Minutes(estimatedMinutes || 0);\n \n // Calculate new estimate: add rounded follow-up estimate to existing estimate\n const newEstimate = oldEstimate + roundedFollowUpMinutes;\n \n // RESTART SESSION & UPDATE ESTIMATE: Set status back to in_progress and adjust time estimate\n await supabase\n .from('ai_sessions')\n .update({\n status: 'in_progress', // Restart active tracking\n ai_time_estimate_minutes: newEstimate, // Increase estimate based on follow-up work\n // Don't update completed_at - session continues\n })\n .eq('id', session.id);\n \n // LOG FOLLOW-UP: Track the manual follow-up interaction\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: null, // Calculated automatically from session timestamps\n resolved_at: outcome === 'success' ? new Date().toISOString() : null\n })\n .select()\n .single();\n \n if (error) throw error;\n \n // RESTART TIME TRACKING: Log follow-up activity start (duration calculated at completion)\n await supabase\n .from('ai_time_logs')\n .insert({\n ai_session_id: session.id,\n activity_type: 'debugging', // Follow-ups are typically debugging/fixing\n description: `Follow-up: ${followUpReason.replace('_', ' ')} - ${outcome}`,\n duration_seconds: 0, // Duration calculated automatically from timestamps\n productivity_score: outcome === 'success' ? 9 : outcome === 'partial_success' ? 6 : 4,\n started_at: followUpTime.toISOString()\n });\n \n // CALCULATE CURRENT EFFICIENCY: Compare time spent vs NEW estimated time\n const sessionStartTime = new Date(session.created_at);\n const totalMinutesElapsed = Math.round((followUpTime.getTime() - sessionStartTime.getTime()) / 60000);\n const currentEfficiency = totalMinutesElapsed > 0 ? (totalMinutesElapsed / newEstimate) : 1;\n \n // UPDATE EFFICIENCY TRACKING: Update running efficiency score with adjusted estimate\n await supabase\n .from('ai_sessions')\n .update({\n efficiency_score: currentEfficiency.toFixed(2),\n actual_time_minutes: totalMinutesElapsed\n })\n .eq('id', session.id);\n \n // CHECK FOR EXISTING AGENDA ENTRY: Check if there's already a draft tracker entry for this session\n const { data: existingEntry, error: entryError } = await supabase\n .from('agenda_events')\n .select('id, tracked_duration, title, description, start_time')\n .eq('ai_session_id', session.id)\n .eq('status', 'draft')\n .single();\n \n let trackerAction = '';\n let trackerDetails = '';\n \n if (existingEntry && !entryError) {\n // UPDATE EXISTING TRACKER: Add follow-up time to existing entry\n const newDuration = (existingEntry.tracked_duration || 0) + (roundedFollowUpMinutes * 60);\n \n await supabase\n .from('agenda_events')\n .update({\n tracked_duration: newDuration,\n end_time: followUpTime.toISOString(),\n title: workDescription,\n description: workDescription\n })\n .eq('id', existingEntry.id);\n \n trackerAction = 'Updated existing tracker';\n trackerDetails = ` • Total tracked time: ${Math.round(newDuration / 60)} minutes (+${roundedFollowUpMinutes} min)\\n` +\n ` • Description: ${workDescription}\\n`;\n } else {\n // CREATE NEW TRACKER: First follow-up or no tracker exists yet\n const durationSeconds = roundedFollowUpMinutes * 60;\n const startTime = new Date(followUpTime.getTime() - durationSeconds * 1000);\n \n await supabase\n .from('agenda_events')\n .insert({\n team_id: authContext.teamId,\n user_id: authContext.userId,\n ai_session_id: session.id,\n title: workDescription,\n description: workDescription,\n start_time: startTime.toISOString(),\n end_time: followUpTime.toISOString(),\n type: 'work',\n status: 'draft',\n all_day: false,\n is_tracked: true,\n tracked_duration: durationSeconds\n });\n \n trackerAction = 'Created new tracker';\n trackerDetails = ` • Tracked time: ${roundedFollowUpMinutes} minutes\\n` +\n ` • Description: ${workDescription}\\n`;\n }\n \n return {\n content: [{\n type: 'text',\n text: `šŸ”„ **Follow-up Tracked & Session Restarted!**\\n\\n` +\n `šŸ†” Session: ${aiSessionId} (back to active)\\n` +\n `šŸ” Reason: ${followUpReason.replace('_', ' ')}\\n` +\n `āœ… Outcome: ${outcome}\\n` +\n `\\nšŸ“Š **Time Estimate Updated:**\\n` +\n ` • Old estimate: ${oldEstimate} minutes\\n` +\n ` • Follow-up estimate: +${roundedFollowUpMinutes} minutes (rounded to 15min)\\n` +\n ` • New estimate: ${newEstimate} minutes\\n` +\n `\\nšŸ“ˆ **Current Progress:**\\n` +\n ` • Total time elapsed: ${totalMinutesElapsed} minutes\\n` +\n ` • Efficiency: ${currentEfficiency < 1 ? 'šŸš€ ' : currentEfficiency > 1.5 ? 'āš ļø ' : 'ā±ļø '}${(currentEfficiency * 100).toFixed(0)}%\\n` +\n `\\nā±ļø **Tracker Entry: ${trackerAction}**\\n` +\n trackerDetails +\n `\\n⚔ **Time tracking resumed** - continue with confidence!`\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 - find by JavaScript filtering\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await 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 .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\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 - get all sessions for accessible teams and filter in JS\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\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 // AUTOMATIC PHASE TRANSITION\n let phaseTransition: string | null = null;\n \n // Get all current todos for this session\n const { data: currentTodos } = await supabase\n .from('ai_todos')\n .select('status')\n .eq('ai_session_id', session.id);\n \n if (currentTodos && currentTodos.length > 0) {\n const hasInProgress = currentTodos.some(t => t.status === 'in_progress');\n const allCompleted = currentTodos.every(t => t.status === 'completed');\n \n // Get current phase status\n const { data: currentPhase } = await supabase\n .from('ai_time_logs')\n .select('activity_type, status')\n .eq('ai_session_id', session.id)\n .eq('status', 'in_progress')\n .single();\n \n // Analysis → Next Phase: When first todo moves to in_progress (work starts)\n if (hasInProgress && currentPhase?.activity_type === 'analysis') {\n await transitionToNextPhase(session.id, 'analysis');\n phaseTransition = 'Analysis completed → Next phase started (Investigation/Development)';\n }\n \n // Investigation → Development: When todos progress during investigation phase\n // This typically happens after initial analysis, when actual coding begins\n if (hasInProgress && currentPhase?.activity_type === 'bug_investigation') {\n // Check if any development-related work has started (indicated by todo progress)\n const completedCount = currentTodos.filter(t => t.status === 'completed').length;\n if (completedCount > 0) {\n // Some work completed, likely moving from investigation to actual fixing\n await transitionToNextPhase(session.id, 'bug_investigation');\n phaseTransition = 'Investigation completed → Development phase started';\n }\n }\n \n // Development → Communication: When all todos are completed (implementation done)\n if (allCompleted && currentPhase?.activity_type === 'development') {\n await transitionToNextPhase(session.id, 'development');\n phaseTransition = 'Development completed → Communication phase started';\n }\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 `${phaseTransition ? `šŸ”„ Phase Transition: ${phaseTransition}\\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 - get all sessions for accessible teams and filter in JS\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\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 '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 // First find the session\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: findError } = await supabase\n .from('ai_sessions')\n .select('id')\n .in('team_id', teamIds);\n \n if (findError) {\n throw new Error(`Database error: ${findError.message}`);\n }\n \n const foundSession = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!foundSession) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n \n // Now update the found 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('id', foundSession.id)\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 case 'get-completion-context': {\n const { aiSessionId, includeFollowUps = true, includeTimeMetrics = true, includeTodos = true } = 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 ticket info\n // Get comprehensive session context - find by JavaScript filtering\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select(`\n id,\n ticket_id,\n ai_time_estimate_minutes,\n actual_time_minutes,\n efficiency_score,\n created_at,\n completed_at,\n status,\n complexity_score\n `)\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n \n // Get ticket data\n const { data: ticket, error: ticketError } = await supabase\n .from('tickets')\n .select('ticket_number, title, description, type, priority')\n .eq('id', session.ticket_id)\n .single();\n \n if (ticketError || !ticket) {\n throw new Error('Ticket not found for session');\n }\n \n let contextData: any = {\n session: {\n id: aiSessionId,\n status: session.status,\n complexity: session.complexity_score,\n createdAt: session.created_at,\n completedAt: session.completed_at\n },\n ticket: {\n number: ticket.ticket_number,\n title: ticket.title,\n description: ticket.description,\n type: ticket.type,\n priority: ticket.priority\n }\n };\n \n // Add time metrics if requested\n if (includeTimeMetrics) {\n const timeSaved = session.ai_time_estimate_minutes && session.actual_time_minutes \n ? Math.max(0, session.ai_time_estimate_minutes - session.actual_time_minutes)\n : null;\n \n contextData.timeMetrics = {\n estimatedMinutes: session.ai_time_estimate_minutes,\n actualMinutes: session.actual_time_minutes,\n timeSaved: timeSaved,\n efficiency: session.efficiency_score,\n sessionDuration: session.completed_at && session.created_at \n ? Math.round((new Date(session.completed_at).getTime() - new Date(session.created_at).getTime()) / 60000)\n : null\n };\n }\n \n // Add todos if requested\n if (includeTodos) {\n const { data: todos } = await supabase\n .from('ai_todos')\n .select('content, status, estimated_minutes, actual_minutes, completed_at')\n .eq('ai_session_id', session.id)\n .order('created_at', { ascending: true });\n \n contextData.todos = todos || [];\n }\n \n // Add follow-ups if requested\n if (includeFollowUps) {\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', { ascending: true });\n \n contextData.followUps = followUps || [];\n }\n \n return {\n content: [{\n type: 'text',\n text: `šŸ“‹ **Completion Context Retrieved!**\\n\\n` +\n `šŸŽ« **Ticket:** ${ticket.ticket_number} - ${ticket.title}\\n` +\n `šŸ†” **Session:** ${aiSessionId} (${session.status})\\n` +\n `ā±ļø **Time:** ${session.actual_time_minutes || 'N/A'}/${session.ai_time_estimate_minutes || 'N/A'} minutes\\n` +\n `šŸ“‹ **Todos:** ${contextData.todos?.filter((t: any) => t.status === 'completed').length || 0}/${contextData.todos?.length || 0} completed\\n` +\n `šŸ”„ **Follow-ups:** ${contextData.followUps?.length || 0}\\n\\n` +\n `āœ… **Full context ready for Cursor AI to generate customer response!**\\n\\n` +\n `**Context Data:**\\n\\`\\`\\`json\\n${JSON.stringify(contextData, null, 2)}\\`\\`\\``\n }]\n };\n }\n \n case 'save-customer-response': {\n const { aiSessionId, customerResponse, responseType = 'completion' } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Get session to validate it exists - find by JavaScript filtering\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: sessionError } = await supabase\n .from('ai_sessions')\n .select('id')\n .in('team_id', teamIds);\n \n if (sessionError) {\n throw new Error(`Database error: ${sessionError.message}`);\n }\n \n // Find session with matching prefix\n const session = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!session) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n \n // Save the response in database\n const { data: responseData, error: responseError } = await supabase\n .from('ai_responses')\n .insert({\n ai_session_id: session.id,\n response_type: responseType,\n content: customerResponse,\n is_ready_for_customer: true,\n provider_approved: false // Needs manual approval\n })\n .select()\n .single();\n \n if (responseError) throw responseError;\n \n return {\n content: [{\n type: 'text',\n text: `šŸ’¾ **Customer Response Saved!**\\n\\n` +\n `šŸ†” Session: ${aiSessionId}\\n` +\n `šŸ“ Response Type: ${responseType}\\n` +\n `šŸ“„ Length: ${customerResponse.length} characters\\n\\n` +\n `āœ… **Response ready for provider approval**\\n` +\n `šŸ” Provider can review in AI tab before sending to customer\\n\\n` +\n `**Preview:**\\n\\`\\`\\`\\n${customerResponse.substring(0, 200)}${customerResponse.length > 200 ? '...' : ''}\\`\\`\\``\n }]\n };\n }\n \n case 'complete-ai-session': {\n const { aiSessionId, workCompleted, technicalSummary, invoiceDescription, efficiencyNotes } = args as any;\n \n // Extract actual session UUID from readable ID\n const sessionUuid = aiSessionId.replace('ai-sess-', '');\n \n // Get session to calculate actual time spent - find by JavaScript filtering\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: allSessions, error: getSessionError } = await supabase\n .from('ai_sessions')\n .select('id, ticket_id, ai_time_estimate_minutes, created_at')\n .in('team_id', teamIds);\n \n if (getSessionError) {\n throw new Error(`Database error: ${getSessionError.message}`);\n }\n \n // Find session with matching prefix\n const existingSession = allSessions?.find(s => s.id.toString().startsWith(sessionUuid));\n if (!existingSession) {\n throw new Error(`Session not found: ${aiSessionId} (searched ${allSessions?.length || 0} sessions)`);\n }\n\n // Calculate actual time spent automatically\n const completionTime = new Date();\n const sessionStartTime = new Date(existingSession.created_at);\n const timeSpentMinutes = Math.round((completionTime.getTime() - sessionStartTime.getTime()) / 60000);\n \n // Update session to completed with calculated time\n const { data: session, error: sessionError } = await supabase\n .from('ai_sessions')\n .update({\n status: 'completed',\n actual_time_minutes: timeSpentMinutes,\n completed_at: completionTime.toISOString(),\n efficiency_score: null // Will be calculated\n })\n .eq('id', existingSession.id)\n .select('id, ticket_id, ai_time_estimate_minutes, created_at')\n .single();\n \n if (sessionError || !session) {\n throw new Error(`Failed to update session: ${aiSessionId}`);\n }\n \n // Calculate efficiency score\n const efficiencyScore = session.ai_time_estimate_minutes \n ? (timeSpentMinutes / session.ai_time_estimate_minutes)\n : 1.0;\n \n // Update efficiency score\n await supabase\n .from('ai_sessions')\n .update({ efficiency_score: efficiencyScore.toFixed(2) })\n .eq('id', session.id);\n \n // CLOSE ALL REMAINING ACTIVE PHASES\n const { data: activePhases } = await supabase\n .from('ai_time_logs')\n .select('*')\n .eq('ai_session_id', existingSession.id)\n .eq('status', 'in_progress');\n\n for (const phase of activePhases || []) {\n const duration = Math.round(\n (completionTime.getTime() - new Date(phase.started_at).getTime()) / 1000\n );\n \n await supabase\n .from('ai_time_logs')\n .update({\n ended_at: completionTime.toISOString(),\n duration_seconds: duration,\n status: 'completed'\n })\n .eq('id', phase.id);\n }\n\n // Mark skipped phases (pending with 0 estimated time)\n await supabase\n .from('ai_time_logs')\n .update({ status: 'skipped' })\n .eq('ai_session_id', existingSession.id)\n .eq('status', 'pending')\n .eq('estimated_duration_seconds', 0);\n \n // Get session duration\n const sessionDuration = Math.round(\n (completionTime.getTime() - new Date(session.created_at).getTime()) / 60000\n );\n \n // Create work summary\n const workSummary = `Completed ${workCompleted.length} tasks including: ${workCompleted.slice(0, 3).join(', ')}${workCompleted.length > 3 ? ' and more' : ''}.`;\n \n // Get ticket details for agenda event creation\n const { data: ticketInfo } = await supabase\n .from('tickets')\n .select('ticket_number, title, project_id')\n .eq('id', session.ticket_id)\n .single();\n \n // CREATE AGENDA EVENT: Now that work is complete, create the timetrack entry\n // Use invoice description if provided, otherwise create a technical one\n let completionDescription: string;\n \n if (invoiceDescription) {\n // Use the invoice-friendly description provided by Cursor (in ticket language)\n completionDescription = `${ticketInfo?.ticket_number || 'Ticket'}: ${invoiceDescription}`;\n } else {\n // Fallback: Create a technical work description\n const workDescription = workCompleted.map((task: string, index: number) => `${index + 1}. ${task}`).join('\\n');\n completionDescription = `${ticketInfo?.ticket_number || 'Ticket'}: ${technicalSummary || workSummary}\\n\\nCompleted work:\\n${workDescription}`;\n }\n \n // Create the agenda event with AI estimated time\n // Use the original AI estimate for billing, not the actual AI completion time\n const estimatedMinutes = session.ai_time_estimate_minutes || timeSpentMinutes;\n const sessionStart = new Date(session.created_at);\n const estimatedEnd = new Date(sessionStart.getTime() + estimatedMinutes * 60000);\n \n const { data: agendaEvent, error: agendaError } = await supabase\n .from('agenda_events')\n .insert({\n team_id: authContext.teamId,\n user_id: authContext.userId,\n title: ticketInfo?.title || 'Development Work',\n description: completionDescription,\n start_time: sessionStart.toISOString(),\n end_time: estimatedEnd.toISOString(),\n project_id: ticketInfo?.project_id || null,\n ticket_id: session.ticket_id,\n ai_session_id: session.id, // Use the actual UUID, not the readable ID\n type: 'work',\n status: 'draft', // Mark as draft for manual approval\n all_day: false,\n is_tracked: true,\n tracked_duration: estimatedMinutes * 60 // Use AI estimate in seconds for billing\n })\n .select('id')\n .single();\n \n if (agendaError) {\n console.error('āš ļø Failed to create agenda event:', agendaError);\n // Don't fail the completion if agenda event creation fails\n }\n \n let responseText = `šŸŽ‰ **AI Session Completed Successfully!**\\n\\n`;\n responseText += `šŸ†” Session: ${aiSessionId}\\n`;\n responseText += `šŸ“Š **Performance Summary:**\\n`;\n responseText += ` • Tasks Completed: ${workCompleted.length}\\n`;\n responseText += ` • Time Spent: ${timeSpentMinutes} minutes\\n`;\n responseText += ` • Estimated Time: ${session.ai_time_estimate_minutes || 'N/A'} minutes\\n`;\n responseText += ` • Efficiency: ${efficiencyScore < 1 ? 'šŸš€' : efficiencyScore > 1.5 ? 'āš ļø' : 'ā±ļø'} ${(efficiencyScore * 100).toFixed(0)}%\\n`;\n responseText += ` • Session Duration: ${sessionDuration} minutes\\n\\n`;\n \n responseText += `āœ… **Work Completed:**\\n`;\n workCompleted.forEach((task: string, index: number) => {\n responseText += `${index + 1}. ${task}\\n`;\n });\n responseText += `\\n`;\n \n if (technicalSummary) {\n responseText += `šŸ”§ **Technical Summary:**\\n${technicalSummary}\\n\\n`;\n }\n \n if (efficiencyNotes) {\n responseText += `šŸ“ˆ **Efficiency Notes:**\\n${efficiencyNotes}\\n\\n`;\n }\n \n if (agendaEvent) {\n responseText += `šŸ“… **Timetrack Entry Created:**\\n`;\n responseText += ` • Agenda event created with work summary\\n`;\n responseText += ` • Status: DRAFT (requires approval in agenda)\\n`;\n responseText += ` • Duration: ${timeSpentMinutes} minutes\\n`;\n responseText += ` • Period: ${sessionStart.toLocaleString()} - ${completionTime.toLocaleString()}\\n\\n`;\n }\n \n // Provide context for Cursor AI to generate customer response\n responseText += `šŸ“‹ **Context for Customer Response:**\\n`;\n responseText += ` • Use \"get-completion-context\" to retrieve full context\\n`;\n responseText += ` • Generate customer-friendly response based on completed work\\n`;\n responseText += ` • Focus on business value and customer benefits\\n\\n`;\n \n responseText += `šŸŽÆ **Session archived successfully!**`;\n \n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n }\n \n case 'log-hours': {\n const { projectId, ticketId, aiSessionId, workDescription, estimatedHours, chatContextSummary } = args as any;\n \n let project = null;\n let ticket = null;\n let aiSession = null;\n \n // Verify project access if projectId is provided\n if (projectId) {\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: projectData, error: projectError } = await supabase\n .from('projects')\n .select('id, name, team_id')\n .eq('id', projectId)\n .in('team_id', teamIds)\n .single();\n \n if (projectError || !projectData) {\n throw new Error(`Project not found or no access: ${projectId}. Please call get-projects first to find the correct project.`);\n }\n \n project = projectData;\n }\n \n // Verify ticket access if ticketId is provided\n if (ticketId) {\n const teamIds = await getAccessibleTeamIds(authContext.teamId);\n const { data: ticketData, error: ticketError } = await supabase\n .from('tickets')\n .select('id, title, status')\n .eq('id', ticketId)\n .in('team_id', teamIds)\n .single();\n \n if (ticketError || !ticketData) {\n throw new Error(`Ticket not found or no access: ${ticketId}. Please call get-tickets first to find the correct ticket.`);\n }\n \n ticket = ticketData;\n }\n \n // Verify AI session if aiSessionId is provided\n if (aiSessionId) {\n const { data: sessionData, error: sessionError } = await supabase\n .from('ai_dev_sessions')\n .select('id, ticket_id, status')\n .eq('id', aiSessionId)\n .single();\n \n if (sessionError || !sessionData) {\n throw new Error(`AI Session not found: ${aiSessionId}.`);\n }\n \n aiSession = sessionData;\n }\n \n // Convert hours to seconds for agenda_events.tracked_duration\n const durationSeconds = Math.round(estimatedHours * 3600);\n \n // Create agenda event as time tracking entry (draft)\n const now = new Date();\n const startTime = new Date(now.getTime() - durationSeconds * 1000); // Back-calculate start time\n \n const { data: agendaEntry, error: agendaError } = await supabase\n .from('agenda_events')\n .insert({\n team_id: authContext.teamId,\n user_id: authContext.userId,\n project_id: project?.id || null,\n ticket_id: ticket?.id || null,\n ai_session_id: aiSession?.id || null,\n title: workDescription,\n description: chatContextSummary || workDescription,\n start_time: startTime.toISOString(),\n end_time: now.toISOString(),\n type: 'work',\n status: 'draft',\n all_day: false,\n is_tracked: true,\n tracked_duration: durationSeconds\n })\n .select('id, tracked_duration, project_id, ticket_id, ai_session_id')\n .single();\n \n if (agendaError || !agendaEntry) {\n throw new Error(`Failed to create time entry: ${agendaError?.message || 'Unknown error'}`);\n }\n \n let responseText = `ā±ļø **Hours Logged Successfully!**\\n\\n`;\n responseText += `šŸ“‹ **Entry Details:**\\n`;\n if (project) {\n responseText += ` • Project: ${project.name}\\n`;\n } else {\n responseText += ` • Project: (No project assigned)\\n`;\n }\n if (ticket) {\n responseText += ` • Ticket: ${ticket.title} (${ticket.status})\\n`;\n }\n if (aiSession) {\n responseText += ` • AI Session: ${aiSession.id} (${aiSession.status})\\n`;\n }\n responseText += ` • Description: ${workDescription}\\n`;\n responseText += ` • Estimated Hours: ${estimatedHours}h (${Math.floor(estimatedHours)}h ${Math.round((estimatedHours % 1) * 60)}m)\\n`;\n responseText += ` • Status: DRAFT (not billed yet)\\n`;\n responseText += ` • Entry ID: ${agendaEntry.id}\\n\\n`;\n \n if (chatContextSummary) {\n responseText += `šŸ“Š **Work Context:**\\n`;\n responseText += `${chatContextSummary.substring(0, 200)}${chatContextSummary.length > 200 ? '...' : ''}\\n\\n`;\n }\n \n responseText += `āœ… Time entry created and ready for review in the agenda!`;\n \n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n }\n \n // === GITHUB TOOLS ===\n case 'get-github-file': {\n const { projectId, filePath, ref } = args as any;\n \n // Get GitHub token for project\n const githubInfo = await getGithubTokenForProject(projectId, authContext.teamId);\n if (!githubInfo) {\n return {\n content: [{\n type: 'text',\n text: 'āŒ GitHub not configured for this project.'\n }]\n };\n }\n \n try {\n const octokit = new Octokit({ auth: githubInfo.token });\n \n console.error(`šŸ“„ Reading file: ${filePath} from ${githubInfo.repositoryFullName}`);\n \n const { data } = await octokit.rest.repos.getContent({\n owner: githubInfo.owner,\n repo: githubInfo.repo,\n path: filePath,\n ref: ref\n });\n \n // Check if it's a file (not directory)\n if (Array.isArray(data) || data.type !== 'file') {\n return {\n content: [{\n type: 'text',\n text: `āŒ \"${filePath}\" is not a file or contains multiple items.`\n }]\n };\n }\n \n // Decode base64 content\n const content = Buffer.from(data.content, 'base64').toString('utf-8');\n \n let responseText = `šŸ“„ **File: ${filePath}**\\n`;\n responseText += `Repository: ${githubInfo.repositoryFullName}\\n`;\n responseText += `Size: ${data.size} bytes\\n`;\n responseText += `URL: ${data.html_url}\\n\\n`;\n responseText += `**Content:**\\n\\`\\`\\`\\n${content}\\n\\`\\`\\``;\n \n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n } catch (error: any) {\n console.error('GitHub get file error:', error);\n \n if (error.status === 404) {\n return {\n content: [{\n type: 'text',\n text: `āŒ File not found: ${filePath}`\n }]\n };\n }\n \n return {\n content: [{\n type: 'text',\n text: `āŒ Failed to read file: ${error.message || 'Unknown error'}`\n }]\n };\n }\n }\n \n case 'list-github-directory': {\n const { projectId, directoryPath, ref } = args as any;\n \n // Get GitHub token for project\n const githubInfo = await getGithubTokenForProject(projectId, authContext.teamId);\n if (!githubInfo) {\n return {\n content: [{\n type: 'text',\n text: 'āŒ GitHub not configured for this project.'\n }]\n };\n }\n \n try {\n const octokit = new Octokit({ auth: githubInfo.token });\n \n // Normalize directory path (empty string or \"/\" for root)\n const normalizedPath = (!directoryPath || directoryPath === '/') ? '' : directoryPath;\n \n console.error(`šŸ“ Listing directory: ${normalizedPath || '(root)'} in ${githubInfo.repositoryFullName}`);\n \n const { data } = await octokit.rest.repos.getContent({\n owner: githubInfo.owner,\n repo: githubInfo.repo,\n path: normalizedPath,\n ref: ref\n });\n \n // Check if it's a directory\n if (!Array.isArray(data)) {\n return {\n content: [{\n type: 'text',\n text: `āŒ \"${directoryPath}\" is not a directory.`\n }]\n };\n }\n \n let responseText = `šŸ“ **Directory: ${directoryPath || '(root)'}**\\n`;\n responseText += `Repository: ${githubInfo.repositoryFullName}\\n`;\n responseText += `Items: ${data.length}\\n\\n`;\n \n // Group by type\n const directories = data.filter(item => item.type === 'dir');\n const files = data.filter(item => item.type === 'file');\n \n if (directories.length > 0) {\n responseText += `**šŸ“ Directories (${directories.length}):**\\n`;\n for (const dir of directories) {\n responseText += ` - ${dir.name}/\\n`;\n }\n responseText += `\\n`;\n }\n \n if (files.length > 0) {\n responseText += `**šŸ“„ Files (${files.length}):**\\n`;\n for (const file of files) {\n responseText += ` - ${file.name} (${file.size} bytes)\\n`;\n }\n }\n \n return {\n content: [{\n type: 'text',\n text: responseText\n }]\n };\n } catch (error: any) {\n console.error('GitHub list directory error:', error);\n \n if (error.status === 404) {\n return {\n content: [{\n type: 'text',\n text: `āŒ Directory not found: ${directoryPath}`\n }]\n };\n }\n \n return {\n content: [{\n type: 'text',\n text: `āŒ Failed to list directory: ${error.message || 'Unknown error'}`\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 teamIds = await getAccessibleTeamIds(authContext!.teamId);\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 .in('team_id', teamIds)\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 teamIds = await getAccessibleTeamIds(authContext!.teamId);\n const { data, error } = await supabase\n .from('customers')\n .select('id, name, email, website, created_at')\n .in('team_id', teamIds)\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 teamIds = await getAccessibleTeamIds(authContext!.teamId);\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 .in('team_id', teamIds)\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.18.0",
3
+ "version": "2.18.2",
4
4
  "description": "MCP Server bridge for MG Tickets - connects Cursor to HTTP MCP server with image support and GitHub code exploration",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",