@app-connect/core 1.7.25 → 1.7.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (138) hide show
  1. package/.env.test +5 -5
  2. package/README.md +441 -441
  3. package/connector/developerPortal.js +31 -31
  4. package/connector/mock.js +84 -77
  5. package/connector/proxy/engine.js +164 -164
  6. package/connector/proxy/index.js +500 -500
  7. package/connector/registry.js +252 -252
  8. package/docs/README.md +50 -50
  9. package/docs/architecture.md +93 -93
  10. package/docs/connectors.md +116 -116
  11. package/docs/handlers.md +125 -125
  12. package/docs/libraries.md +101 -101
  13. package/docs/models.md +144 -144
  14. package/docs/routes.md +115 -115
  15. package/docs/tests.md +73 -73
  16. package/handlers/admin.js +523 -523
  17. package/handlers/appointment.js +193 -0
  18. package/handlers/auth.js +320 -296
  19. package/handlers/calldown.js +99 -99
  20. package/handlers/contact.js +280 -280
  21. package/handlers/disposition.js +82 -80
  22. package/handlers/log.js +990 -973
  23. package/handlers/managedAuth.js +446 -446
  24. package/handlers/managedOAuth.js +247 -0
  25. package/handlers/plugin.js +208 -208
  26. package/handlers/user.js +142 -142
  27. package/index.js +3162 -2652
  28. package/jest.config.js +56 -56
  29. package/lib/analytics.js +54 -54
  30. package/lib/authSession.js +109 -109
  31. package/lib/cacheCleanup.js +21 -0
  32. package/lib/callLogComposer.js +898 -898
  33. package/lib/callLogLookup.js +34 -0
  34. package/lib/constants.js +8 -8
  35. package/lib/debugTracer.js +177 -177
  36. package/lib/encode.js +30 -30
  37. package/lib/errorHandler.js +218 -206
  38. package/lib/generalErrorMessage.js +41 -41
  39. package/lib/jwt.js +18 -18
  40. package/lib/logger.js +190 -190
  41. package/lib/migrateCallLogsSchema.js +116 -0
  42. package/lib/ringcentral.js +266 -266
  43. package/lib/s3ErrorLogReport.js +65 -65
  44. package/lib/sharedSMSComposer.js +471 -471
  45. package/lib/util.js +67 -67
  46. package/mcp/README.md +412 -395
  47. package/mcp/lib/validator.js +91 -91
  48. package/mcp/mcpHandler.js +425 -425
  49. package/mcp/tools/cancelAppointment.js +101 -0
  50. package/mcp/tools/checkAuthStatus.js +105 -105
  51. package/mcp/tools/confirmAppointment.js +101 -0
  52. package/mcp/tools/createAppointment.js +157 -0
  53. package/mcp/tools/createCallLog.js +327 -316
  54. package/mcp/tools/createContact.js +117 -117
  55. package/mcp/tools/createMessageLog.js +287 -287
  56. package/mcp/tools/doAuth.js +60 -60
  57. package/mcp/tools/findContactByName.js +93 -93
  58. package/mcp/tools/findContactByPhone.js +101 -101
  59. package/mcp/tools/getCallLog.js +111 -102
  60. package/mcp/tools/getGoogleFilePicker.js +99 -99
  61. package/mcp/tools/getHelp.js +43 -43
  62. package/mcp/tools/getPublicConnectors.js +94 -94
  63. package/mcp/tools/getSessionInfo.js +90 -90
  64. package/mcp/tools/index.js +51 -41
  65. package/mcp/tools/listAppointments.js +163 -0
  66. package/mcp/tools/logout.js +99 -96
  67. package/mcp/tools/rcGetCallLogs.js +65 -65
  68. package/mcp/tools/updateAppointment.js +154 -0
  69. package/mcp/tools/updateCallLog.js +130 -126
  70. package/mcp/ui/App/App.tsx +358 -358
  71. package/mcp/ui/App/components/AuthInfoForm.tsx +113 -113
  72. package/mcp/ui/App/components/AuthSuccess.tsx +22 -22
  73. package/mcp/ui/App/components/ConnectorList.tsx +82 -82
  74. package/mcp/ui/App/components/DebugPanel.tsx +43 -43
  75. package/mcp/ui/App/components/OAuthConnect.tsx +270 -270
  76. package/mcp/ui/App/lib/callTool.ts +130 -130
  77. package/mcp/ui/App/lib/debugLog.ts +41 -41
  78. package/mcp/ui/App/lib/developerPortal.ts +111 -111
  79. package/mcp/ui/App/main.css +5 -5
  80. package/mcp/ui/App/root.tsx +13 -13
  81. package/mcp/ui/index.html +13 -13
  82. package/mcp/ui/package-lock.json +6356 -6356
  83. package/mcp/ui/package.json +25 -25
  84. package/mcp/ui/tsconfig.json +26 -26
  85. package/mcp/ui/vite.config.ts +16 -16
  86. package/models/accountDataModel.js +33 -33
  87. package/models/adminConfigModel.js +35 -35
  88. package/models/cacheModel.js +30 -26
  89. package/models/callDownListModel.js +34 -34
  90. package/models/callLogModel.js +33 -27
  91. package/models/dynamo/connectorSchema.js +146 -146
  92. package/models/dynamo/lockSchema.js +24 -24
  93. package/models/dynamo/noteCacheSchema.js +29 -29
  94. package/models/llmSessionModel.js +17 -17
  95. package/models/messageLogModel.js +25 -25
  96. package/models/sequelize.js +16 -16
  97. package/models/userModel.js +45 -45
  98. package/package.json +1 -1
  99. package/releaseNotes.json +1101 -1081
  100. package/test/connector/proxy/engine.test.js +126 -126
  101. package/test/connector/proxy/index.test.js +279 -279
  102. package/test/connector/proxy/sample.json +161 -161
  103. package/test/connector/registry.test.js +415 -415
  104. package/test/handlers/admin.test.js +616 -616
  105. package/test/handlers/auth.test.js +1092 -1018
  106. package/test/handlers/contact.test.js +1014 -1014
  107. package/test/handlers/log.test.js +1298 -1160
  108. package/test/handlers/managedAuth.test.js +457 -457
  109. package/test/handlers/plugin.test.js +380 -380
  110. package/test/index.test.js +105 -105
  111. package/test/lib/cacheCleanup.test.js +42 -0
  112. package/test/lib/callLogComposer.test.js +1231 -1231
  113. package/test/lib/debugTracer.test.js +328 -328
  114. package/test/lib/jwt.test.js +176 -176
  115. package/test/lib/logger.test.js +206 -206
  116. package/test/lib/oauth.test.js +359 -359
  117. package/test/lib/ringcentral.test.js +467 -467
  118. package/test/lib/sharedSMSComposer.test.js +1084 -1084
  119. package/test/lib/util.test.js +329 -329
  120. package/test/mcp/tools/checkAuthStatus.test.js +83 -83
  121. package/test/mcp/tools/createCallLog.test.js +436 -436
  122. package/test/mcp/tools/createContact.test.js +58 -58
  123. package/test/mcp/tools/createMessageLog.test.js +595 -595
  124. package/test/mcp/tools/doAuth.test.js +113 -113
  125. package/test/mcp/tools/findContactByName.test.js +275 -275
  126. package/test/mcp/tools/findContactByPhone.test.js +296 -296
  127. package/test/mcp/tools/getCallLog.test.js +298 -298
  128. package/test/mcp/tools/getGoogleFilePicker.test.js +281 -281
  129. package/test/mcp/tools/getPublicConnectors.test.js +107 -107
  130. package/test/mcp/tools/getSessionInfo.test.js +127 -127
  131. package/test/mcp/tools/logout.test.js +233 -233
  132. package/test/mcp/tools/rcGetCallLogs.test.js +56 -56
  133. package/test/mcp/tools/updateCallLog.test.js +360 -360
  134. package/test/models/accountDataModel.test.js +98 -98
  135. package/test/models/dynamo/connectorSchema.test.js +189 -189
  136. package/test/models/models.test.js +568 -539
  137. package/test/routes/managedAuthRoutes.test.js +235 -104
  138. package/test/setup.js +178 -178
@@ -1,94 +1,94 @@
1
- const axios = require('axios');
2
- const { Op } = require('sequelize');
3
- const { UserModel } = require('../../models/userModel');
4
- const { getHashValue } = require('../../lib/util');
5
-
6
- /**
7
- * MCP Tool: Get Public Connectors
8
- *
9
- * Triggers the connector selection widget. The widget fetches the connector
10
- * list and manifests directly from the developer portal on the client side.
11
- * This tool only needs to resolve the RC account ID (for private connector
12
- * support) and return the server URL for widget-to-server tool calls.
13
- */
14
-
15
- const toolDefinition = {
16
- name: 'getPublicConnectors',
17
- description: 'Get available connectors. Returns an interactive widget - do NOT summarize or list the results in text, just show the widget.',
18
- inputSchema: {
19
- type: 'object',
20
- properties: {},
21
- required: []
22
- },
23
- annotations: {
24
- readOnlyHint: true,
25
- openWorldHint: true,
26
- destructiveHint: false
27
- },
28
- _meta: {
29
- // openai/outputTemplate is injected at registration time by mcpHandler.js
30
- // using the module-level WIDGET_URI — do not hardcode a version here.
31
- "openai/toolBehavior": 'interactive',
32
- "openai/widgetAccessible": true
33
- }
34
- };
35
-
36
- /**
37
- * Execute the getPublicConnectors tool.
38
- * Uses the RC access token (injected by mcpHandler) to resolve the account ID,
39
- * which the widget needs to fetch private connectors directly from the developer portal.
40
- */
41
- async function execute({ rcAccessToken, openaiSessionId } = {}) {
42
- let rcExtensionId = null;
43
- let rcAccountId = null;
44
-
45
- if (rcAccessToken) {
46
- try {
47
- const resp = await axios.get(
48
- 'https://platform.ringcentral.com/restapi/v1.0/account/~/extension/~',
49
- { headers: { Authorization: `Bearer ${rcAccessToken}` } }
50
- );
51
- rcExtensionId = resp.data?.id ?? null;
52
- rcAccountId = resp.data?.account?.id ?? null;
53
- } catch {
54
- // Non-fatal: widget will only show public connectors
55
- }
56
- }
57
-
58
- // Check if user session already exists from Chrome extension
59
- const hashedRcExtensionId = getHashValue(rcExtensionId, process.env.HASH_KEY);
60
- const user = await UserModel.findOne({
61
- where: {
62
- hashedRcExtensionId,
63
- [Op.and]: [
64
- { accessToken: { [Op.not]: null } },
65
- { accessToken: { [Op.ne]: '' } },
66
- ],
67
- },
68
- order: [['updatedAt', 'DESC']],
69
- });
70
- // Case: user exists, return user info in plain message
71
- if (user?.accessToken) {
72
- return {
73
- structuredContent: {
74
- error: true,
75
- errorMessage: `You are already connected to ${user.platform}. It's controlled from App Connect Chrome extension.`
76
- }
77
- }
78
- }
79
- else {
80
- // Case: user doesn't exist, return structured content for widget
81
- return {
82
- structuredContent: {
83
- serverUrl: process.env.APP_SERVER || 'https://localhost:6066',
84
- rcExtensionId,
85
- rcAccountId,
86
- openaiSessionId: openaiSessionId ?? null,
87
- }
88
- };
89
- }
90
-
91
- }
92
-
93
- exports.definition = toolDefinition;
94
- exports.execute = execute;
1
+ const axios = require('axios');
2
+ const { Op } = require('sequelize');
3
+ const { UserModel } = require('../../models/userModel');
4
+ const { getHashValue } = require('../../lib/util');
5
+
6
+ /**
7
+ * MCP Tool: Get Public Connectors
8
+ *
9
+ * Triggers the connector selection widget. The widget fetches the connector
10
+ * list and manifests directly from the developer portal on the client side.
11
+ * This tool only needs to resolve the RC account ID (for private connector
12
+ * support) and return the server URL for widget-to-server tool calls.
13
+ */
14
+
15
+ const toolDefinition = {
16
+ name: 'getPublicConnectors',
17
+ description: 'Get available connectors. Returns an interactive widget - do NOT summarize or list the results in text, just show the widget.',
18
+ inputSchema: {
19
+ type: 'object',
20
+ properties: {},
21
+ required: []
22
+ },
23
+ annotations: {
24
+ readOnlyHint: true,
25
+ openWorldHint: true,
26
+ destructiveHint: false
27
+ },
28
+ _meta: {
29
+ // openai/outputTemplate is injected at registration time by mcpHandler.js
30
+ // using the module-level WIDGET_URI — do not hardcode a version here.
31
+ "openai/toolBehavior": 'interactive',
32
+ "openai/widgetAccessible": true
33
+ }
34
+ };
35
+
36
+ /**
37
+ * Execute the getPublicConnectors tool.
38
+ * Uses the RC access token (injected by mcpHandler) to resolve the account ID,
39
+ * which the widget needs to fetch private connectors directly from the developer portal.
40
+ */
41
+ async function execute({ rcAccessToken, openaiSessionId } = {}) {
42
+ let rcExtensionId = null;
43
+ let rcAccountId = null;
44
+
45
+ if (rcAccessToken) {
46
+ try {
47
+ const resp = await axios.get(
48
+ 'https://platform.ringcentral.com/restapi/v1.0/account/~/extension/~',
49
+ { headers: { Authorization: `Bearer ${rcAccessToken}` } }
50
+ );
51
+ rcExtensionId = resp.data?.id ?? null;
52
+ rcAccountId = resp.data?.account?.id ?? null;
53
+ } catch {
54
+ // Non-fatal: widget will only show public connectors
55
+ }
56
+ }
57
+
58
+ // Check if user session already exists from Chrome extension
59
+ const hashedRcExtensionId = getHashValue(rcExtensionId, process.env.HASH_KEY);
60
+ const user = await UserModel.findOne({
61
+ where: {
62
+ hashedRcExtensionId,
63
+ [Op.and]: [
64
+ { accessToken: { [Op.not]: null } },
65
+ { accessToken: { [Op.ne]: '' } },
66
+ ],
67
+ },
68
+ order: [['updatedAt', 'DESC']],
69
+ });
70
+ // Case: user exists, return user info in plain message
71
+ if (user?.accessToken) {
72
+ return {
73
+ structuredContent: {
74
+ error: true,
75
+ errorMessage: `You are already connected to ${user.platform}. It's controlled from App Connect Chrome extension.`
76
+ }
77
+ }
78
+ }
79
+ else {
80
+ // Case: user doesn't exist, return structured content for widget
81
+ return {
82
+ structuredContent: {
83
+ serverUrl: process.env.APP_SERVER || 'https://localhost:6066',
84
+ rcExtensionId,
85
+ rcAccountId,
86
+ openaiSessionId: openaiSessionId ?? null,
87
+ }
88
+ };
89
+ }
90
+
91
+ }
92
+
93
+ exports.definition = toolDefinition;
94
+ exports.execute = execute;
@@ -1,90 +1,90 @@
1
- const jwt = require('../../lib/jwt');
2
- const { UserModel } = require('../../models/userModel');
3
- const { RingCentral } = require('../../lib/ringcentral');
4
-
5
- /**
6
- * MCP Tool: Get Session Info
7
- *
8
- * Returns non-sensitive information about the current MCP/CRM session.
9
- */
10
-
11
- const toolDefinition = {
12
- name: 'getSessionInfo',
13
- description: 'Get the current user session info, including RingCentral identity and CRM connection status.',
14
- inputSchema: {
15
- type: 'object',
16
- properties: {},
17
- required: []
18
- },
19
- annotations: {
20
- readOnlyHint: true,
21
- openWorldHint: false,
22
- destructiveHint: false
23
- }
24
- };
25
-
26
- /**
27
- * Execute the getSessionInfo tool
28
- * @param {Object} args - Tool arguments injected by mcpHandler
29
- * @param {string} [args.openaiSessionId] - OpenAI session identifier
30
- * @param {string} [args.rcExtensionId] - Verified RingCentral extension identifier
31
- * @param {string} [args.jwtToken] - CRM JWT token
32
- * @param {string} [args.rcAccessToken] - RingCentral access token
33
- * @returns {Object} Result object with session information
34
- */
35
- async function execute(args = {}) {
36
- try {
37
- const {
38
- openaiSessionId = null,
39
- rcExtensionId = null,
40
- jwtToken,
41
- rcAccessToken,
42
- } = args;
43
-
44
- const decodedToken = jwtToken ? jwt.decodeJwt(jwtToken) : null;
45
- const userId = decodedToken?.id ?? null;
46
- const user = userId ? await UserModel.findByPk(userId) : null;
47
-
48
- let rcExtensionInfo = null;
49
- if (rcExtensionId && rcAccessToken) {
50
- const rcSDK = new RingCentral({
51
- server: process.env.RINGCENTRAL_SERVER,
52
- clientId: process.env.RINGCENTRAL_CLIENT_ID,
53
- clientSecret: process.env.RINGCENTRAL_CLIENT_SECRET,
54
- redirectUri: `${process.env.APP_SERVER}/ringcentral/oauth/callback`
55
- });
56
- rcExtensionInfo = await rcSDK.getExtensionInfo(rcExtensionId, {
57
- access_token: rcAccessToken,
58
- token_type: 'Bearer'
59
- });
60
- }
61
- return {
62
- success: true,
63
- data: {
64
- openaiSessionId,
65
- dataToShow: {
66
- isCrmAuthenticated: Boolean(decodedToken && user?.accessToken),
67
- ringcentral: {
68
- extensionId: rcExtensionId ?? null,
69
- name: rcExtensionInfo?.name ?? null,
70
- },
71
- crm: {
72
- userId,
73
- platform: decodedToken?.platform ?? user?.platform ?? null,
74
- hostname: user?.hostname ?? null
75
- }
76
- }
77
- }
78
- };
79
- }
80
- catch (error) {
81
- return {
82
- success: false,
83
- error: error.message || 'Unknown error occurred',
84
- errorDetails: error.stack
85
- };
86
- }
87
- }
88
-
89
- exports.definition = toolDefinition;
90
- exports.execute = execute;
1
+ const jwt = require('../../lib/jwt');
2
+ const { UserModel } = require('../../models/userModel');
3
+ const { RingCentral } = require('../../lib/ringcentral');
4
+
5
+ /**
6
+ * MCP Tool: Get Session Info
7
+ *
8
+ * Returns non-sensitive information about the current MCP/CRM session.
9
+ */
10
+
11
+ const toolDefinition = {
12
+ name: 'getSessionInfo',
13
+ description: 'Get the current user session info, including RingCentral identity and CRM connection status.',
14
+ inputSchema: {
15
+ type: 'object',
16
+ properties: {},
17
+ required: []
18
+ },
19
+ annotations: {
20
+ readOnlyHint: true,
21
+ openWorldHint: false,
22
+ destructiveHint: false
23
+ }
24
+ };
25
+
26
+ /**
27
+ * Execute the getSessionInfo tool
28
+ * @param {Object} args - Tool arguments injected by mcpHandler
29
+ * @param {string} [args.openaiSessionId] - OpenAI session identifier
30
+ * @param {string} [args.rcExtensionId] - Verified RingCentral extension identifier
31
+ * @param {string} [args.jwtToken] - CRM JWT token
32
+ * @param {string} [args.rcAccessToken] - RingCentral access token
33
+ * @returns {Object} Result object with session information
34
+ */
35
+ async function execute(args = {}) {
36
+ try {
37
+ const {
38
+ openaiSessionId = null,
39
+ rcExtensionId = null,
40
+ jwtToken,
41
+ rcAccessToken,
42
+ } = args;
43
+
44
+ const decodedToken = jwtToken ? jwt.decodeJwt(jwtToken) : null;
45
+ const userId = decodedToken?.id ?? null;
46
+ const user = userId ? await UserModel.findByPk(userId) : null;
47
+
48
+ let rcExtensionInfo = null;
49
+ if (rcExtensionId && rcAccessToken) {
50
+ const rcSDK = new RingCentral({
51
+ server: process.env.RINGCENTRAL_SERVER,
52
+ clientId: process.env.RINGCENTRAL_CLIENT_ID,
53
+ clientSecret: process.env.RINGCENTRAL_CLIENT_SECRET,
54
+ redirectUri: `${process.env.APP_SERVER}/ringcentral/oauth/callback`
55
+ });
56
+ rcExtensionInfo = await rcSDK.getExtensionInfo(rcExtensionId, {
57
+ access_token: rcAccessToken,
58
+ token_type: 'Bearer'
59
+ });
60
+ }
61
+ return {
62
+ success: true,
63
+ data: {
64
+ openaiSessionId,
65
+ dataToShow: {
66
+ isCrmAuthenticated: Boolean(decodedToken && user?.accessToken),
67
+ ringcentral: {
68
+ extensionId: rcExtensionId ?? null,
69
+ name: rcExtensionInfo?.name ?? null,
70
+ },
71
+ crm: {
72
+ userId,
73
+ platform: decodedToken?.platform ?? user?.platform ?? null,
74
+ hostname: user?.hostname ?? null
75
+ }
76
+ }
77
+ }
78
+ };
79
+ }
80
+ catch (error) {
81
+ return {
82
+ success: false,
83
+ error: error.message || 'Unknown error occurred',
84
+ errorDetails: error.stack
85
+ };
86
+ }
87
+ }
88
+
89
+ exports.definition = toolDefinition;
90
+ exports.execute = execute;
@@ -1,41 +1,51 @@
1
- /**
2
- * MCP Tools Index
3
- *
4
- * Two separate registries:
5
- * - tools: Registered in the MCP server — visible to and callable by the AI model
6
- * - widgetTools: Only accessible via POST /mcp/widget-tool-call — hidden from the AI model
7
- */
8
-
9
- const getHelp = require('./getHelp');
10
- const getPublicConnectors = require('./getPublicConnectors');
11
- const getSessionInfo = require('./getSessionInfo');
12
- const doAuth = require('./doAuth');
13
- const checkAuthStatus = require('./checkAuthStatus');
14
- const logout = require('./logout');
15
- const findContact = require('./findContactByPhone');
16
- const findContactWithName = require('./findContactByName');
17
- const createCallLog = require('./createCallLog');
18
- const rcGetCallLogs = require('./rcGetCallLogs');
19
- // const getGoogleFilePicker = require('./getGoogleFilePicker');
20
- const createContact = require('./createContact');
21
-
22
- // AI-visible MCP tools — registered in the MCP server
23
- module.exports.tools = [
24
- getHelp,
25
- getPublicConnectors,
26
- getSessionInfo,
27
- logout,
28
- findContact,
29
- findContactWithName,
30
- createCallLog,
31
- rcGetCallLogs,
32
- // getGoogleFilePicker,
33
- createContact,
34
- ];
35
-
36
- // Widget-only tools — callable via /mcp/widget-tool-call, NOT registered as MCP tools
37
- module.exports.widgetTools = [
38
- doAuth,
39
- checkAuthStatus,
40
- ];
41
-
1
+ /**
2
+ * MCP Tools Index
3
+ *
4
+ * Two separate registries:
5
+ * - tools: Registered in the MCP server — visible to and callable by the AI model
6
+ * - widgetTools: Only accessible via POST /mcp/widget-tool-call — hidden from the AI model
7
+ */
8
+
9
+ const getHelp = require('./getHelp');
10
+ const getPublicConnectors = require('./getPublicConnectors');
11
+ const getSessionInfo = require('./getSessionInfo');
12
+ const doAuth = require('./doAuth');
13
+ const checkAuthStatus = require('./checkAuthStatus');
14
+ const logout = require('./logout');
15
+ const findContact = require('./findContactByPhone');
16
+ const findContactWithName = require('./findContactByName');
17
+ const createCallLog = require('./createCallLog');
18
+ const rcGetCallLogs = require('./rcGetCallLogs');
19
+ // const getGoogleFilePicker = require('./getGoogleFilePicker');
20
+ const createContact = require('./createContact');
21
+ const createAppointment = require('./createAppointment');
22
+ const updateAppointment = require('./updateAppointment');
23
+ const confirmAppointment = require('./confirmAppointment');
24
+ const cancelAppointment = require('./cancelAppointment');
25
+ const listAppointments = require('./listAppointments');
26
+
27
+ // AI-visible MCP tools — registered in the MCP server
28
+ module.exports.tools = [
29
+ getHelp,
30
+ getPublicConnectors,
31
+ getSessionInfo,
32
+ logout,
33
+ findContact,
34
+ findContactWithName,
35
+ createCallLog,
36
+ rcGetCallLogs,
37
+ // getGoogleFilePicker,
38
+ createContact,
39
+ listAppointments,
40
+ createAppointment,
41
+ updateAppointment,
42
+ confirmAppointment,
43
+ cancelAppointment,
44
+ ];
45
+
46
+ // Widget-only tools — callable via /mcp/widget-tool-call, NOT registered as MCP tools
47
+ module.exports.widgetTools = [
48
+ doAuth,
49
+ checkAuthStatus,
50
+ ];
51
+
@@ -0,0 +1,163 @@
1
+ const jwt = require('../../lib/jwt');
2
+ const connectorRegistry = require('../../connector/registry');
3
+ const appointmentCore = require('../../handlers/appointment');
4
+
5
+ /**
6
+ * MCP Tool: List Appointments
7
+ *
8
+ * Fetches appointments/events from the CRM platform.
9
+ * Accepts a named filter (upcoming, today, past, all) or a custom date range.
10
+ */
11
+
12
+ const toolDefinition = {
13
+ name: 'listAppointments',
14
+ description: '⚠️ REQUIRES CRM CONNECTION. | List appointments or events from the CRM platform. Use the `filter` param to get upcoming, today\'s, past, or all appointments. For a specific window, supply `startDate` and `endDate` (YYYY-MM-DD) directly.',
15
+ inputSchema: {
16
+ type: 'object',
17
+ properties: {
18
+ filter: {
19
+ type: 'string',
20
+ enum: ['upcoming', 'today', 'past', 'all', 'custom'],
21
+ description: [
22
+ 'Named time filter:',
23
+ ' • "upcoming" — from today onward (next 3 months)',
24
+ ' • "today" — only today\'s appointments',
25
+ ' • "past" — everything before today (last 3 months)',
26
+ ' • "all" — last 3 months through next 3 months',
27
+ ' • "custom" — use startDate + endDate you provide',
28
+ ].join('\n')
29
+ },
30
+ startDate: {
31
+ type: 'string',
32
+ description: 'Start of custom date range in YYYY-MM-DD format. Only used when filter is "custom".'
33
+ },
34
+ endDate: {
35
+ type: 'string',
36
+ description: 'End of custom date range in YYYY-MM-DD format. Only used when filter is "custom".'
37
+ },
38
+ mineOnly: {
39
+ type: 'boolean',
40
+ description: 'When true, returns only appointments assigned to the current user. Defaults to false.'
41
+ }
42
+ },
43
+ required: []
44
+ },
45
+ annotations: {
46
+ readOnlyHint: true,
47
+ openWorldHint: true,
48
+ destructiveHint: false
49
+ }
50
+ };
51
+
52
+ /**
53
+ * Build a YYYY-MM-DD string offset by `days` from today.
54
+ */
55
+ function offsetDate(days) {
56
+ const d = new Date();
57
+ d.setDate(d.getDate() + days);
58
+ return d.toISOString().slice(0, 10);
59
+ }
60
+
61
+ function todayStr() {
62
+ return new Date().toISOString().slice(0, 10);
63
+ }
64
+
65
+ /**
66
+ * Resolve the range object from the filter name or explicit dates.
67
+ */
68
+ function resolveRange({ filter, startDate, endDate }) {
69
+ const f = (filter ?? 'all').toLowerCase();
70
+ switch (f) {
71
+ case 'upcoming':
72
+ return { startDate: todayStr(), endDate: offsetDate(90) };
73
+ case 'today':
74
+ return { startDate: todayStr(), endDate: todayStr() };
75
+ case 'past':
76
+ return { startDate: offsetDate(-90), endDate: offsetDate(-1) };
77
+ case 'custom':
78
+ return {
79
+ startDate: startDate ?? offsetDate(-90),
80
+ endDate: endDate ?? offsetDate(90)
81
+ };
82
+ case 'all':
83
+ default:
84
+ return { startDate: offsetDate(-90), endDate: offsetDate(90) };
85
+ }
86
+ }
87
+
88
+ /**
89
+ * Execute the listAppointments tool
90
+ * @param {Object} args
91
+ * @param {string} args.jwtToken - Injected server-side JWT token
92
+ * @param {string} [args.filter] - Named filter: upcoming | today | past | all | custom
93
+ * @param {string} [args.startDate] - Custom range start (YYYY-MM-DD), used when filter="custom"
94
+ * @param {string} [args.endDate] - Custom range end (YYYY-MM-DD), used when filter="custom"
95
+ * @param {boolean} [args.mineOnly] - Restrict to the current user's appointments
96
+ * @returns {Object} Result with appointment list
97
+ */
98
+ async function execute(args) {
99
+ try {
100
+ const { jwtToken, filter, startDate, endDate, mineOnly } = args;
101
+
102
+ if (!jwtToken) {
103
+ throw new Error('Please go to Settings and authorize CRM platform');
104
+ }
105
+
106
+ const decodedToken = jwt.decodeJwt(jwtToken);
107
+ if (!decodedToken) {
108
+ throw new Error('Invalid JWT token');
109
+ }
110
+ const { id: userId, platform } = decodedToken;
111
+
112
+ if (!userId) {
113
+ throw new Error('Invalid JWT token: userId not found');
114
+ }
115
+
116
+ const platformModule = connectorRegistry.getConnector(platform);
117
+ if (!platformModule) {
118
+ throw new Error(`Platform connector not found for: ${platform}`);
119
+ }
120
+
121
+ if (!platformModule.listAppointments) {
122
+ throw new Error(`listAppointments is not implemented for platform: ${platform}`);
123
+ }
124
+
125
+ const range = resolveRange({ filter, startDate, endDate });
126
+
127
+ const { successful, appointments, returnMessage } = await appointmentCore.listAppointments({
128
+ platform,
129
+ userId,
130
+ range,
131
+ mineOnly: mineOnly ?? false,
132
+ forceSync: false
133
+ });
134
+
135
+ if (successful) {
136
+ return {
137
+ success: true,
138
+ data: {
139
+ filter: filter ?? 'all',
140
+ range,
141
+ totalCount: appointments?.length ?? 0,
142
+ appointments: appointments ?? []
143
+ }
144
+ };
145
+ }
146
+ else {
147
+ return {
148
+ success: false,
149
+ error: returnMessage?.message || 'Failed to list appointments'
150
+ };
151
+ }
152
+ }
153
+ catch (error) {
154
+ return {
155
+ success: false,
156
+ error: error.message || 'Unknown error occurred',
157
+ errorDetails: error.stack
158
+ };
159
+ }
160
+ }
161
+
162
+ exports.definition = toolDefinition;
163
+ exports.execute = execute;