@app-connect/core 1.7.18 → 1.7.20

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 (60) hide show
  1. package/connector/proxy/index.js +2 -1
  2. package/handlers/auth.js +30 -55
  3. package/handlers/log.js +182 -10
  4. package/handlers/plugin.js +27 -0
  5. package/handlers/user.js +31 -2
  6. package/index.js +115 -22
  7. package/lib/authSession.js +21 -12
  8. package/lib/callLogComposer.js +1 -1
  9. package/lib/debugTracer.js +20 -2
  10. package/lib/util.js +21 -4
  11. package/mcp/README.md +395 -0
  12. package/mcp/mcpHandler.js +318 -82
  13. package/mcp/tools/checkAuthStatus.js +28 -35
  14. package/mcp/tools/createCallLog.js +13 -9
  15. package/mcp/tools/createContact.js +2 -6
  16. package/mcp/tools/doAuth.js +27 -157
  17. package/mcp/tools/findContactByName.js +6 -9
  18. package/mcp/tools/findContactByPhone.js +2 -6
  19. package/mcp/tools/getGoogleFilePicker.js +5 -9
  20. package/mcp/tools/getHelp.js +2 -3
  21. package/mcp/tools/getPublicConnectors.js +55 -24
  22. package/mcp/tools/index.js +11 -36
  23. package/mcp/tools/logout.js +32 -13
  24. package/mcp/tools/rcGetCallLogs.js +3 -20
  25. package/mcp/ui/App/App.tsx +358 -0
  26. package/mcp/ui/App/components/AuthInfoForm.tsx +113 -0
  27. package/mcp/ui/App/components/AuthSuccess.tsx +22 -0
  28. package/mcp/ui/App/components/ConnectorList.tsx +82 -0
  29. package/mcp/ui/App/components/DebugPanel.tsx +43 -0
  30. package/mcp/ui/App/components/OAuthConnect.tsx +270 -0
  31. package/mcp/ui/App/lib/callTool.ts +130 -0
  32. package/mcp/ui/App/lib/debugLog.ts +41 -0
  33. package/mcp/ui/App/lib/developerPortal.ts +111 -0
  34. package/mcp/ui/App/main.css +6 -0
  35. package/mcp/ui/App/root.tsx +13 -0
  36. package/mcp/ui/dist/index.html +53 -0
  37. package/mcp/ui/index.html +13 -0
  38. package/mcp/ui/package-lock.json +6356 -0
  39. package/mcp/ui/package.json +25 -0
  40. package/mcp/ui/tsconfig.json +26 -0
  41. package/mcp/ui/vite.config.ts +16 -0
  42. package/models/llmSessionModel.js +14 -0
  43. package/models/userModel.js +3 -0
  44. package/package.json +2 -2
  45. package/releaseNotes.json +24 -0
  46. package/test/handlers/auth.test.js +31 -0
  47. package/test/handlers/plugin.test.js +287 -0
  48. package/test/lib/util.test.js +379 -1
  49. package/test/mcp/tools/createCallLog.test.js +3 -3
  50. package/test/mcp/tools/doAuth.test.js +40 -303
  51. package/test/mcp/tools/findContactByName.test.js +3 -3
  52. package/test/mcp/tools/findContactByPhone.test.js +3 -3
  53. package/test/mcp/tools/getGoogleFilePicker.test.js +7 -7
  54. package/test/mcp/tools/getPublicConnectors.test.js +49 -70
  55. package/test/mcp/tools/logout.test.js +17 -11
  56. package/mcp/SupportedPlatforms.md +0 -12
  57. package/mcp/tools/collectAuthInfo.js +0 -91
  58. package/mcp/tools/setConnector.js +0 -69
  59. package/test/mcp/tools/collectAuthInfo.test.js +0 -234
  60. package/test/mcp/tools/setConnector.test.js +0 -177
package/mcp/mcpHandler.js CHANGED
@@ -1,21 +1,167 @@
1
1
  /**
2
2
  * MCP Server for RC Unified CRM Extension
3
- *
4
- * This module provides MCP (Model Context Protocol) interface for the CRM extension.
5
- * It exposes tools that can be called by AI assistants or other MCP clients.
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.
6
7
  */
7
8
 
9
+ const axios = require('axios');
8
10
  const tools = require('./tools');
11
+ const { LlmSessionModel } = require('../models/llmSessionModel');
12
+ const { CacheModel } = require('../models/cacheModel');
13
+ const { UserModel } = require('../models/userModel');
14
+ const { getHashValue } = require('../lib/util');
15
+ const jwt = require('../lib/jwt');
9
16
  const logger = require('../lib/logger');
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+
20
+ /**
21
+ * Increment this to bust ChatGPT's widget resource cache after every UI build.
22
+ * This is the single source of truth — injected into getPublicConnectors _meta at response time.
23
+ */
24
+ const WIDGET_VERSION = 10;
25
+ const WIDGET_URI = `ui://widget/ConnectorList-v${WIDGET_VERSION}.html`;
10
26
 
11
27
  const JSON_RPC_INTERNAL_ERROR = -32603;
12
28
  const JSON_RPC_METHOD_NOT_FOUND = -32601;
29
+ const JSON_RPC_INVALID_PARAMS = -32602;
30
+
31
+ /**
32
+ * JSON Schema definitions for tools that accept parameters.
33
+ * Without inputSchema, ChatGPT silently drops all arguments when calling the tool.
34
+ */
35
+ const inputSchemas = {
36
+ findContactByName: {
37
+ type: 'object',
38
+ properties: {
39
+ name: { type: 'string', description: 'Name to search for' },
40
+ },
41
+ required: ['name'],
42
+ },
43
+ findContactByPhone: {
44
+ type: 'object',
45
+ properties: {
46
+ phoneNumber: { type: 'string', description: 'Phone number in E.164 format (e.g. +14155551234)' },
47
+ overridingFormat: { type: 'string', description: 'Overriding format to search for' },
48
+ isExtension: { type: 'boolean', description: 'Whether the request is from an extension' },
49
+ },
50
+ required: ['phoneNumber'],
51
+ },
52
+ createContact: {
53
+ type: 'object',
54
+ properties: {
55
+ phoneNumber: { type: 'string', description: 'Phone number in E.164 format (e.g. +14155551234)' },
56
+ newContactName: { type: 'string', description: 'Full name of the new contact' },
57
+ },
58
+ required: ['phoneNumber'],
59
+ },
60
+ createCallLog: {
61
+ type: 'object',
62
+ properties: {
63
+ incomingData: { description: 'Call log data to create' },
64
+ contactId: { type: 'string', description: 'CRM contact ID to attach the log to' },
65
+ contactType: { type: 'string', description: 'Type of the CRM contact' },
66
+ note: { type: 'string', description: 'Note to include in the call log' },
67
+ },
68
+ required: [],
69
+ },
70
+ rcGetCallLogs: {
71
+ type: 'object',
72
+ properties: {
73
+ timeFrom: { type: 'string', description: 'Start of time range in ISO 8601 format' },
74
+ timeTo: { type: 'string', description: 'End of time range in ISO 8601 format' },
75
+ },
76
+ required: ['timeFrom', 'timeTo'],
77
+ },
78
+ logout: {
79
+ type: 'object',
80
+ properties: {},
81
+ required: [],
82
+ },
83
+ };
84
+
85
+ /**
86
+ * Verify an RC access token and return the caller's extension ID.
87
+ * Throws if the token is invalid.
88
+ */
89
+ async function resolveRcExtensionId(rcAccessToken) {
90
+ const resp = await axios.get(
91
+ 'https://platform.ringcentral.com/restapi/v1.0/account/~/extension/~',
92
+ { headers: { Authorization: `Bearer ${rcAccessToken}` } }
93
+ );
94
+ return resp.data?.id?.toString() ?? null;
95
+ }
96
+
97
+ /**
98
+ * Resolve rcExtensionId for the current request.
99
+ * Checks CacheModel first (avoids RC API call on Lambda cold starts),
100
+ * falls back to a live RC API verification and persists the result.
101
+ */
102
+ async function resolveSessionContext(rcAccessToken, openaiSessionId) {
103
+ if (!rcAccessToken) return { rcExtensionId: null };
13
104
 
105
+ if (openaiSessionId) {
106
+ try {
107
+ const cached = await CacheModel.findByPk(`${openaiSessionId}-rcExtensionId`);
108
+ if (cached?.data?.rcExtensionId && (!cached.expiry || cached.expiry > new Date())) {
109
+ return { rcExtensionId: cached.data.rcExtensionId };
110
+ }
111
+ } catch (err) {
112
+ logger.warn('CacheModel lookup failed:', { message: err.message });
113
+ }
114
+ }
115
+
116
+ let rcExtensionId = null;
117
+ try {
118
+ rcExtensionId = await resolveRcExtensionId(rcAccessToken);
119
+ if (openaiSessionId && rcExtensionId) {
120
+ await CacheModel.upsert({
121
+ id: `${openaiSessionId}-rcExtensionId`,
122
+ userId: openaiSessionId,
123
+ cacheKey: 'rcExtensionId',
124
+ data: { rcExtensionId },
125
+ status: 'active',
126
+ expiry: new Date(Date.now() + 24 * 60 * 60 * 1000), // 24h TTL
127
+ });
128
+ }
129
+ } catch (err) {
130
+ logger.warn('Failed to resolve RC extension ID:', { message: err.message });
131
+ }
132
+
133
+ return { rcExtensionId };
134
+ }
135
+
136
+ /**
137
+ * Build the tools list to return in tools/list responses.
138
+ * Injects inputSchema and stamps WIDGET_URI into getPublicConnectors _meta.
139
+ */
140
+ function getToolsList() {
141
+ return tools.tools.map(tool => {
142
+ const def = { ...tool.definition };
143
+ if (def.name === 'getPublicConnectors') {
144
+ def._meta = { ...(def._meta || {}), 'openai/outputTemplate': WIDGET_URI };
145
+ }
146
+ if (inputSchemas[def.name]) {
147
+ def.inputSchema = inputSchemas[def.name];
148
+ }
149
+ return def;
150
+ });
151
+ }
152
+
153
+ /**
154
+ * Handle incoming MCP HTTP requests.
155
+ * Stateless: each POST is handled independently with no session state between requests.
156
+ */
14
157
  async function handleMcpRequest(req, res) {
15
158
  try {
16
159
  const { method, params, id } = req.body;
17
160
  logger.info('Received MCP request:', { method });
18
161
 
162
+ const rcAccessToken = req.headers['authorization']?.split('Bearer ')?.[1];
163
+ const openaiSessionId = params?._meta?.['openai/session'] ?? null;
164
+
19
165
  let response;
20
166
 
21
167
  switch (method) {
@@ -27,44 +173,95 @@ async function handleMcpRequest(req, res) {
27
173
  protocolVersion: '2024-11-05',
28
174
  capabilities: {
29
175
  tools: {},
30
- prompts: {}
176
+ resources: {},
31
177
  },
32
178
  serverInfo: {
33
179
  name: 'rc-unified-crm-extension',
34
- version: '1.0.0'
35
- }
36
- }
180
+ version: '1.0.0',
181
+ },
182
+ },
37
183
  };
38
184
  break;
185
+
39
186
  case 'tools/list':
40
187
  response = {
41
188
  jsonrpc: '2.0',
42
189
  id,
43
- result: {
44
- tools: getTools()
45
- }
190
+ result: { tools: getToolsList() },
46
191
  };
47
192
  break;
48
- case 'tools/call':
193
+
194
+ case 'tools/call': {
49
195
  const { name: toolName, arguments: args } = params;
50
- const rcAccessToken = req.headers['authorization']?.split('Bearer ')?.[1];
51
- if (args && rcAccessToken) {
52
- args.rcAccessToken = rcAccessToken;
53
- }
54
- try {
55
- const result = await executeTool(toolName, args || {});
56
- response = {
57
- jsonrpc: '2.0',
58
- id,
59
- result: {
60
- content: [
61
- {
62
- type: 'text',
63
- text: JSON.stringify(result, null, 2)
196
+ const toolArgs = { ...(args || {}) };
197
+
198
+ if (rcAccessToken) toolArgs.rcAccessToken = rcAccessToken;
199
+ if (openaiSessionId) toolArgs.openaiSessionId = openaiSessionId;
200
+
201
+ const { rcExtensionId } = await resolveSessionContext(rcAccessToken, openaiSessionId);
202
+ if (rcExtensionId) {
203
+ toolArgs.rcExtensionId = rcExtensionId;
204
+ if (!toolArgs.jwtToken) {
205
+ let llmSession = await LlmSessionModel.findByPk(rcExtensionId);
206
+ if (!llmSession?.jwtToken && openaiSessionId) {
207
+ const fallback = await LlmSessionModel.findByPk(openaiSessionId);
208
+ if (fallback?.jwtToken) {
209
+ await LlmSessionModel.upsert({ id: rcExtensionId, jwtToken: fallback.jwtToken });
210
+ llmSession = fallback;
211
+ }
212
+ else {
213
+ const hashedRcExtensionId = getHashValue(rcExtensionId, process.env.HASH_KEY);
214
+ const user = await UserModel.findOne({ where: { hashedRcExtensionId } });
215
+ if (user?.accessToken) {
216
+ await LlmSessionModel.upsert({
217
+ id: rcExtensionId,
218
+ jwtToken: jwt.generateJwt({
219
+ id: user.id.toString(),
220
+ platform: user.platform
221
+ }),
222
+ });
223
+ llmSession = await LlmSessionModel.findByPk(rcExtensionId);
64
224
  }
65
- ]
225
+ }
66
226
  }
67
- };
227
+ if (llmSession?.jwtToken) {
228
+ const { id: userId } = jwt.decodeJwt(llmSession.jwtToken);
229
+ if (userId) {
230
+ const user = await UserModel.findByPk(userId);
231
+ if (user?.accessToken) {
232
+ toolArgs.jwtToken = llmSession.jwtToken;
233
+ }
234
+ }
235
+ }
236
+ }
237
+ }
238
+
239
+ try {
240
+ const tool = tools.tools.find(t => t.definition.name === toolName);
241
+ if (!tool) throw new Error(`Tool not found: ${toolName}`);
242
+
243
+ const result = await tool.execute(toolArgs);
244
+
245
+ if (result?.structuredContent) {
246
+ response = {
247
+ jsonrpc: '2.0',
248
+ id,
249
+ result: {
250
+ structuredContent: result.structuredContent,
251
+ content: Array.isArray(result.content)
252
+ ? result.content
253
+ : [{ type: 'text', text: '[Interactive widget displayed above - no additional response needed]' }],
254
+ },
255
+ };
256
+ } else {
257
+ response = {
258
+ jsonrpc: '2.0',
259
+ id,
260
+ result: {
261
+ content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
262
+ },
263
+ };
264
+ }
68
265
  } catch (toolError) {
69
266
  response = {
70
267
  jsonrpc: '2.0',
@@ -72,95 +269,134 @@ async function handleMcpRequest(req, res) {
72
269
  error: {
73
270
  code: JSON_RPC_INTERNAL_ERROR,
74
271
  message: `Tool execution failed: ${toolError.message}`,
75
- data: {
76
- error: toolError.message,
77
- stack: process.env.NODE_ENV !== 'production' ? toolError.stack : undefined
78
- }
79
- }
272
+ },
80
273
  };
81
274
  }
82
275
  break;
83
- case 'ping':
276
+ }
277
+
278
+ case 'resources/list':
84
279
  response = {
85
280
  jsonrpc: '2.0',
86
281
  id,
87
- result: {}
282
+ result: {
283
+ resources: [{
284
+ uri: WIDGET_URI,
285
+ name: 'connector-list-widget',
286
+ title: 'ConnectorList',
287
+ description: 'ChatGPT widget for connector selection',
288
+ mimeType: 'text/html+skybridge',
289
+ }],
290
+ },
88
291
  };
89
292
  break;
293
+
294
+ case 'resources/read': {
295
+ const uri = params?.uri;
296
+ if (!uri?.startsWith('ui://widget/')) {
297
+ response = {
298
+ jsonrpc: '2.0',
299
+ id,
300
+ error: { code: JSON_RPC_INVALID_PARAMS, message: `Unknown resource: ${uri}` },
301
+ };
302
+ break;
303
+ }
304
+
305
+ const appUrl = process.env.APP_SERVER || 'http://localhost:6066';
306
+ const distPath = path.join(__dirname, 'ui', 'dist', 'index.html');
307
+ const devPath = path.join(__dirname, 'ui', 'index.html');
308
+ let htmlContent;
309
+ try { htmlContent = fs.readFileSync(distPath, 'utf8'); }
310
+ catch { htmlContent = fs.readFileSync(devPath, 'utf8'); }
311
+
312
+ response = {
313
+ jsonrpc: '2.0',
314
+ id,
315
+ result: {
316
+ contents: [{
317
+ uri: WIDGET_URI,
318
+ mimeType: 'text/html+skybridge',
319
+ text: htmlContent,
320
+ _meta: {
321
+ 'openai/widgetPrefersBorder': true,
322
+ 'openai/widgetDomain': appUrl,
323
+ 'openai/widgetCSP': {
324
+ connect_domains: [appUrl, 'https://appconnect.labs.ringcentral.com'],
325
+ resource_domains: [appUrl],
326
+ },
327
+ },
328
+ }],
329
+ },
330
+ };
331
+ break;
332
+ }
333
+
334
+ case 'ping':
335
+ response = { jsonrpc: '2.0', id, result: {} };
336
+ break;
337
+
338
+ case 'notifications/initialized':
339
+ case 'notifications/cancelled':
340
+ // JSON-RPC notifications — no id, no response expected
341
+ return res.status(200).end();
342
+
90
343
  default:
91
344
  response = {
92
345
  jsonrpc: '2.0',
93
346
  id,
94
- error: {
95
- code: JSON_RPC_METHOD_NOT_FOUND,
96
- message: `Method not found: ${method}`
97
- }
347
+ error: { code: JSON_RPC_METHOD_NOT_FOUND, message: `Method not found: ${method}` },
98
348
  };
99
349
  }
100
350
 
101
351
  res.status(200).json(response);
102
352
  } catch (error) {
103
353
  logger.error('Error handling MCP request:', { stack: error.stack });
104
- const errorResponse = {
354
+ res.status(200).json({
105
355
  jsonrpc: '2.0',
106
356
  id: req.body?.id || null,
107
357
  error: {
108
358
  code: JSON_RPC_INTERNAL_ERROR,
109
359
  message: 'Internal server error',
110
- data: {
111
- error: error.message,
112
- stack: process.env.NODE_ENV !== 'production' ? error.stack : undefined
113
- }
114
- }
115
- };
116
- res.status(200).json(errorResponse);
360
+ data: { error: error.message },
361
+ },
362
+ });
117
363
  }
118
364
  }
119
365
 
120
-
121
366
  /**
122
- * Get all registered MCP tools
123
- * @returns {Array} Array of tool definitions
367
+ * Handle widget tool calls via direct HTTP (bypasses MCP protocol).
368
+ * The ChatGPT postMessage bridge does not forward tool arguments,
369
+ * so the widget uses fetch() to this endpoint instead.
124
370
  */
125
- function getTools() {
126
- return tools.tools.map(tool => tool.definition);
127
- }
371
+ async function handleWidgetToolCall(req, res) {
372
+ try {
373
+ logger.info('Widget tool call received. body:', JSON.stringify(req.body));
128
374
 
129
- /**
130
- * Execute a specific MCP tool
131
- * @param {string} toolName - Name of the tool to execute
132
- * @param {Object} args - Arguments to pass to the tool
133
- * @returns {Promise<Object>} Tool execution result
134
- */
135
- async function executeTool(toolName, args) {
136
- // Find the tool by name
137
- const tool = tools.tools.find(t => t.definition.name === toolName);
375
+ const { tool: toolName, toolArgs: args } = req.body || {};
138
376
 
139
- if (!tool) {
140
- throw new Error(`Tool not found: ${toolName}`);
141
- }
377
+ logger.info('Widget tool call parsed:', { toolName, args: JSON.stringify(args) });
142
378
 
143
- // Execute the tool
144
- return await tool.execute(args);
145
- }
379
+ if (!toolName) {
380
+ return res.status(400).json({ success: false, error: 'Missing tool name' });
381
+ }
146
382
 
147
- /**
148
- * Get a specific tool definition
149
- * @param {string} toolName - Name of the tool
150
- * @returns {Object} Tool definition
151
- */
152
- function getToolDefinition(toolName) {
153
- const tool = tools.tools.find(t => t.definition.name === toolName);
383
+ const allWidgetCallable = [...tools.tools, ...tools.widgetTools];
384
+ const tool = allWidgetCallable.find(t => t.definition.name === toolName);
385
+ if (!tool) {
386
+ return res.status(404).json({ success: false, error: `Unknown tool: ${toolName}` });
387
+ }
154
388
 
155
- if (!tool) {
156
- throw new Error(`Tool not found: ${toolName}`);
389
+ const result = await tool.execute(args || {});
390
+ logger.info('Widget tool call result:', { toolName, success: result?.success });
391
+ res.json(result);
392
+ } catch (error) {
393
+ logger.error('Widget tool call error:', { stack: error.stack });
394
+ res.status(500).json({
395
+ success: false,
396
+ error: error.message || 'Internal server error',
397
+ });
157
398
  }
158
-
159
- return tool.definition;
160
399
  }
161
400
 
162
401
  exports.handleMcpRequest = handleMcpRequest;
163
- exports.getTools = getTools;
164
- exports.executeTool = executeTool;
165
- exports.getToolDefinition = getToolDefinition;
166
- exports.tools = tools.tools;
402
+ exports.handleWidgetToolCall = handleWidgetToolCall;
@@ -1,4 +1,5 @@
1
1
  const { getAuthSession } = require('../../lib/authSession');
2
+ const { LlmSessionModel } = require('../../models/llmSessionModel');
2
3
 
3
4
  /**
4
5
  * MCP Tool: Check Auth Status
@@ -8,7 +9,7 @@ const { getAuthSession } = require('../../lib/authSession');
8
9
 
9
10
  const toolDefinition = {
10
11
  name: 'checkAuthStatus',
11
- description: 'Auth flow step.5. Check the status of an ongoing OAuth authentication session. Poll this after user clicks the auth link.',
12
+ description: 'Check the status of an ongoing OAuth authentication session. Poll this after user clicks the auth link.',
12
13
  inputSchema: {
13
14
  type: 'object',
14
15
  properties: {
@@ -16,10 +17,6 @@ const toolDefinition = {
16
17
  type: 'string',
17
18
  description: 'The session ID returned from doAuth tool'
18
19
  },
19
- platform: {
20
- type: 'string',
21
- description: 'The platform to check the status of'
22
- }
23
20
  },
24
21
  required: ['sessionId']
25
22
  },
@@ -34,39 +31,39 @@ const toolDefinition = {
34
31
  * Execute the checkAuthStatus tool
35
32
  * @param {Object} args - The tool arguments
36
33
  * @param {string} args.sessionId - The session ID to check
34
+ * @param {string} args.rcExtensionId - The RC extension ID
37
35
  * @returns {Object} Result object with authentication status
38
36
  */
39
37
  async function execute(args) {
40
38
  try {
41
- const { sessionId, platform } = args;
42
-
39
+ // rcExtensionId is injected by mcpHandler after verifying the RC access
40
+ // token. Using it as the DB key binds the CRM credential to a verified
41
+ // RC identity.
42
+ const { sessionId, rcExtensionId } = args;
43
+ if (!rcExtensionId) {
44
+ throw new Error('rcExtensionId is required');
45
+ }
43
46
  const session = await getAuthSession(sessionId);
44
-
47
+
45
48
  if (!session) {
46
49
  return {
47
50
  success: false,
48
- error: 'Session not found or expired',
49
- data: {
50
- status: 'expired'
51
- }
51
+ error: 'CRM auth session not found or expired. Ask the user to start the auth flow again.'
52
52
  };
53
53
  }
54
-
54
+
55
55
  switch (session.status) {
56
- case 'completed':
57
- if(platform === 'googleSheets') {
58
- return {
59
- success: true,
60
- data: {
61
- status: 'completed',
62
- jwtToken: session.jwtToken,
63
- userInfo: session.userInfo,
64
- message: 'IMPORTANT: Authentication successful! Keep jwtToken in memory for future use. DO NOT directly show it to user. Next step is to call getGoogleFilePicker tool.'
65
- }
66
- };
56
+ case 'completed': {
57
+ // Guard against duplicate DB writes if polled concurrently
58
+ try {
59
+ await LlmSessionModel.create({
60
+ id: rcExtensionId,
61
+ jwtToken: session.jwtToken
62
+ });
63
+ } catch {
64
+ // Record already exists from a prior poll safe to ignore
67
65
  }
68
66
  return {
69
- success: true,
70
67
  data: {
71
68
  status: 'completed',
72
69
  jwtToken: session.jwtToken,
@@ -74,24 +71,21 @@ async function execute(args) {
74
71
  message: 'IMPORTANT: Authentication successful! Keep jwtToken in memory for future use. DO NOT directly show it to user.'
75
72
  }
76
73
  };
77
-
74
+ }
75
+
78
76
  case 'failed':
79
77
  return {
80
- success: false,
81
- error: 'Authentication failed',
82
78
  data: {
83
79
  status: 'failed',
84
- errorMessage: session.errorMessage
80
+ errorMessage: session.errorMessage || 'Unknown error'
85
81
  }
86
82
  };
87
-
83
+
88
84
  case 'pending':
89
85
  default:
90
86
  return {
91
- success: true,
92
87
  data: {
93
- status: 'pending',
94
- message: 'Waiting for user to complete authorization. Poll again in a few seconds.'
88
+ status: 'pending'
95
89
  }
96
90
  };
97
91
  }
@@ -99,8 +93,7 @@ async function execute(args) {
99
93
  catch (error) {
100
94
  return {
101
95
  success: false,
102
- error: error.message || 'Unknown error occurred',
103
- errorDetails: error.stack
96
+ error: `CRM auth status check error: ${error.message}`
104
97
  };
105
98
  }
106
99
  }
@@ -12,21 +12,17 @@ const { CallLogModel } = require('../../models/callLogModel');
12
12
 
13
13
  const toolDefinition = {
14
14
  name: 'createCallLog',
15
- description: '⚠️ REQUIRES AUTHENTICATION: User must first authenticate using the "auth" tool to obtain a JWT token before using this tool. | Create only one call log in the CRM platform. Returns the created log ID if successful.',
15
+ description: '⚠️ REQUIRES CRM CONNECTION. | Create only one call log in the CRM platform. Returns the created log ID if successful. To use with `rcGetCallLogs`: pass a single item from the `records[]` array directly as `incomingData.logInfo`.',
16
16
  inputSchema: {
17
17
  type: 'object',
18
18
  properties: {
19
- jwtToken: {
20
- type: 'string',
21
- description: 'JWT token containing userId and platform information. If user does not have this, direct them to use the "auth" tool first.'
22
- },
23
19
  incomingData: {
24
20
  type: 'object',
25
21
  description: 'Call log data to create',
26
22
  properties: {
27
23
  logInfo: {
28
24
  type: 'object',
29
- description: 'RingCentral call log information (follows RingCentral Call Log schema)',
25
+ description: 'A single record from `rcGetCallLogs` pass the object exactly as returned, with no changes.',
30
26
  properties: {
31
27
  id: {
32
28
  type: 'string',
@@ -153,16 +149,24 @@ const toolDefinition = {
153
149
  description: 'RingCentral extension ID of the assigned user'
154
150
  }
155
151
  }
152
+ },
153
+ contactName: {
154
+ type: 'string',
155
+ description: 'Contact name'
156
+ },
157
+ contactType: {
158
+ type: 'string',
159
+ description: 'Contact type'
156
160
  }
157
161
  },
158
- required: ['logInfo']
162
+ required: ['logInfo', 'contactName']
159
163
  },
160
164
  contactId: {
161
165
  type: 'string',
162
166
  description: 'OPTIONAL: CRM contact ID to associate with the call.'
163
167
  }
164
168
  },
165
- required: ['jwtToken', 'incomingData']
169
+ required: ['incomingData']
166
170
  },
167
171
  annotations: {
168
172
  readOnlyHint: false,
@@ -250,7 +254,7 @@ async function execute(args) {
250
254
  userId,
251
255
  phoneNumber: contactNumber,
252
256
  overridingFormat: '',
253
- isExtension: 'false'
257
+ isExtension: false
254
258
  });
255
259
  const filteredContact = contactInfo.contact?.filter(c => !c.isNewContact);
256
260
  if (contactInfo.successful && filteredContact?.length > 0) {