@robosystems/mcp 0.3.7 → 0.3.9

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 (2) hide show
  1. package/index.js +129 -130
  2. package/package.json +1 -1
package/index.js CHANGED
@@ -452,93 +452,81 @@ class RoboSystemsMCPClient {
452
452
  }
453
453
 
454
454
  async handleSSEResponse(response, toolName) {
455
- return new Promise((resolve, reject) => {
456
- const events = []
457
- const operationId = response.headers.get('x-operation-id') || `sse-${Date.now()}`
458
-
459
- const eventSource = this.connectionPool.getConnection(operationId, response.url, this.headers)
455
+ // Read SSE events directly from the POST response body instead of opening
456
+ // a new EventSource. EventSource always uses GET, which 405s on this
457
+ // POST-only endpoint. The SSE stream is already in the response body.
458
+ const events = []
459
+ const reader = response.body.getReader()
460
+ const decoder = new TextDecoder()
461
+ let buffer = ''
460
462
 
461
- const timeout = setTimeout(() => {
462
- this.connectionPool.closeConnection(operationId)
463
- reject(new Error('SSE timeout after 5 minutes'))
464
- }, 300000)
463
+ let timeoutId
464
+ const timeout = new Promise((_, reject) => {
465
+ timeoutId = setTimeout(() => reject(new Error('SSE timeout after 5 minutes')), 300000)
466
+ })
465
467
 
466
- eventSource.onmessage = (event) => {
467
- try {
468
- const data = JSON.parse(event.data)
469
- events.push({ event: event.type || 'message', data })
470
- } catch (e) {
471
- console.error('Failed to parse SSE event:', e)
472
- }
473
- }
468
+ const readStream = async () => {
469
+ try {
470
+ while (true) {
471
+ const { done, value } = await reader.read()
472
+ if (done) break
473
+
474
+ buffer += decoder.decode(value, { stream: true })
475
+ const lines = buffer.split(/\r?\n/)
476
+ buffer = lines.pop() || ''
477
+
478
+ for (const line of lines) {
479
+ if (line.startsWith('data:')) {
480
+ const dataStr = line.slice(5).trim()
481
+ if (!dataStr || dataStr === '[DONE]') continue
482
+
483
+ let data
484
+ try {
485
+ data = JSON.parse(dataStr)
486
+ } catch (e) {
487
+ console.error('Failed to parse SSE event:', e)
488
+ continue
489
+ }
474
490
 
475
- eventSource.addEventListener('complete', () => {
476
- clearTimeout(timeout)
477
- const result = this.aggregateStreamedResults(events, toolName)
478
- resolve(result)
479
- })
491
+ const eventType = data.event || 'message'
480
492
 
481
- // Listen for the actual server event types
482
- eventSource.addEventListener('operation_completed', () => {
483
- clearTimeout(timeout)
484
- this.connectionPool.closeConnection(operationId)
485
- const result = this.aggregateStreamedResults(events, toolName)
486
- resolve(result)
487
- })
493
+ if (eventType === 'operation_error') {
494
+ throw new Error(data.data?.error || data.data?.message || 'Operation failed')
495
+ }
488
496
 
489
- eventSource.addEventListener('operation_error', (event) => {
490
- clearTimeout(timeout)
491
- this.connectionPool.closeConnection(operationId)
492
- try {
493
- const data = JSON.parse(event.data)
494
- reject(new Error(data.error || data.message || 'Operation failed'))
495
- } catch (_e) {
496
- reject(new Error('Operation failed'))
497
- }
498
- })
497
+ if (eventType === 'operation_progress' || eventType === 'progress') {
498
+ const progress = data.data?.percentage ? `${data.data.percentage}% - ` : ''
499
+ console.error(`Progress: ${progress}${data.data?.message || 'Processing...'}`)
500
+ continue
501
+ }
499
502
 
500
- eventSource.addEventListener('error', () => {
501
- clearTimeout(timeout)
502
- this.connectionPool.closeConnection(operationId)
503
+ events.push({ event: eventType, data: data.data ?? data })
503
504
 
504
- if (events.length > 0) {
505
- const result = this.aggregateStreamedResults(events, toolName)
506
- resolve(result)
507
- } else {
508
- reject(new Error('SSE connection failed'))
505
+ if (eventType === 'complete' || eventType === 'operation_completed') {
506
+ return
507
+ }
508
+ } else if (line.startsWith('event:')) {
509
+ // event: lines are handled via the data: payload's event field
510
+ }
511
+ }
509
512
  }
510
- })
513
+ } finally {
514
+ reader.cancel().catch(() => {})
515
+ }
516
+ }
511
517
 
512
- // Handle specific event types
513
- eventSource.addEventListener('query_chunk', (event) => {
514
- try {
515
- const data = JSON.parse(event.data)
516
- events.push({ event: 'query_chunk', data })
517
- } catch (e) {
518
- console.error('Failed to parse query chunk:', e)
519
- }
520
- })
518
+ try {
519
+ await Promise.race([readStream(), timeout])
520
+ } finally {
521
+ clearTimeout(timeoutId)
522
+ reader.cancel().catch(() => {})
523
+ }
521
524
 
522
- eventSource.addEventListener('progress', (event) => {
523
- try {
524
- const data = JSON.parse(event.data)
525
- console.error(`Progress: ${data.message || 'Processing...'}`)
526
- } catch (_e) {
527
- // Ignore progress parsing errors
528
- }
529
- })
525
+ if (events.length === 0) {
526
+ throw new Error('SSE connection failed')
527
+ }
530
528
 
531
- // Also listen for operation_progress events
532
- eventSource.addEventListener('operation_progress', (event) => {
533
- try {
534
- const data = JSON.parse(event.data)
535
- const progress = data.percentage ? `${data.percentage}% - ` : ''
536
- console.error(`Progress: ${progress}${data.message || 'Processing...'}`)
537
- } catch (_e) {
538
- // Ignore progress parsing errors
539
- }
540
- })
541
- })
529
+ return this.aggregateStreamedResults(events, toolName)
542
530
  }
543
531
 
544
532
  async handleNDJSONResponse(response) {
@@ -766,7 +754,7 @@ class RoboSystemsMCPClient {
766
754
  `${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
767
755
  {
768
756
  method: 'POST',
769
- headers: this.headers,
757
+ headers: { ...this.headers, Accept: 'application/json' },
770
758
  body: JSON.stringify({
771
759
  name: 'create-workspace',
772
760
  arguments: { name, description, fork_parent, subgraph_type },
@@ -861,7 +849,12 @@ class RoboSystemsMCPClient {
861
849
  // Handle "primary" alias
862
850
  const targetGraphId = workspace_id === 'primary' ? this.primaryGraphId : workspace_id
863
851
 
864
- // Validate workspace exists
852
+ // Validate workspace exists — if not found locally, refresh from server first
853
+ if (!this.workspaces.has(targetGraphId)) {
854
+ console.error(`Workspace "${targetGraphId}" not in local cache, refreshing from server...`)
855
+ await this._refreshWorkspacesCache()
856
+ }
857
+
865
858
  if (!this.workspaces.has(targetGraphId)) {
866
859
  return {
867
860
  type: 'text',
@@ -869,7 +862,7 @@ class RoboSystemsMCPClient {
869
862
  {
870
863
  error: 'Unknown workspace',
871
864
  workspace_id: targetGraphId,
872
- message: `Workspace "${targetGraphId}" not found. Use list-workspaces to see available workspaces.`,
865
+ message: `Workspace "${targetGraphId}" not found.`,
873
866
  available_workspaces: Array.from(this.workspaces.keys()),
874
867
  },
875
868
  null,
@@ -929,7 +922,7 @@ class RoboSystemsMCPClient {
929
922
  `${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
930
923
  {
931
924
  method: 'POST',
932
- headers: this.headers,
925
+ headers: { ...this.headers, Accept: 'application/json' },
933
926
  body: JSON.stringify({
934
927
  name: 'delete-workspace',
935
928
  arguments: { workspace_id, force },
@@ -1015,20 +1008,14 @@ class RoboSystemsMCPClient {
1015
1008
  }
1016
1009
  }
1017
1010
 
1018
- async _handleListWorkspaces() {
1011
+ async _refreshWorkspacesCache() {
1019
1012
  try {
1020
- console.error('Listing workspaces via MCP tool')
1021
-
1022
- // Call the MCP tool endpoint (server provides the list)
1023
1013
  const response = await fetch(
1024
1014
  `${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
1025
1015
  {
1026
1016
  method: 'POST',
1027
- headers: this.headers,
1028
- body: JSON.stringify({
1029
- name: 'list-workspaces',
1030
- arguments: {},
1031
- }),
1017
+ headers: { ...this.headers, Accept: 'application/json' },
1018
+ body: JSON.stringify({ name: 'list-workspaces', arguments: {} }),
1032
1019
  }
1033
1020
  )
1034
1021
 
@@ -1039,7 +1026,6 @@ class RoboSystemsMCPClient {
1039
1026
 
1040
1027
  const data = await response.json()
1041
1028
 
1042
- // Parse the result
1043
1029
  let result
1044
1030
  if (data.result && data.result.type === 'text' && data.result.text) {
1045
1031
  try {
@@ -1051,18 +1037,7 @@ class RoboSystemsMCPClient {
1051
1037
  result = data.result || data
1052
1038
  }
1053
1039
 
1054
- // Check for errors from server
1055
- if (result.error) {
1056
- console.error(`Server error listing workspaces: ${result.message}`)
1057
- return {
1058
- type: 'text',
1059
- text: JSON.stringify(result, null, 2),
1060
- }
1061
- }
1062
-
1063
- // Update client tracking with server's workspace list
1064
1040
  if (result.workspaces) {
1065
- // Clear and rebuild workspace tracking from server data
1066
1041
  this.workspaces.clear()
1067
1042
  for (const ws of result.workspaces) {
1068
1043
  this.workspaces.set(ws.workspace_id, {
@@ -1073,39 +1048,20 @@ class RoboSystemsMCPClient {
1073
1048
  created_at: ws.created_at ? new Date(ws.created_at).getTime() : Date.now(),
1074
1049
  })
1075
1050
  }
1076
-
1077
- // Validate that the current activeGraphId still exists
1078
- if (!this.workspaces.has(this.activeGraphId)) {
1079
- console.error(
1080
- `Active workspace ${this.activeGraphId} no longer exists on server, switching to primary`
1081
- )
1082
- this.activeGraphId = this.primaryGraphId
1083
- this.metrics.workspaceSwitches++
1084
- }
1085
1051
  }
1086
1052
 
1087
- // Mark active workspace in response
1088
- const workspaces = result.workspaces.map((ws) => ({
1089
- ...ws,
1090
- active: ws.workspace_id === this.activeGraphId,
1091
- }))
1092
-
1093
- return {
1094
- type: 'text',
1095
- text: JSON.stringify(
1096
- {
1097
- primary_graph_id: result.primary_graph_id,
1098
- active_workspace: this.activeGraphId,
1099
- total_workspaces: workspaces.length,
1100
- workspaces,
1101
- },
1102
- null,
1103
- 2
1104
- ),
1105
- }
1053
+ return result
1106
1054
  } catch (error) {
1107
- console.error(`Failed to list workspaces: ${error.message}`)
1055
+ console.error(`Failed to refresh workspaces cache: ${error.message}`)
1056
+ return null
1057
+ }
1058
+ }
1059
+
1060
+ async _handleListWorkspaces() {
1061
+ console.error('Listing workspaces via MCP tool')
1062
+ const result = await this._refreshWorkspacesCache()
1108
1063
 
1064
+ if (!result) {
1109
1065
  // Fallback to client-side tracking
1110
1066
  const workspaces = Array.from(this.workspaces.entries()).map(([id, meta]) => ({
1111
1067
  workspace_id: id,
@@ -1132,6 +1088,49 @@ class RoboSystemsMCPClient {
1132
1088
  ),
1133
1089
  }
1134
1090
  }
1091
+
1092
+ if (result.error) {
1093
+ console.error(`Server error listing workspaces: ${result.message}`)
1094
+ return {
1095
+ type: 'text',
1096
+ text: JSON.stringify(result, null, 2),
1097
+ }
1098
+ }
1099
+
1100
+ if (!result.workspaces) {
1101
+ return {
1102
+ type: 'text',
1103
+ text: JSON.stringify(result, null, 2),
1104
+ }
1105
+ }
1106
+
1107
+ // Validate that the current activeGraphId still exists
1108
+ if (!this.workspaces.has(this.activeGraphId)) {
1109
+ console.error(
1110
+ `Active workspace ${this.activeGraphId} no longer exists on server, switching to primary`
1111
+ )
1112
+ this.activeGraphId = this.primaryGraphId
1113
+ this.metrics.workspaceSwitches++
1114
+ }
1115
+
1116
+ const workspaces = result.workspaces.map((ws) => ({
1117
+ ...ws,
1118
+ active: ws.workspace_id === this.activeGraphId,
1119
+ }))
1120
+
1121
+ return {
1122
+ type: 'text',
1123
+ text: JSON.stringify(
1124
+ {
1125
+ primary_graph_id: result.primary_graph_id,
1126
+ active_workspace: this.activeGraphId,
1127
+ total_workspaces: workspaces.length,
1128
+ workspaces,
1129
+ },
1130
+ null,
1131
+ 2
1132
+ ),
1133
+ }
1135
1134
  }
1136
1135
 
1137
1136
  cleanup() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@robosystems/mcp",
3
- "version": "0.3.7",
3
+ "version": "0.3.9",
4
4
  "description": "MCP client adapter for connecting AI agents to RoboSystems Financial Knowledge Graph API endpoints with workspace support",
5
5
  "type": "module",
6
6
  "main": "index.js",