@app-connect/core 1.7.24 → 1.7.26

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 (137) hide show
  1. package/.env.test +5 -5
  2. package/README.md +441 -441
  3. package/connector/developerPortal.js +31 -42
  4. package/connector/mock.js +84 -77
  5. package/connector/proxy/engine.js +164 -163
  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 -117
  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 +296 -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 +984 -973
  23. package/handlers/managedAuth.js +446 -446
  24. package/handlers/plugin.js +208 -208
  25. package/handlers/user.js +142 -142
  26. package/index.js +3140 -2652
  27. package/jest.config.js +56 -56
  28. package/lib/analytics.js +54 -54
  29. package/lib/authSession.js +109 -109
  30. package/lib/cacheCleanup.js +21 -0
  31. package/lib/callLogComposer.js +898 -898
  32. package/lib/callLogLookup.js +34 -0
  33. package/lib/constants.js +8 -8
  34. package/lib/debugTracer.js +177 -177
  35. package/lib/encode.js +30 -30
  36. package/lib/errorHandler.js +218 -206
  37. package/lib/generalErrorMessage.js +41 -41
  38. package/lib/jwt.js +18 -18
  39. package/lib/logger.js +190 -190
  40. package/lib/migrateCallLogsSchema.js +116 -0
  41. package/lib/ringcentral.js +266 -266
  42. package/lib/s3ErrorLogReport.js +65 -65
  43. package/lib/sharedSMSComposer.js +471 -471
  44. package/lib/util.js +67 -67
  45. package/mcp/README.md +412 -395
  46. package/mcp/lib/validator.js +91 -91
  47. package/mcp/mcpHandler.js +425 -425
  48. package/mcp/tools/cancelAppointment.js +101 -0
  49. package/mcp/tools/checkAuthStatus.js +105 -105
  50. package/mcp/tools/confirmAppointment.js +101 -0
  51. package/mcp/tools/createAppointment.js +157 -0
  52. package/mcp/tools/createCallLog.js +327 -316
  53. package/mcp/tools/createContact.js +117 -117
  54. package/mcp/tools/createMessageLog.js +287 -287
  55. package/mcp/tools/doAuth.js +60 -60
  56. package/mcp/tools/findContactByName.js +93 -93
  57. package/mcp/tools/findContactByPhone.js +101 -101
  58. package/mcp/tools/getCallLog.js +111 -102
  59. package/mcp/tools/getGoogleFilePicker.js +99 -99
  60. package/mcp/tools/getHelp.js +43 -43
  61. package/mcp/tools/getPublicConnectors.js +94 -94
  62. package/mcp/tools/getSessionInfo.js +90 -90
  63. package/mcp/tools/index.js +51 -41
  64. package/mcp/tools/listAppointments.js +163 -0
  65. package/mcp/tools/logout.js +96 -96
  66. package/mcp/tools/rcGetCallLogs.js +65 -65
  67. package/mcp/tools/updateAppointment.js +154 -0
  68. package/mcp/tools/updateCallLog.js +130 -126
  69. package/mcp/ui/App/App.tsx +358 -358
  70. package/mcp/ui/App/components/AuthInfoForm.tsx +113 -113
  71. package/mcp/ui/App/components/AuthSuccess.tsx +22 -22
  72. package/mcp/ui/App/components/ConnectorList.tsx +82 -82
  73. package/mcp/ui/App/components/DebugPanel.tsx +43 -43
  74. package/mcp/ui/App/components/OAuthConnect.tsx +270 -270
  75. package/mcp/ui/App/lib/callTool.ts +130 -130
  76. package/mcp/ui/App/lib/debugLog.ts +41 -41
  77. package/mcp/ui/App/lib/developerPortal.ts +111 -111
  78. package/mcp/ui/App/main.css +5 -5
  79. package/mcp/ui/App/root.tsx +13 -13
  80. package/mcp/ui/index.html +13 -13
  81. package/mcp/ui/package-lock.json +6356 -6356
  82. package/mcp/ui/package.json +25 -25
  83. package/mcp/ui/tsconfig.json +26 -26
  84. package/mcp/ui/vite.config.ts +16 -16
  85. package/models/accountDataModel.js +33 -33
  86. package/models/adminConfigModel.js +35 -35
  87. package/models/cacheModel.js +30 -26
  88. package/models/callDownListModel.js +34 -34
  89. package/models/callLogModel.js +33 -27
  90. package/models/dynamo/connectorSchema.js +146 -146
  91. package/models/dynamo/lockSchema.js +24 -24
  92. package/models/dynamo/noteCacheSchema.js +29 -29
  93. package/models/llmSessionModel.js +17 -17
  94. package/models/messageLogModel.js +25 -25
  95. package/models/sequelize.js +16 -16
  96. package/models/userModel.js +45 -45
  97. package/package.json +72 -72
  98. package/releaseNotes.json +1093 -1073
  99. package/test/connector/proxy/engine.test.js +126 -93
  100. package/test/connector/proxy/index.test.js +279 -279
  101. package/test/connector/proxy/sample.json +161 -161
  102. package/test/connector/registry.test.js +415 -415
  103. package/test/handlers/admin.test.js +616 -616
  104. package/test/handlers/auth.test.js +1018 -1015
  105. package/test/handlers/contact.test.js +1014 -1014
  106. package/test/handlers/log.test.js +1298 -1160
  107. package/test/handlers/managedAuth.test.js +458 -458
  108. package/test/handlers/plugin.test.js +380 -380
  109. package/test/index.test.js +105 -105
  110. package/test/lib/cacheCleanup.test.js +42 -0
  111. package/test/lib/callLogComposer.test.js +1231 -1231
  112. package/test/lib/debugTracer.test.js +328 -328
  113. package/test/lib/jwt.test.js +176 -176
  114. package/test/lib/logger.test.js +206 -206
  115. package/test/lib/oauth.test.js +359 -359
  116. package/test/lib/ringcentral.test.js +467 -467
  117. package/test/lib/sharedSMSComposer.test.js +1084 -1084
  118. package/test/lib/util.test.js +329 -329
  119. package/test/mcp/tools/checkAuthStatus.test.js +83 -82
  120. package/test/mcp/tools/createCallLog.test.js +436 -436
  121. package/test/mcp/tools/createContact.test.js +58 -58
  122. package/test/mcp/tools/createMessageLog.test.js +595 -595
  123. package/test/mcp/tools/doAuth.test.js +113 -113
  124. package/test/mcp/tools/findContactByName.test.js +275 -275
  125. package/test/mcp/tools/findContactByPhone.test.js +296 -296
  126. package/test/mcp/tools/getCallLog.test.js +298 -298
  127. package/test/mcp/tools/getGoogleFilePicker.test.js +281 -281
  128. package/test/mcp/tools/getPublicConnectors.test.js +107 -107
  129. package/test/mcp/tools/getSessionInfo.test.js +127 -127
  130. package/test/mcp/tools/logout.test.js +233 -233
  131. package/test/mcp/tools/rcGetCallLogs.test.js +56 -56
  132. package/test/mcp/tools/updateCallLog.test.js +360 -360
  133. package/test/models/accountDataModel.test.js +98 -98
  134. package/test/models/dynamo/connectorSchema.test.js +189 -189
  135. package/test/models/models.test.js +568 -539
  136. package/test/routes/managedAuthRoutes.test.js +104 -129
  137. package/test/setup.js +178 -178
package/mcp/mcpHandler.js CHANGED
@@ -1,425 +1,425 @@
1
- /**
2
- * MCP Server for RC Unified CRM Extension
3
- *
4
- * Stateless hand-rolled JSON-RPC handler — no SDK, no SSE, no sessions Map.
5
- * Fully compatible with stateless deployments (AWS Lambda, etc.).
6
- * All auth context is resolved per-request; rcExtensionId is cached in CacheModel.
7
- */
8
-
9
- const axios = require('axios');
10
- const { Op } = require('sequelize');
11
- const tools = require('./tools');
12
- const { LlmSessionModel } = require('../models/llmSessionModel');
13
- const { CacheModel } = require('../models/cacheModel');
14
- const { UserModel } = require('../models/userModel');
15
- const { getHashValue } = require('../lib/util');
16
- const jwt = require('../lib/jwt');
17
- const logger = require('../lib/logger');
18
- const fs = require('fs');
19
- const path = require('path');
20
-
21
- /**
22
- * Increment this to bust ChatGPT's widget resource cache after every UI build.
23
- * This is the single source of truth — injected into getPublicConnectors _meta at response time.
24
- */
25
- const WIDGET_VERSION = 10;
26
- const WIDGET_URI = `ui://widget/ConnectorList-v${WIDGET_VERSION}.html`;
27
- const RC_EXTENSION_CACHE_KEY = 'rcExtensionId';
28
- const RC_EXTENSION_CACHE_STATUS = 'resolved';
29
-
30
- const JSON_RPC_INTERNAL_ERROR = -32603;
31
- const JSON_RPC_METHOD_NOT_FOUND = -32601;
32
- const JSON_RPC_INVALID_PARAMS = -32602;
33
-
34
- /**
35
- * JSON Schema definitions for tools that accept parameters.
36
- * Without inputSchema, ChatGPT silently drops all arguments when calling the tool.
37
- */
38
- const inputSchemas = {
39
- findContactByName: {
40
- type: 'object',
41
- properties: {
42
- name: { type: 'string', description: 'Name to search for' },
43
- },
44
- required: ['name'],
45
- },
46
- findContactByPhone: {
47
- type: 'object',
48
- properties: {
49
- phoneNumber: { type: 'string', description: 'Phone number in E.164 format (e.g. +14155551234)' },
50
- overridingFormat: { type: 'string', description: 'Overriding format to search for' },
51
- isExtension: { type: 'boolean', description: 'Whether the request is from an extension' },
52
- },
53
- required: ['phoneNumber'],
54
- },
55
- createContact: {
56
- type: 'object',
57
- properties: {
58
- phoneNumber: { type: 'string', description: 'Phone number in E.164 format (e.g. +14155551234)' },
59
- newContactName: { type: 'string', description: 'Full name of the new contact' },
60
- },
61
- required: ['phoneNumber'],
62
- },
63
- createCallLog: {
64
- type: 'object',
65
- properties: {
66
- incomingData: { description: 'Call log data to create' },
67
- contactId: { type: 'string', description: 'CRM contact ID to attach the log to' },
68
- contactType: { type: 'string', description: 'Type of the CRM contact' },
69
- note: { type: 'string', description: 'Note to include in the call log' },
70
- },
71
- required: [],
72
- },
73
- rcGetCallLogs: {
74
- type: 'object',
75
- properties: {
76
- timeFrom: { type: 'string', description: 'Start of time range in ISO 8601 format' },
77
- timeTo: { type: 'string', description: 'End of time range in ISO 8601 format' },
78
- },
79
- required: ['timeFrom', 'timeTo'],
80
- },
81
- logout: {
82
- type: 'object',
83
- properties: {},
84
- required: [],
85
- },
86
- };
87
-
88
- /**
89
- * Verify an RC access token and return the caller's extension ID.
90
- * Throws if the token is invalid.
91
- */
92
- async function resolveRcExtensionId(rcAccessToken) {
93
- const resp = await axios.get(
94
- 'https://platform.ringcentral.com/restapi/v1.0/account/~/extension/~',
95
- { headers: { Authorization: `Bearer ${rcAccessToken}` } }
96
- );
97
- return resp.data?.id?.toString() ?? null;
98
- }
99
-
100
- /**
101
- * Resolve rcExtensionId for the current request.
102
- * Checks CacheModel first (avoids RC API call on Lambda cold starts),
103
- * falls back to a live RC API verification and persists the result.
104
- */
105
- async function resolveSessionContext(rcAccessToken, openaiSessionId) {
106
- if (!rcAccessToken) return { rcExtensionId: null };
107
-
108
- if (openaiSessionId) {
109
- try {
110
- const cached = await CacheModel.findByPk(`${openaiSessionId}-${RC_EXTENSION_CACHE_KEY}`);
111
- if (cached?.data?.rcExtensionId && (!cached.expiry || cached.expiry > new Date())) {
112
- return { rcExtensionId: cached.data.rcExtensionId };
113
- }
114
- } catch (err) {
115
- logger.warn('CacheModel lookup failed:', { message: err.message });
116
- }
117
- }
118
-
119
- let rcExtensionId = null;
120
- try {
121
- rcExtensionId = await resolveRcExtensionId(rcAccessToken);
122
- if (openaiSessionId && rcExtensionId) {
123
- await CacheModel.upsert({
124
- id: `${openaiSessionId}-${RC_EXTENSION_CACHE_KEY}`,
125
- userId: openaiSessionId,
126
- cacheKey: RC_EXTENSION_CACHE_KEY,
127
- data: { rcExtensionId },
128
- status: RC_EXTENSION_CACHE_STATUS,
129
- expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24h TTL
130
- });
131
- }
132
- } catch (err) {
133
- logger.warn('Failed to resolve RC extension ID:', { message: err.message });
134
- }
135
-
136
- return { rcExtensionId };
137
- }
138
-
139
- /**
140
- * Build the tools list to return in tools/list responses.
141
- * Injects inputSchema and stamps WIDGET_URI into getPublicConnectors _meta.
142
- */
143
- function getToolsList() {
144
- return tools.tools.map(tool => {
145
- const def = { ...tool.definition };
146
- if (def.name === 'getPublicConnectors') {
147
- def._meta = { ...(def._meta || {}), 'openai/outputTemplate': WIDGET_URI };
148
- }
149
- if (inputSchemas[def.name]) {
150
- def.inputSchema = inputSchemas[def.name];
151
- }
152
- return def;
153
- });
154
- }
155
-
156
- /**
157
- * Handle incoming MCP HTTP requests.
158
- * Stateless: each POST is handled independently with no session state between requests.
159
- */
160
- async function handleMcpRequest(req, res) {
161
- try {
162
- const { method, params, id } = req.body;
163
- logger.info('Received MCP request:', { method });
164
-
165
- const rcAccessToken = req.headers['authorization']?.split('Bearer ')?.[1];
166
- const openaiSessionId = params?._meta?.['openai/session'] ?? null;
167
-
168
- let response;
169
-
170
- switch (method) {
171
- case 'initialize':
172
- response = {
173
- jsonrpc: '2.0',
174
- id,
175
- result: {
176
- protocolVersion: '2024-11-05',
177
- capabilities: {
178
- tools: {},
179
- resources: {},
180
- },
181
- serverInfo: {
182
- name: 'rc-unified-crm-extension',
183
- version: '1.0.0',
184
- },
185
- },
186
- };
187
- break;
188
-
189
- case 'tools/list':
190
- response = {
191
- jsonrpc: '2.0',
192
- id,
193
- result: { tools: getToolsList() },
194
- };
195
- break;
196
-
197
- case 'tools/call': {
198
- const { name: toolName, arguments: args } = params;
199
- const toolArgs = { ...(args || {}) };
200
-
201
- if (rcAccessToken) toolArgs.rcAccessToken = rcAccessToken;
202
- if (openaiSessionId) toolArgs.openaiSessionId = openaiSessionId;
203
-
204
- const { rcExtensionId } = await resolveSessionContext(rcAccessToken, openaiSessionId);
205
- if (rcExtensionId) {
206
- toolArgs.rcExtensionId = rcExtensionId;
207
- if (!toolArgs.jwtToken) {
208
- let llmSession = await LlmSessionModel.findByPk(rcExtensionId);
209
- if (llmSession?.expiry && llmSession.expiry < new Date()) {
210
- await LlmSessionModel.destroy({ where: { id: rcExtensionId } });
211
- llmSession = null;
212
- }
213
- if (!llmSession?.jwtToken && openaiSessionId) {
214
- const fallback = await LlmSessionModel.findByPk(openaiSessionId);
215
- if (fallback?.jwtToken) {
216
- const { id: fallbackUserId } = jwt.decodeJwt(fallback.jwtToken);
217
- const fallbackUser = fallbackUserId
218
- ? await UserModel.findByPk(fallbackUserId)
219
- : null;
220
- if (fallbackUser?.accessToken) {
221
- await LlmSessionModel.upsert({ id: rcExtensionId, jwtToken: fallback.jwtToken, expiry: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) });
222
- llmSession = fallback;
223
- }
224
- }
225
- if (!llmSession?.jwtToken) {
226
- const hashedRcExtensionId = getHashValue(rcExtensionId, process.env.HASH_KEY);
227
- const user = await UserModel.findOne({
228
- where: {
229
- hashedRcExtensionId,
230
- [Op.and]: [
231
- { accessToken: { [Op.not]: null } },
232
- { accessToken: { [Op.ne]: '' } },
233
- ],
234
- },
235
- order: [['updatedAt', 'DESC']],
236
- });
237
- if (user?.accessToken) {
238
- await LlmSessionModel.upsert({
239
- id: rcExtensionId,
240
- jwtToken: jwt.generateJwt({
241
- id: user.id.toString(),
242
- platform: user.platform
243
- }),
244
- expiry: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
245
- });
246
- llmSession = await LlmSessionModel.findByPk(rcExtensionId);
247
- }
248
- }
249
- }
250
- if (llmSession?.jwtToken) {
251
- const { id: userId } = jwt.decodeJwt(llmSession.jwtToken);
252
- if (userId) {
253
- const user = await UserModel.findByPk(userId);
254
- if (user?.accessToken) {
255
- toolArgs.jwtToken = llmSession.jwtToken;
256
- }
257
- }
258
- }
259
- }
260
- }
261
-
262
- try {
263
- const tool = tools.tools.find(t => t.definition.name === toolName);
264
- if (!tool) throw new Error(`Tool not found: ${toolName}`);
265
-
266
- const result = await tool.execute(toolArgs);
267
-
268
- if (result?.structuredContent) {
269
- response = {
270
- jsonrpc: '2.0',
271
- id,
272
- result: {
273
- structuredContent: result.structuredContent,
274
- content: Array.isArray(result.content)
275
- ? result.content
276
- : [{ type: 'text', text: '[Interactive widget displayed above - no additional response needed]' }],
277
- },
278
- };
279
- } else {
280
- response = {
281
- jsonrpc: '2.0',
282
- id,
283
- result: {
284
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
285
- },
286
- };
287
- }
288
- } catch (toolError) {
289
- response = {
290
- jsonrpc: '2.0',
291
- id,
292
- error: {
293
- code: JSON_RPC_INTERNAL_ERROR,
294
- message: `Tool execution failed: ${toolError.message}`,
295
- },
296
- };
297
- }
298
- break;
299
- }
300
-
301
- case 'resources/list':
302
- response = {
303
- jsonrpc: '2.0',
304
- id,
305
- result: {
306
- resources: [{
307
- uri: WIDGET_URI,
308
- name: 'connector-list-widget',
309
- title: 'ConnectorList',
310
- description: 'ChatGPT widget for connector selection',
311
- mimeType: 'text/html+skybridge',
312
- }],
313
- },
314
- };
315
- break;
316
-
317
- case 'resources/read': {
318
- const uri = params?.uri;
319
- if (!uri?.startsWith('ui://widget/')) {
320
- response = {
321
- jsonrpc: '2.0',
322
- id,
323
- error: { code: JSON_RPC_INVALID_PARAMS, message: `Unknown resource: ${uri}` },
324
- };
325
- break;
326
- }
327
-
328
- const appUrl = process.env.APP_SERVER || 'http://localhost:6066';
329
- const distPath = path.join(__dirname, 'ui', 'dist', 'index.html');
330
- const devPath = path.join(__dirname, 'ui', 'index.html');
331
- let htmlContent;
332
- try { htmlContent = fs.readFileSync(distPath, 'utf8'); }
333
- catch { htmlContent = fs.readFileSync(devPath, 'utf8'); }
334
-
335
- response = {
336
- jsonrpc: '2.0',
337
- id,
338
- result: {
339
- contents: [{
340
- uri: WIDGET_URI,
341
- mimeType: 'text/html+skybridge',
342
- text: htmlContent,
343
- _meta: {
344
- 'openai/widgetPrefersBorder': true,
345
- 'openai/widgetDomain': appUrl,
346
- 'openai/widgetCSP': {
347
- connect_domains: [appUrl, 'https://appconnect.labs.ringcentral.com'],
348
- resource_domains: [appUrl],
349
- },
350
- },
351
- }],
352
- },
353
- };
354
- break;
355
- }
356
-
357
- case 'ping':
358
- response = { jsonrpc: '2.0', id, result: {} };
359
- break;
360
-
361
- case 'notifications/initialized':
362
- case 'notifications/cancelled':
363
- // JSON-RPC notifications — no id, no response expected
364
- return res.status(200).end();
365
-
366
- default:
367
- response = {
368
- jsonrpc: '2.0',
369
- id,
370
- error: { code: JSON_RPC_METHOD_NOT_FOUND, message: `Method not found: ${method}` },
371
- };
372
- }
373
-
374
- res.status(200).json(response);
375
- } catch (error) {
376
- logger.error('Error handling MCP request:', { stack: error.stack });
377
- res.status(200).json({
378
- jsonrpc: '2.0',
379
- id: req.body?.id || null,
380
- error: {
381
- code: JSON_RPC_INTERNAL_ERROR,
382
- message: 'Internal server error',
383
- data: { error: error.message },
384
- },
385
- });
386
- }
387
- }
388
-
389
- /**
390
- * Handle widget tool calls via direct HTTP (bypasses MCP protocol).
391
- * The ChatGPT postMessage bridge does not forward tool arguments,
392
- * so the widget uses fetch() to this endpoint instead.
393
- */
394
- async function handleWidgetToolCall(req, res) {
395
- try {
396
- logger.info('Widget tool call received. body:', JSON.stringify(req.body));
397
-
398
- const { tool: toolName, toolArgs: args } = req.body || {};
399
-
400
- logger.info('Widget tool call parsed:', { toolName, args: JSON.stringify(args) });
401
-
402
- if (!toolName) {
403
- return res.status(400).json({ success: false, error: 'Missing tool name' });
404
- }
405
-
406
- const allWidgetCallable = [...tools.tools, ...tools.widgetTools];
407
- const tool = allWidgetCallable.find(t => t.definition.name === toolName);
408
- if (!tool) {
409
- return res.status(404).json({ success: false, error: `Unknown tool: ${toolName}` });
410
- }
411
-
412
- const result = await tool.execute(args || {});
413
- logger.info('Widget tool call result:', { toolName, success: result?.success });
414
- res.json(result);
415
- } catch (error) {
416
- logger.error('Widget tool call error:', { stack: error.stack });
417
- res.status(500).json({
418
- success: false,
419
- error: error.message || 'Internal server error',
420
- });
421
- }
422
- }
423
-
424
- exports.handleMcpRequest = handleMcpRequest;
425
- exports.handleWidgetToolCall = handleWidgetToolCall;
1
+ /**
2
+ * MCP Server for RC Unified CRM Extension
3
+ *
4
+ * Stateless hand-rolled JSON-RPC handler — no SDK, no SSE, no sessions Map.
5
+ * Fully compatible with stateless deployments (AWS Lambda, etc.).
6
+ * All auth context is resolved per-request; rcExtensionId is cached in CacheModel.
7
+ */
8
+
9
+ const axios = require('axios');
10
+ const { Op } = require('sequelize');
11
+ const tools = require('./tools');
12
+ const { LlmSessionModel } = require('../models/llmSessionModel');
13
+ const { CacheModel } = require('../models/cacheModel');
14
+ const { UserModel } = require('../models/userModel');
15
+ const { getHashValue } = require('../lib/util');
16
+ const jwt = require('../lib/jwt');
17
+ const logger = require('../lib/logger');
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+
21
+ /**
22
+ * Increment this to bust ChatGPT's widget resource cache after every UI build.
23
+ * This is the single source of truth — injected into getPublicConnectors _meta at response time.
24
+ */
25
+ const WIDGET_VERSION = 10;
26
+ const WIDGET_URI = `ui://widget/ConnectorList-v${WIDGET_VERSION}.html`;
27
+ const RC_EXTENSION_CACHE_KEY = 'rcExtensionId';
28
+ const RC_EXTENSION_CACHE_STATUS = 'resolved';
29
+
30
+ const JSON_RPC_INTERNAL_ERROR = -32603;
31
+ const JSON_RPC_METHOD_NOT_FOUND = -32601;
32
+ const JSON_RPC_INVALID_PARAMS = -32602;
33
+
34
+ /**
35
+ * JSON Schema definitions for tools that accept parameters.
36
+ * Without inputSchema, ChatGPT silently drops all arguments when calling the tool.
37
+ */
38
+ const inputSchemas = {
39
+ findContactByName: {
40
+ type: 'object',
41
+ properties: {
42
+ name: { type: 'string', description: 'Name to search for' },
43
+ },
44
+ required: ['name'],
45
+ },
46
+ findContactByPhone: {
47
+ type: 'object',
48
+ properties: {
49
+ phoneNumber: { type: 'string', description: 'Phone number in E.164 format (e.g. +14155551234)' },
50
+ overridingFormat: { type: 'string', description: 'Overriding format to search for' },
51
+ isExtension: { type: 'boolean', description: 'Whether the request is from an extension' },
52
+ },
53
+ required: ['phoneNumber'],
54
+ },
55
+ createContact: {
56
+ type: 'object',
57
+ properties: {
58
+ phoneNumber: { type: 'string', description: 'Phone number in E.164 format (e.g. +14155551234)' },
59
+ newContactName: { type: 'string', description: 'Full name of the new contact' },
60
+ },
61
+ required: ['phoneNumber'],
62
+ },
63
+ createCallLog: {
64
+ type: 'object',
65
+ properties: {
66
+ incomingData: { description: 'Call log data to create' },
67
+ contactId: { type: 'string', description: 'CRM contact ID to attach the log to' },
68
+ contactType: { type: 'string', description: 'Type of the CRM contact' },
69
+ note: { type: 'string', description: 'Note to include in the call log' },
70
+ },
71
+ required: [],
72
+ },
73
+ rcGetCallLogs: {
74
+ type: 'object',
75
+ properties: {
76
+ timeFrom: { type: 'string', description: 'Start of time range in ISO 8601 format' },
77
+ timeTo: { type: 'string', description: 'End of time range in ISO 8601 format' },
78
+ },
79
+ required: ['timeFrom', 'timeTo'],
80
+ },
81
+ logout: {
82
+ type: 'object',
83
+ properties: {},
84
+ required: [],
85
+ },
86
+ };
87
+
88
+ /**
89
+ * Verify an RC access token and return the caller's extension ID.
90
+ * Throws if the token is invalid.
91
+ */
92
+ async function resolveRcExtensionId(rcAccessToken) {
93
+ const resp = await axios.get(
94
+ 'https://platform.ringcentral.com/restapi/v1.0/account/~/extension/~',
95
+ { headers: { Authorization: `Bearer ${rcAccessToken}` } }
96
+ );
97
+ return resp.data?.id?.toString() ?? null;
98
+ }
99
+
100
+ /**
101
+ * Resolve rcExtensionId for the current request.
102
+ * Checks CacheModel first (avoids RC API call on Lambda cold starts),
103
+ * falls back to a live RC API verification and persists the result.
104
+ */
105
+ async function resolveSessionContext(rcAccessToken, openaiSessionId) {
106
+ if (!rcAccessToken) return { rcExtensionId: null };
107
+
108
+ if (openaiSessionId) {
109
+ try {
110
+ const cached = await CacheModel.findByPk(`${openaiSessionId}-${RC_EXTENSION_CACHE_KEY}`);
111
+ if (cached?.data?.rcExtensionId && (!cached.expiry || cached.expiry > new Date())) {
112
+ return { rcExtensionId: cached.data.rcExtensionId };
113
+ }
114
+ } catch (err) {
115
+ logger.warn('CacheModel lookup failed:', { message: err.message });
116
+ }
117
+ }
118
+
119
+ let rcExtensionId = null;
120
+ try {
121
+ rcExtensionId = await resolveRcExtensionId(rcAccessToken);
122
+ if (openaiSessionId && rcExtensionId) {
123
+ await CacheModel.upsert({
124
+ id: `${openaiSessionId}-${RC_EXTENSION_CACHE_KEY}`,
125
+ userId: openaiSessionId,
126
+ cacheKey: RC_EXTENSION_CACHE_KEY,
127
+ data: { rcExtensionId },
128
+ status: RC_EXTENSION_CACHE_STATUS,
129
+ expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24h TTL
130
+ });
131
+ }
132
+ } catch (err) {
133
+ logger.warn('Failed to resolve RC extension ID:', { message: err.message });
134
+ }
135
+
136
+ return { rcExtensionId };
137
+ }
138
+
139
+ /**
140
+ * Build the tools list to return in tools/list responses.
141
+ * Injects inputSchema and stamps WIDGET_URI into getPublicConnectors _meta.
142
+ */
143
+ function getToolsList() {
144
+ return tools.tools.map(tool => {
145
+ const def = { ...tool.definition };
146
+ if (def.name === 'getPublicConnectors') {
147
+ def._meta = { ...(def._meta || {}), 'openai/outputTemplate': WIDGET_URI };
148
+ }
149
+ if (inputSchemas[def.name]) {
150
+ def.inputSchema = inputSchemas[def.name];
151
+ }
152
+ return def;
153
+ });
154
+ }
155
+
156
+ /**
157
+ * Handle incoming MCP HTTP requests.
158
+ * Stateless: each POST is handled independently with no session state between requests.
159
+ */
160
+ async function handleMcpRequest(req, res) {
161
+ try {
162
+ const { method, params, id } = req.body;
163
+ logger.info('Received MCP request:', { method });
164
+
165
+ const rcAccessToken = req.headers['authorization']?.split('Bearer ')?.[1];
166
+ const openaiSessionId = params?._meta?.['openai/session'] ?? null;
167
+
168
+ let response;
169
+
170
+ switch (method) {
171
+ case 'initialize':
172
+ response = {
173
+ jsonrpc: '2.0',
174
+ id,
175
+ result: {
176
+ protocolVersion: '2024-11-05',
177
+ capabilities: {
178
+ tools: {},
179
+ resources: {},
180
+ },
181
+ serverInfo: {
182
+ name: 'rc-unified-crm-extension',
183
+ version: '1.0.0',
184
+ },
185
+ },
186
+ };
187
+ break;
188
+
189
+ case 'tools/list':
190
+ response = {
191
+ jsonrpc: '2.0',
192
+ id,
193
+ result: { tools: getToolsList() },
194
+ };
195
+ break;
196
+
197
+ case 'tools/call': {
198
+ const { name: toolName, arguments: args } = params;
199
+ const toolArgs = { ...(args || {}) };
200
+
201
+ if (rcAccessToken) toolArgs.rcAccessToken = rcAccessToken;
202
+ if (openaiSessionId) toolArgs.openaiSessionId = openaiSessionId;
203
+
204
+ const { rcExtensionId } = await resolveSessionContext(rcAccessToken, openaiSessionId);
205
+ if (rcExtensionId) {
206
+ toolArgs.rcExtensionId = rcExtensionId;
207
+ if (!toolArgs.jwtToken) {
208
+ let llmSession = await LlmSessionModel.findByPk(rcExtensionId);
209
+ if (llmSession?.expiry && llmSession.expiry < new Date()) {
210
+ await LlmSessionModel.destroy({ where: { id: rcExtensionId } });
211
+ llmSession = null;
212
+ }
213
+ if (!llmSession?.jwtToken && openaiSessionId) {
214
+ const fallback = await LlmSessionModel.findByPk(openaiSessionId);
215
+ if (fallback?.jwtToken) {
216
+ const { id: fallbackUserId } = jwt.decodeJwt(fallback.jwtToken);
217
+ const fallbackUser = fallbackUserId
218
+ ? await UserModel.findByPk(fallbackUserId)
219
+ : null;
220
+ if (fallbackUser?.accessToken) {
221
+ await LlmSessionModel.upsert({ id: rcExtensionId, jwtToken: fallback.jwtToken, expiry: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000) });
222
+ llmSession = fallback;
223
+ }
224
+ }
225
+ if (!llmSession?.jwtToken) {
226
+ const hashedRcExtensionId = getHashValue(rcExtensionId, process.env.HASH_KEY);
227
+ const user = await UserModel.findOne({
228
+ where: {
229
+ hashedRcExtensionId,
230
+ [Op.and]: [
231
+ { accessToken: { [Op.not]: null } },
232
+ { accessToken: { [Op.ne]: '' } },
233
+ ],
234
+ },
235
+ order: [['updatedAt', 'DESC']],
236
+ });
237
+ if (user?.accessToken) {
238
+ await LlmSessionModel.upsert({
239
+ id: rcExtensionId,
240
+ jwtToken: jwt.generateJwt({
241
+ id: user.id.toString(),
242
+ platform: user.platform
243
+ }),
244
+ expiry: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
245
+ });
246
+ llmSession = await LlmSessionModel.findByPk(rcExtensionId);
247
+ }
248
+ }
249
+ }
250
+ if (llmSession?.jwtToken) {
251
+ const { id: userId } = jwt.decodeJwt(llmSession.jwtToken);
252
+ if (userId) {
253
+ const user = await UserModel.findByPk(userId);
254
+ if (user?.accessToken) {
255
+ toolArgs.jwtToken = llmSession.jwtToken;
256
+ }
257
+ }
258
+ }
259
+ }
260
+ }
261
+
262
+ try {
263
+ const tool = tools.tools.find(t => t.definition.name === toolName);
264
+ if (!tool) throw new Error(`Tool not found: ${toolName}`);
265
+
266
+ const result = await tool.execute(toolArgs);
267
+
268
+ if (result?.structuredContent) {
269
+ response = {
270
+ jsonrpc: '2.0',
271
+ id,
272
+ result: {
273
+ structuredContent: result.structuredContent,
274
+ content: Array.isArray(result.content)
275
+ ? result.content
276
+ : [{ type: 'text', text: '[Interactive widget displayed above - no additional response needed]' }],
277
+ },
278
+ };
279
+ } else {
280
+ response = {
281
+ jsonrpc: '2.0',
282
+ id,
283
+ result: {
284
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
285
+ },
286
+ };
287
+ }
288
+ } catch (toolError) {
289
+ response = {
290
+ jsonrpc: '2.0',
291
+ id,
292
+ error: {
293
+ code: JSON_RPC_INTERNAL_ERROR,
294
+ message: `Tool execution failed: ${toolError.message}`,
295
+ },
296
+ };
297
+ }
298
+ break;
299
+ }
300
+
301
+ case 'resources/list':
302
+ response = {
303
+ jsonrpc: '2.0',
304
+ id,
305
+ result: {
306
+ resources: [{
307
+ uri: WIDGET_URI,
308
+ name: 'connector-list-widget',
309
+ title: 'ConnectorList',
310
+ description: 'ChatGPT widget for connector selection',
311
+ mimeType: 'text/html+skybridge',
312
+ }],
313
+ },
314
+ };
315
+ break;
316
+
317
+ case 'resources/read': {
318
+ const uri = params?.uri;
319
+ if (!uri?.startsWith('ui://widget/')) {
320
+ response = {
321
+ jsonrpc: '2.0',
322
+ id,
323
+ error: { code: JSON_RPC_INVALID_PARAMS, message: `Unknown resource: ${uri}` },
324
+ };
325
+ break;
326
+ }
327
+
328
+ const appUrl = process.env.APP_SERVER || 'http://localhost:6066';
329
+ const distPath = path.join(__dirname, 'ui', 'dist', 'index.html');
330
+ const devPath = path.join(__dirname, 'ui', 'index.html');
331
+ let htmlContent;
332
+ try { htmlContent = fs.readFileSync(distPath, 'utf8'); }
333
+ catch { htmlContent = fs.readFileSync(devPath, 'utf8'); }
334
+
335
+ response = {
336
+ jsonrpc: '2.0',
337
+ id,
338
+ result: {
339
+ contents: [{
340
+ uri: WIDGET_URI,
341
+ mimeType: 'text/html+skybridge',
342
+ text: htmlContent,
343
+ _meta: {
344
+ 'openai/widgetPrefersBorder': true,
345
+ 'openai/widgetDomain': appUrl,
346
+ 'openai/widgetCSP': {
347
+ connect_domains: [appUrl, 'https://appconnect.labs.ringcentral.com'],
348
+ resource_domains: [appUrl],
349
+ },
350
+ },
351
+ }],
352
+ },
353
+ };
354
+ break;
355
+ }
356
+
357
+ case 'ping':
358
+ response = { jsonrpc: '2.0', id, result: {} };
359
+ break;
360
+
361
+ case 'notifications/initialized':
362
+ case 'notifications/cancelled':
363
+ // JSON-RPC notifications — no id, no response expected
364
+ return res.status(200).end();
365
+
366
+ default:
367
+ response = {
368
+ jsonrpc: '2.0',
369
+ id,
370
+ error: { code: JSON_RPC_METHOD_NOT_FOUND, message: `Method not found: ${method}` },
371
+ };
372
+ }
373
+
374
+ res.status(200).json(response);
375
+ } catch (error) {
376
+ logger.error('Error handling MCP request:', { stack: error.stack });
377
+ res.status(200).json({
378
+ jsonrpc: '2.0',
379
+ id: req.body?.id || null,
380
+ error: {
381
+ code: JSON_RPC_INTERNAL_ERROR,
382
+ message: 'Internal server error',
383
+ data: { error: error.message },
384
+ },
385
+ });
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Handle widget tool calls via direct HTTP (bypasses MCP protocol).
391
+ * The ChatGPT postMessage bridge does not forward tool arguments,
392
+ * so the widget uses fetch() to this endpoint instead.
393
+ */
394
+ async function handleWidgetToolCall(req, res) {
395
+ try {
396
+ logger.info('Widget tool call received. body:', JSON.stringify(req.body));
397
+
398
+ const { tool: toolName, toolArgs: args } = req.body || {};
399
+
400
+ logger.info('Widget tool call parsed:', { toolName, args: JSON.stringify(args) });
401
+
402
+ if (!toolName) {
403
+ return res.status(400).json({ success: false, error: 'Missing tool name' });
404
+ }
405
+
406
+ const allWidgetCallable = [...tools.tools, ...tools.widgetTools];
407
+ const tool = allWidgetCallable.find(t => t.definition.name === toolName);
408
+ if (!tool) {
409
+ return res.status(404).json({ success: false, error: `Unknown tool: ${toolName}` });
410
+ }
411
+
412
+ const result = await tool.execute(args || {});
413
+ logger.info('Widget tool call result:', { toolName, success: result?.success });
414
+ res.json(result);
415
+ } catch (error) {
416
+ logger.error('Widget tool call error:', { stack: error.stack });
417
+ res.status(500).json({
418
+ success: false,
419
+ error: error.message || 'Internal server error',
420
+ });
421
+ }
422
+ }
423
+
424
+ exports.handleMcpRequest = handleMcpRequest;
425
+ exports.handleWidgetToolCall = handleWidgetToolCall;