@robosystems/mcp 0.2.10 → 0.3.1

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 (3) hide show
  1. package/README.md +2 -1
  2. package/index.js +493 -32
  3. package/package.json +8 -2
package/README.md CHANGED
@@ -7,6 +7,7 @@ Official MCP (Model Context Protocol) client adapter for connecting AI agents to
7
7
 
8
8
  ## Features
9
9
 
10
+ - **Workspace Management** - Create isolated environments for experimentation
10
11
  - **MCP-compliant server** for Claude Desktop and other AI agents
11
12
  - **Streaming support** for memory-efficient processing of large result sets
12
13
  - **Connection pooling** for optimal SSE performance
@@ -40,7 +41,7 @@ Add to your MCP servers configuration:
40
41
  |----------|-------------|---------|
41
42
  | `ROBOSYSTEMS_API_URL` | The RoboSystems API endpoint | `https://api.robosystems.ai` |
42
43
  | `ROBOSYSTEMS_API_KEY` | Your API key | `rfs...` |
43
- | `ROBOSYSTEMS_GRAPH_ID` | The graph database ID to connect to | `kg...` or `sec` |
44
+ | `ROBOSYSTEMS_GRAPH_ID` | The primary graph database ID (parent for workspaces) | `kg...` or `sec` |
44
45
 
45
46
  ## API Reference
46
47
 
package/index.js CHANGED
@@ -59,17 +59,19 @@ class SSEConnectionPool {
59
59
 
60
60
  // Create new connection
61
61
  const eventSource = new EventSource(url, { headers })
62
+
63
+ // Auto-cleanup after TTL - store timer ID to prevent memory leaks
64
+ const cleanupTimer = setTimeout(() => {
65
+ this.closeConnection(operationId)
66
+ }, this.connectionTTL)
67
+
62
68
  this.connections.set(operationId, {
63
69
  eventSource,
64
70
  createdAt: Date.now(),
65
71
  lastUsed: Date.now(),
72
+ cleanupTimer,
66
73
  })
67
74
 
68
- // Auto-cleanup after TTL
69
- setTimeout(() => {
70
- this.closeConnection(operationId)
71
- }, this.connectionTTL)
72
-
73
75
  return eventSource
74
76
  }
75
77
 
@@ -92,6 +94,10 @@ class SSEConnectionPool {
92
94
  closeConnection(operationId) {
93
95
  const conn = this.connections.get(operationId)
94
96
  if (conn) {
97
+ // Clear the cleanup timer to prevent memory leaks
98
+ if (conn.cleanupTimer) {
99
+ clearTimeout(conn.cleanupTimer)
100
+ }
95
101
  conn.eventSource.close()
96
102
  this.connections.delete(operationId)
97
103
  }
@@ -114,10 +120,11 @@ class ResultCache {
114
120
  this.cacheExpiry = new Map()
115
121
  }
116
122
 
117
- generateKey(tool, args) {
123
+ generateKey(tool, args, workspaceId = null) {
118
124
  // Sort object keys to ensure deterministic cache keys
125
+ // Include workspaceId to prevent cache collisions across workspaces
119
126
  const sortedArgs = this._sortObjectKeys(args)
120
- const data = JSON.stringify({ tool, args: sortedArgs }, null, 0)
127
+ const data = JSON.stringify({ tool, args: sortedArgs, workspace: workspaceId }, null, 0)
121
128
  return createHash('sha256').update(data).digest('hex')
122
129
  }
123
130
 
@@ -135,9 +142,9 @@ class ResultCache {
135
142
  return sortedObj
136
143
  }
137
144
 
138
- get(tool, args) {
139
- const key = this.generateKey(tool, args)
140
-
145
+ get(tool, args, workspaceId = null) {
146
+ const key = this.generateKey(tool, args, workspaceId)
147
+
141
148
  if (this.cache.has(key)) {
142
149
  const expiry = this.cacheExpiry.get(key)
143
150
  if (expiry > Date.now()) {
@@ -148,12 +155,12 @@ class ResultCache {
148
155
  this.cacheExpiry.delete(key)
149
156
  }
150
157
  }
151
-
158
+
152
159
  return null
153
160
  }
154
161
 
155
- set(tool, args, result, ttlSeconds = 300) {
156
- const key = this.generateKey(tool, args)
162
+ set(tool, args, result, ttlSeconds = 300, workspaceId = null) {
163
+ const key = this.generateKey(tool, args, workspaceId)
157
164
  this.cache.set(key, result)
158
165
  this.cacheExpiry.set(key, Date.now() + (ttlSeconds * 1000))
159
166
  }
@@ -172,33 +179,45 @@ class RoboSystemsMCPClient {
172
179
  constructor(baseUrl, apiKey, graphId) {
173
180
  this.baseUrl = baseUrl.replace(/\/$/, '') // Remove trailing slash
174
181
  this.apiKey = apiKey
175
- this.graphId = graphId
182
+ this.primaryGraphId = graphId // Parent graph (never changes)
183
+ this.activeGraphId = graphId // Currently active graph (can switch to workspaces)
184
+ this.graphId = graphId // Deprecated: kept for backward compatibility
176
185
  this.headers = {
177
186
  'X-API-Key': apiKey,
178
187
  'Content-Type': 'application/json',
179
188
  'User-Agent': `robosystems-mcp/${PACKAGE_VERSION}`,
180
189
  'X-MCP-Client': PACKAGE_VERSION,
181
190
  }
182
-
191
+
183
192
  // Initialize components
184
193
  this.connectionPool = new SSEConnectionPool()
185
194
  this.resultCache = new ResultCache()
186
195
  this.maxRetries = 3
187
196
  this.baseRetryDelay = 1000
188
-
197
+
198
+ // Workspace tracking
199
+ this.workspaces = new Map()
200
+ this.workspaces.set(graphId, {
201
+ type: 'primary',
202
+ name: 'main',
203
+ created_at: Date.now(),
204
+ parent_graph_id: null
205
+ })
206
+
189
207
  // Simple metrics
190
208
  this.metrics = {
191
209
  totalRequests: 0,
192
210
  cacheHits: 0,
193
211
  errors: 0,
212
+ workspaceSwitches: 0,
194
213
  }
195
214
  }
196
215
 
197
216
  async getTools() {
198
217
  try {
199
- console.error(`Fetching tools from ${this.baseUrl}/v1/graphs/${this.graphId}/mcp/tools`)
218
+ console.error(`Fetching tools from ${this.baseUrl}/v1/graphs/${this.activeGraphId}/mcp/tools`)
200
219
  const response = await fetch(
201
- `${this.baseUrl}/v1/graphs/${this.graphId}/mcp/tools`,
220
+ `${this.baseUrl}/v1/graphs/${this.activeGraphId}/mcp/tools`,
202
221
  {
203
222
  headers: this.headers,
204
223
  }
@@ -211,8 +230,20 @@ class RoboSystemsMCPClient {
211
230
  }
212
231
 
213
232
  const data = await response.json()
214
- console.error(`Got ${data.tools?.length || 0} tools from API`)
215
- return data.tools || []
233
+ let tools = data.tools || []
234
+ console.error(`Got ${tools.length} tools from API`)
235
+
236
+ // Add client-side workspace tools (if not already provided by server)
237
+ const workspaceToolNames = ['create-workspace', 'switch-workspace', 'delete-workspace', 'list-workspaces']
238
+ const hasWorkspaceTools = tools.some(t => workspaceToolNames.includes(t.name))
239
+
240
+ if (!hasWorkspaceTools) {
241
+ const workspaceTools = this._getWorkspaceToolDefinitions()
242
+ tools = [...tools, ...workspaceTools]
243
+ console.error(`Added ${workspaceTools.length} client-side workspace tools`)
244
+ }
245
+
246
+ return tools
216
247
  } catch (error) {
217
248
  console.error(`Failed to get tools: ${error.message}`)
218
249
  console.error(`Stack: ${error.stack}`)
@@ -220,18 +251,101 @@ class RoboSystemsMCPClient {
220
251
  }
221
252
  }
222
253
 
254
+ _getWorkspaceToolDefinitions() {
255
+ return [
256
+ {
257
+ name: 'create-workspace',
258
+ description: 'Create an isolated workspace (subgraph) for experimentation. Data and queries are isolated from the main graph.',
259
+ inputSchema: {
260
+ type: 'object',
261
+ properties: {
262
+ name: {
263
+ type: 'string',
264
+ description: 'Workspace name (alphanumeric only, 1-20 characters)'
265
+ },
266
+ description: {
267
+ type: 'string',
268
+ description: 'Optional workspace description'
269
+ },
270
+ fork_parent: {
271
+ type: 'boolean',
272
+ description: 'Copy data from parent graph to workspace',
273
+ default: false
274
+ }
275
+ },
276
+ required: ['name']
277
+ }
278
+ },
279
+ {
280
+ name: 'switch-workspace',
281
+ description: 'Switch to a different workspace or back to the primary graph. All subsequent operations will use the active workspace.',
282
+ inputSchema: {
283
+ type: 'object',
284
+ properties: {
285
+ workspace_id: {
286
+ type: 'string',
287
+ description: 'Workspace ID to switch to, or "primary" for main graph'
288
+ }
289
+ },
290
+ required: ['workspace_id']
291
+ }
292
+ },
293
+ {
294
+ name: 'delete-workspace',
295
+ description: 'Delete a workspace and all its data. Cannot delete the primary graph. Switches back to primary if deleting active workspace.',
296
+ inputSchema: {
297
+ type: 'object',
298
+ properties: {
299
+ workspace_id: {
300
+ type: 'string',
301
+ description: 'Workspace ID to delete'
302
+ },
303
+ force: {
304
+ type: 'boolean',
305
+ description: 'Force deletion even if workspace contains data',
306
+ default: false
307
+ }
308
+ },
309
+ required: ['workspace_id']
310
+ }
311
+ },
312
+ {
313
+ name: 'list-workspaces',
314
+ description: 'List all workspaces and show which one is currently active',
315
+ inputSchema: {
316
+ type: 'object',
317
+ properties: {}
318
+ }
319
+ }
320
+ ]
321
+ }
322
+
223
323
  async callTool(name, args = {}) {
224
324
  this.metrics.totalRequests++
225
-
325
+
326
+ // Intercept workspace management tools (client-side implementation)
327
+ if (name === 'create-workspace') {
328
+ return this._handleCreateWorkspace(args)
329
+ }
330
+ if (name === 'switch-workspace') {
331
+ return this._handleSwitchWorkspace(args)
332
+ }
333
+ if (name === 'delete-workspace') {
334
+ return this._handleDeleteWorkspace(args)
335
+ }
336
+ if (name === 'list-workspaces') {
337
+ return this._handleListWorkspaces()
338
+ }
339
+
226
340
  // Check cache first for cacheable tools
227
341
  if (this.isCacheable(name)) {
228
- const cached = this.resultCache.get(name, args)
342
+ const cached = this.resultCache.get(name, args, this.activeGraphId)
229
343
  if (cached) {
230
344
  this.metrics.cacheHits++
231
345
  return cached
232
346
  }
233
347
  }
234
-
348
+
235
349
  // Execute with simple retry logic
236
350
  return this.executeWithRetry(() => this._callToolInternal(name, args))
237
351
  }
@@ -244,7 +358,7 @@ class RoboSystemsMCPClient {
244
358
  }
245
359
 
246
360
  const response = await fetch(
247
- `${this.baseUrl}/v1/graphs/${this.graphId}/mcp/call-tool`,
361
+ `${this.baseUrl}/v1/graphs/${this.activeGraphId}/mcp/call-tool`,
248
362
  {
249
363
  method: 'POST',
250
364
  headers,
@@ -284,7 +398,7 @@ class RoboSystemsMCPClient {
284
398
  // Cache the result if appropriate
285
399
  if (this.isCacheable(name)) {
286
400
  const ttl = this.getCacheTTL(name)
287
- this.resultCache.set(name, args, result, ttl)
401
+ this.resultCache.set(name, args, result, ttl, this.activeGraphId)
288
402
  }
289
403
 
290
404
  return result
@@ -468,9 +582,9 @@ class RoboSystemsMCPClient {
468
582
  console.error(`Query queued with ID: ${data.queue_id}`)
469
583
 
470
584
  const statusUrl = data.status_url ||
471
- `${this.baseUrl}/v1/graphs/${this.graphId}/query/${data.queue_id}/status`
585
+ `${this.baseUrl}/v1/graphs/${this.activeGraphId}/query/${data.queue_id}/status`
472
586
  const resultUrl = data.result_url ||
473
- `${this.baseUrl}/v1/graphs/${this.graphId}/query/${data.queue_id}/result`
587
+ `${this.baseUrl}/v1/graphs/${this.activeGraphId}/query/${data.queue_id}/result`
474
588
 
475
589
  // Simple polling with exponential backoff
476
590
  let attempts = 0
@@ -604,7 +718,7 @@ class RoboSystemsMCPClient {
604
718
  }
605
719
 
606
720
  getMetrics() {
607
- const cacheHitRate = this.metrics.totalRequests > 0
721
+ const cacheHitRate = this.metrics.totalRequests > 0
608
722
  ? (this.metrics.cacheHits / this.metrics.totalRequests * 100).toFixed(1) + '%'
609
723
  : '0%'
610
724
 
@@ -614,6 +728,348 @@ class RoboSystemsMCPClient {
614
728
  cacheHitRate,
615
729
  errors: this.metrics.errors,
616
730
  activeConnections: this.connectionPool.connections.size,
731
+ workspaceSwitches: this.metrics.workspaceSwitches,
732
+ activeWorkspace: this.activeGraphId,
733
+ totalWorkspaces: this.workspaces.size,
734
+ }
735
+ }
736
+
737
+ // Workspace management methods
738
+
739
+ async _handleCreateWorkspace(args) {
740
+ const { name, description, fork_parent = false } = args
741
+
742
+ try {
743
+ console.error(`Creating workspace via MCP tool: ${name} (fork_parent: ${fork_parent})`)
744
+
745
+ // Call the MCP tool endpoint (server handles the creation)
746
+ const response = await fetch(
747
+ `${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
748
+ {
749
+ method: 'POST',
750
+ headers: this.headers,
751
+ body: JSON.stringify({
752
+ name: 'create-workspace',
753
+ arguments: { name, description, fork_parent }
754
+ })
755
+ }
756
+ )
757
+
758
+ if (!response.ok) {
759
+ const errorText = await response.text()
760
+ throw new Error(`HTTP ${response.status}: ${errorText}`)
761
+ }
762
+
763
+ const data = await response.json()
764
+
765
+ // Parse the result (server returns JSON in result.text)
766
+ let result
767
+ if (data.result && data.result.type === 'text' && data.result.text) {
768
+ try {
769
+ result = JSON.parse(data.result.text)
770
+ } catch (e) {
771
+ result = { message: data.result.text }
772
+ }
773
+ } else {
774
+ result = data.result || data
775
+ }
776
+
777
+ // Check for errors from server
778
+ if (result.error) {
779
+ console.error(`Server error creating workspace: ${result.message}`)
780
+ return {
781
+ type: 'text',
782
+ text: JSON.stringify(result, null, 2)
783
+ }
784
+ }
785
+
786
+ // Server created the workspace successfully
787
+ const workspaceId = result.workspace_id
788
+
789
+ // Track the workspace
790
+ this.workspaces.set(workspaceId, {
791
+ type: 'workspace',
792
+ parent_graph_id: this.primaryGraphId,
793
+ name,
794
+ description: result.description || description,
795
+ created_at: Date.now(),
796
+ forked_from_parent: fork_parent
797
+ })
798
+
799
+ // Automatically switch to the new workspace
800
+ const previousGraph = this.activeGraphId
801
+ this.activeGraphId = workspaceId
802
+ this.metrics.workspaceSwitches++
803
+
804
+ console.error(`Created and switched to workspace: ${workspaceId}`)
805
+
806
+ return {
807
+ type: 'text',
808
+ text: JSON.stringify({
809
+ success: true,
810
+ workspace_id: workspaceId,
811
+ name,
812
+ previous_workspace: previousGraph,
813
+ active: true,
814
+ forked_from_parent: fork_parent,
815
+ message: `Created workspace "${name}" and switched to it. All operations now use this isolated environment.`
816
+ }, null, 2)
817
+ }
818
+ } catch (error) {
819
+ console.error(`Failed to create workspace: ${error.message}`)
820
+ return {
821
+ type: 'text',
822
+ text: JSON.stringify({
823
+ error: 'Failed to create workspace',
824
+ message: error.message,
825
+ workspace_name: name
826
+ }, null, 2)
827
+ }
828
+ }
829
+ }
830
+
831
+ async _handleSwitchWorkspace(args) {
832
+ const { workspace_id } = args
833
+
834
+ // Handle "primary" alias
835
+ const targetGraphId = workspace_id === 'primary' ? this.primaryGraphId : workspace_id
836
+
837
+ // Validate workspace exists
838
+ if (!this.workspaces.has(targetGraphId)) {
839
+ return {
840
+ type: 'text',
841
+ text: JSON.stringify({
842
+ error: 'Unknown workspace',
843
+ workspace_id: targetGraphId,
844
+ message: `Workspace "${targetGraphId}" not found. Use list-workspaces to see available workspaces.`,
845
+ available_workspaces: Array.from(this.workspaces.keys())
846
+ }, null, 2)
847
+ }
848
+ }
849
+
850
+ // Already in this workspace?
851
+ if (this.activeGraphId === targetGraphId) {
852
+ return {
853
+ type: 'text',
854
+ text: JSON.stringify({
855
+ success: true,
856
+ workspace_id: targetGraphId,
857
+ message: `Already in workspace "${targetGraphId}"`
858
+ }, null, 2)
859
+ }
860
+ }
861
+
862
+ // Switch workspace
863
+ const previousGraph = this.activeGraphId
864
+ this.activeGraphId = targetGraphId
865
+ this.metrics.workspaceSwitches++
866
+
867
+ const workspace = this.workspaces.get(targetGraphId)
868
+ console.error(`Switched from ${previousGraph} to ${targetGraphId}`)
869
+
870
+ return {
871
+ type: 'text',
872
+ text: JSON.stringify({
873
+ success: true,
874
+ switched_from: previousGraph,
875
+ switched_to: targetGraphId,
876
+ workspace_type: workspace.type,
877
+ message: `Switched to ${workspace.type === 'primary' ? 'primary graph' : `workspace "${workspace.name}"`}. All operations now use this environment.`
878
+ }, null, 2)
879
+ }
880
+ }
881
+
882
+ async _handleDeleteWorkspace(args) {
883
+ const { workspace_id, force = false } = args
884
+
885
+ try {
886
+ console.error(`Deleting workspace via MCP tool: ${workspace_id} (force: ${force})`)
887
+
888
+ // Call the MCP tool endpoint (server handles the deletion)
889
+ const response = await fetch(
890
+ `${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
891
+ {
892
+ method: 'POST',
893
+ headers: this.headers,
894
+ body: JSON.stringify({
895
+ name: 'delete-workspace',
896
+ arguments: { workspace_id, force }
897
+ })
898
+ }
899
+ )
900
+
901
+ if (!response.ok) {
902
+ const errorText = await response.text()
903
+ throw new Error(`HTTP ${response.status}: ${errorText}`)
904
+ }
905
+
906
+ const data = await response.json()
907
+
908
+ // Parse the result
909
+ let result
910
+ if (data.result && data.result.type === 'text' && data.result.text) {
911
+ try {
912
+ result = JSON.parse(data.result.text)
913
+ } catch (e) {
914
+ result = { message: data.result.text }
915
+ }
916
+ } else {
917
+ result = data.result || data
918
+ }
919
+
920
+ // Check for errors from server
921
+ if (result.error) {
922
+ console.error(`Server error deleting workspace: ${result.message}`)
923
+ return {
924
+ type: 'text',
925
+ text: JSON.stringify(result, null, 2)
926
+ }
927
+ }
928
+
929
+ // Server deleted the workspace successfully
930
+ const workspace = this.workspaces.get(workspace_id)
931
+ if (workspace) {
932
+ this.workspaces.delete(workspace_id)
933
+ }
934
+
935
+ // Switch back to primary if we deleted the active workspace
936
+ const switchedBack = this.activeGraphId === workspace_id
937
+ if (switchedBack) {
938
+ this.activeGraphId = this.primaryGraphId
939
+ this.metrics.workspaceSwitches++
940
+ }
941
+
942
+ console.error(`Deleted workspace: ${workspace_id}${switchedBack ? ' (switched back to primary)' : ''}`)
943
+
944
+ return {
945
+ type: 'text',
946
+ text: JSON.stringify({
947
+ success: true,
948
+ deleted: workspace_id,
949
+ active_workspace: this.activeGraphId,
950
+ switched_back_to_primary: switchedBack,
951
+ message: result.message || `Deleted workspace "${workspace_id}"${switchedBack ? ' and switched back to primary graph' : ''}.`
952
+ }, null, 2)
953
+ }
954
+ } catch (error) {
955
+ console.error(`Failed to delete workspace: ${error.message}`)
956
+ return {
957
+ type: 'text',
958
+ text: JSON.stringify({
959
+ error: 'Failed to delete workspace',
960
+ message: error.message,
961
+ workspace_id
962
+ }, null, 2)
963
+ }
964
+ }
965
+ }
966
+
967
+ async _handleListWorkspaces() {
968
+ try {
969
+ console.error('Listing workspaces via MCP tool')
970
+
971
+ // Call the MCP tool endpoint (server provides the list)
972
+ const response = await fetch(
973
+ `${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
974
+ {
975
+ method: 'POST',
976
+ headers: this.headers,
977
+ body: JSON.stringify({
978
+ name: 'list-workspaces',
979
+ arguments: {}
980
+ })
981
+ }
982
+ )
983
+
984
+ if (!response.ok) {
985
+ const errorText = await response.text()
986
+ throw new Error(`HTTP ${response.status}: ${errorText}`)
987
+ }
988
+
989
+ const data = await response.json()
990
+
991
+ // Parse the result
992
+ let result
993
+ if (data.result && data.result.type === 'text' && data.result.text) {
994
+ try {
995
+ result = JSON.parse(data.result.text)
996
+ } catch (e) {
997
+ result = { message: data.result.text }
998
+ }
999
+ } else {
1000
+ result = data.result || data
1001
+ }
1002
+
1003
+ // Check for errors from server
1004
+ if (result.error) {
1005
+ console.error(`Server error listing workspaces: ${result.message}`)
1006
+ return {
1007
+ type: 'text',
1008
+ text: JSON.stringify(result, null, 2)
1009
+ }
1010
+ }
1011
+
1012
+ // Update client tracking with server's workspace list
1013
+ if (result.workspaces) {
1014
+ // Clear and rebuild workspace tracking from server data
1015
+ this.workspaces.clear()
1016
+ for (const ws of result.workspaces) {
1017
+ this.workspaces.set(ws.workspace_id, {
1018
+ type: ws.type,
1019
+ name: ws.name,
1020
+ description: ws.description,
1021
+ parent_graph_id: ws.parent_graph_id,
1022
+ created_at: ws.created_at ? new Date(ws.created_at).getTime() : Date.now()
1023
+ })
1024
+ }
1025
+
1026
+ // Validate that the current activeGraphId still exists
1027
+ if (!this.workspaces.has(this.activeGraphId)) {
1028
+ console.error(`Active workspace ${this.activeGraphId} no longer exists on server, switching to primary`)
1029
+ this.activeGraphId = this.primaryGraphId
1030
+ this.metrics.workspaceSwitches++
1031
+ }
1032
+ }
1033
+
1034
+ // Mark active workspace in response
1035
+ const workspaces = result.workspaces.map(ws => ({
1036
+ ...ws,
1037
+ active: ws.workspace_id === this.activeGraphId
1038
+ }))
1039
+
1040
+ return {
1041
+ type: 'text',
1042
+ text: JSON.stringify({
1043
+ primary_graph_id: result.primary_graph_id,
1044
+ active_workspace: this.activeGraphId,
1045
+ total_workspaces: workspaces.length,
1046
+ workspaces
1047
+ }, null, 2)
1048
+ }
1049
+ } catch (error) {
1050
+ console.error(`Failed to list workspaces: ${error.message}`)
1051
+
1052
+ // Fallback to client-side tracking
1053
+ const workspaces = Array.from(this.workspaces.entries()).map(([id, meta]) => ({
1054
+ workspace_id: id,
1055
+ type: meta.type,
1056
+ name: meta.name,
1057
+ description: meta.description,
1058
+ active: id === this.activeGraphId,
1059
+ created_at: new Date(meta.created_at).toISOString(),
1060
+ parent_graph_id: meta.parent_graph_id
1061
+ }))
1062
+
1063
+ return {
1064
+ type: 'text',
1065
+ text: JSON.stringify({
1066
+ primary_graph_id: this.primaryGraphId,
1067
+ active_workspace: this.activeGraphId,
1068
+ total_workspaces: workspaces.length,
1069
+ workspaces,
1070
+ _note: 'Fallback to client-side tracking due to error'
1071
+ }, null, 2)
1072
+ }
617
1073
  }
618
1074
  }
619
1075
 
@@ -641,7 +1097,8 @@ async function main() {
641
1097
  }
642
1098
 
643
1099
  console.error(`RoboSystems MCP Client v${PACKAGE_VERSION}`)
644
- console.error(`Connecting to ${baseUrl} for graph ${graphId}`)
1100
+ console.error(`Connecting to ${baseUrl}`)
1101
+ console.error(`Primary graph: ${graphId}`)
645
1102
  console.error(`API Key: ${apiKey.substring(0, 10)}...`)
646
1103
 
647
1104
  const remoteClient = new RoboSystemsMCPClient(baseUrl, apiKey, graphId)
@@ -711,7 +1168,8 @@ async function main() {
711
1168
  await server.connect(transport)
712
1169
 
713
1170
  console.error('RoboSystems MCP server running')
714
- console.error('Features: Connection pooling, smart caching, retry logic, progress tracking')
1171
+ console.error('Features: Workspace management, connection pooling, smart caching, retry logic, progress tracking')
1172
+ console.error(`Active workspace: ${remoteClient.activeGraphId}`)
715
1173
 
716
1174
  // Log metrics every 5 minutes
717
1175
  metricsInterval = setInterval(() => {
@@ -750,13 +1208,16 @@ export {
750
1208
  // Only run as server if this is the main module
751
1209
  // Check if we're being run directly (not imported)
752
1210
  // This works with both `node index.js` and `npx` invocations
753
- const isMainModule =
1211
+ const isMainModule =
754
1212
  import.meta.url === `file://${process.argv[1]}` ||
755
1213
  process.argv[1]?.endsWith('/mcp') || // npx binary name
756
1214
  process.argv[1]?.endsWith('/@robosystems/mcp') || // alternative npx name
757
1215
  process.argv[1]?.includes('robosystems-mcp'); // package name in path
758
1216
 
759
- if (isMainModule) {
1217
+ // Don't run in test mode
1218
+ const isTestMode = process.env.VITEST === 'true' || process.env.NODE_ENV === 'test'
1219
+
1220
+ if (isMainModule && !isTestMode) {
760
1221
  // Run the server
761
1222
  main().catch((error) => {
762
1223
  console.error(`Fatal error: ${error.message}`)
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@robosystems/mcp",
3
- "version": "0.2.10",
4
- "description": "MCP client adapter for connecting AI agents to RoboSystems Financial Knowledge Graph API endpoints",
3
+ "version": "0.3.1",
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",
7
7
  "bin": {
@@ -15,6 +15,8 @@
15
15
  ],
16
16
  "scripts": {
17
17
  "start": "node index.js",
18
+ "test": "vitest run",
19
+ "test:watch": "vitest",
18
20
  "feature:create": "./bin/create-feature",
19
21
  "release:create": "./bin/create-release",
20
22
  "pr:create": "./bin/create-pr"
@@ -34,6 +36,10 @@
34
36
  "@modelcontextprotocol/sdk": "^1.17.1",
35
37
  "eventsource": "^4.0.0"
36
38
  },
39
+ "devDependencies": {
40
+ "happy-dom": "^20.0.8",
41
+ "vitest": "^4.0.3"
42
+ },
37
43
  "engines": {
38
44
  "node": ">=18.0.0"
39
45
  },