@robosystems/mcp 0.4.2 → 0.5.0
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.
- package/README.md +19 -38
- package/index.js +33 -1332
- package/package.json +1 -5
package/index.js
CHANGED
|
@@ -1,29 +1,24 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* RoboSystems MCP
|
|
4
|
+
* RoboSystems MCP stdio proxy.
|
|
5
5
|
*
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* A transparent pipe between a stdio-only MCP client (Claude Desktop, or any
|
|
7
|
+
* host that cannot speak HTTP transports) and the platform's native MCP
|
|
8
|
+
* endpoint (Streamable HTTP). Every JSON-RPC message is forwarded verbatim
|
|
9
|
+
* with the API-key header attached, so per-session instructions, live tool
|
|
10
|
+
* lists and streamed progress notifications behave exactly as they do when
|
|
11
|
+
* the URL is connected directly. The proxy adds nothing of its own.
|
|
9
12
|
*
|
|
10
|
-
*
|
|
11
|
-
* -
|
|
12
|
-
*
|
|
13
|
-
* - Retry logic for network resilience
|
|
14
|
-
* - Progress tracking for long operations
|
|
15
|
-
* - Clean resource management
|
|
13
|
+
* The REST-aggregating bridge that used to live here (GET /mcp/tools + POST
|
|
14
|
+
* /mcp/call-tool, plus client-side workspace tools) was retired when the
|
|
15
|
+
* server removed those endpoints; every server speaks the transport.
|
|
16
16
|
*/
|
|
17
17
|
|
|
18
|
-
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
19
|
-
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
20
|
-
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
21
|
-
import { EventSource } from 'eventsource'
|
|
22
|
-
import { runProxy } from './proxy.js'
|
|
23
18
|
import { readFileSync } from 'fs'
|
|
24
19
|
import { fileURLToPath } from 'url'
|
|
25
20
|
import { dirname, join } from 'path'
|
|
26
|
-
import {
|
|
21
|
+
import { runProxy } from './proxy.js'
|
|
27
22
|
|
|
28
23
|
// Get package version dynamically
|
|
29
24
|
const __filename = fileURLToPath(import.meta.url)
|
|
@@ -35,7 +30,7 @@ const PACKAGE_VERSION = packageJson.version
|
|
|
35
30
|
* Numeric semver compare for the three core components ("1.2.3").
|
|
36
31
|
* Pre-release tags are ignored — good enough for a stale-version warning.
|
|
37
32
|
*/
|
|
38
|
-
function _isNewerVersion(latest, current) {
|
|
33
|
+
export function _isNewerVersion(latest, current) {
|
|
39
34
|
const a = String(latest)
|
|
40
35
|
.split('.')
|
|
41
36
|
.map((n) => parseInt(n, 10) || 0)
|
|
@@ -80,1336 +75,42 @@ async function checkForUpdate() {
|
|
|
80
75
|
}
|
|
81
76
|
|
|
82
77
|
/**
|
|
83
|
-
*
|
|
84
|
-
*
|
|
78
|
+
* The endpoint to forward to: an explicit ROBOSYSTEMS_MCP_URL wins (a local
|
|
79
|
+
* stack, or the graph-agnostic OAuth endpoint); otherwise the per-graph URL
|
|
80
|
+
* is derived from ROBOSYSTEMS_GRAPH_ID. Returns null when neither is set.
|
|
85
81
|
*/
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
this.connectionTTL = 30000 // 30 seconds
|
|
91
|
-
}
|
|
92
|
-
|
|
93
|
-
getConnection(operationId, url, headers) {
|
|
94
|
-
// Check for existing connection
|
|
95
|
-
if (this.connections.has(operationId)) {
|
|
96
|
-
const conn = this.connections.get(operationId)
|
|
97
|
-
conn.lastUsed = Date.now()
|
|
98
|
-
return conn.eventSource
|
|
99
|
-
}
|
|
100
|
-
|
|
101
|
-
// Clean up old connections if at limit
|
|
102
|
-
if (this.connections.size >= this.maxConnections) {
|
|
103
|
-
this.evictOldest()
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// Create new connection
|
|
107
|
-
const eventSource = new EventSource(url, { headers })
|
|
108
|
-
|
|
109
|
-
// Auto-cleanup after TTL - store timer ID to prevent memory leaks
|
|
110
|
-
const cleanupTimer = setTimeout(() => {
|
|
111
|
-
this.closeConnection(operationId)
|
|
112
|
-
}, this.connectionTTL)
|
|
113
|
-
|
|
114
|
-
this.connections.set(operationId, {
|
|
115
|
-
eventSource,
|
|
116
|
-
createdAt: Date.now(),
|
|
117
|
-
lastUsed: Date.now(),
|
|
118
|
-
cleanupTimer,
|
|
119
|
-
})
|
|
120
|
-
|
|
121
|
-
return eventSource
|
|
122
|
-
}
|
|
123
|
-
|
|
124
|
-
evictOldest() {
|
|
125
|
-
let oldest = null
|
|
126
|
-
let oldestTime = Date.now()
|
|
127
|
-
|
|
128
|
-
for (const [id, conn] of this.connections) {
|
|
129
|
-
if (conn.lastUsed < oldestTime) {
|
|
130
|
-
oldest = id
|
|
131
|
-
oldestTime = conn.lastUsed
|
|
132
|
-
}
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
if (oldest) {
|
|
136
|
-
this.closeConnection(oldest)
|
|
137
|
-
}
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
closeConnection(operationId) {
|
|
141
|
-
const conn = this.connections.get(operationId)
|
|
142
|
-
if (conn) {
|
|
143
|
-
// Clear the cleanup timer to prevent memory leaks
|
|
144
|
-
if (conn.cleanupTimer) {
|
|
145
|
-
clearTimeout(conn.cleanupTimer)
|
|
146
|
-
}
|
|
147
|
-
conn.eventSource.close()
|
|
148
|
-
this.connections.delete(operationId)
|
|
149
|
-
}
|
|
150
|
-
}
|
|
151
|
-
|
|
152
|
-
closeAll() {
|
|
153
|
-
for (const [id] of this.connections) {
|
|
154
|
-
this.closeConnection(id)
|
|
155
|
-
}
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
|
|
159
|
-
/**
|
|
160
|
-
* Simple Result Cache
|
|
161
|
-
* Caches frequently accessed data like schemas
|
|
162
|
-
*/
|
|
163
|
-
class ResultCache {
|
|
164
|
-
constructor() {
|
|
165
|
-
this.cache = new Map()
|
|
166
|
-
this.cacheExpiry = new Map()
|
|
167
|
-
}
|
|
168
|
-
|
|
169
|
-
generateKey(tool, args, workspaceId = null) {
|
|
170
|
-
// Sort object keys to ensure deterministic cache keys
|
|
171
|
-
// Include workspaceId to prevent cache collisions across workspaces
|
|
172
|
-
const sortedArgs = this._sortObjectKeys(args)
|
|
173
|
-
const data = JSON.stringify({ tool, args: sortedArgs, workspace: workspaceId }, null, 0)
|
|
174
|
-
return createHash('sha256').update(data).digest('hex')
|
|
175
|
-
}
|
|
176
|
-
|
|
177
|
-
_sortObjectKeys(obj) {
|
|
178
|
-
if (obj === null || typeof obj !== 'object') {
|
|
179
|
-
return obj
|
|
180
|
-
}
|
|
181
|
-
if (Array.isArray(obj)) {
|
|
182
|
-
return obj.map((item) => this._sortObjectKeys(item))
|
|
183
|
-
}
|
|
184
|
-
const sortedObj = {}
|
|
185
|
-
Object.keys(obj)
|
|
186
|
-
.sort()
|
|
187
|
-
.forEach((key) => {
|
|
188
|
-
sortedObj[key] = this._sortObjectKeys(obj[key])
|
|
189
|
-
})
|
|
190
|
-
return sortedObj
|
|
191
|
-
}
|
|
192
|
-
|
|
193
|
-
get(tool, args, workspaceId = null) {
|
|
194
|
-
const key = this.generateKey(tool, args, workspaceId)
|
|
195
|
-
|
|
196
|
-
if (this.cache.has(key)) {
|
|
197
|
-
const expiry = this.cacheExpiry.get(key)
|
|
198
|
-
if (expiry > Date.now()) {
|
|
199
|
-
return this.cache.get(key)
|
|
200
|
-
} else {
|
|
201
|
-
// Expired - remove from cache
|
|
202
|
-
this.cache.delete(key)
|
|
203
|
-
this.cacheExpiry.delete(key)
|
|
204
|
-
}
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
return null
|
|
208
|
-
}
|
|
209
|
-
|
|
210
|
-
set(tool, args, result, ttlSeconds = 300, workspaceId = null) {
|
|
211
|
-
const key = this.generateKey(tool, args, workspaceId)
|
|
212
|
-
this.cache.set(key, result)
|
|
213
|
-
this.cacheExpiry.set(key, Date.now() + ttlSeconds * 1000)
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
clear() {
|
|
217
|
-
this.cache.clear()
|
|
218
|
-
this.cacheExpiry.clear()
|
|
219
|
-
}
|
|
220
|
-
}
|
|
221
|
-
|
|
222
|
-
/**
|
|
223
|
-
* RoboSystems MCP Client
|
|
224
|
-
* Handles communication with the RoboSystems API
|
|
225
|
-
*/
|
|
226
|
-
class RoboSystemsMCPClient {
|
|
227
|
-
constructor(baseUrl, apiKey, graphId) {
|
|
228
|
-
this.baseUrl = baseUrl.replace(/\/$/, '') // Remove trailing slash
|
|
229
|
-
this.apiKey = apiKey
|
|
230
|
-
this.primaryGraphId = graphId // Parent graph (never changes)
|
|
231
|
-
this.activeGraphId = graphId // Currently active graph (can switch to workspaces)
|
|
232
|
-
this.graphId = graphId // Deprecated: kept for backward compatibility
|
|
233
|
-
this.instructions = null // Per-graph routing guidance for the active graph (set by getTools)
|
|
234
|
-
this.headers = {
|
|
235
|
-
'X-API-Key': apiKey,
|
|
236
|
-
'Content-Type': 'application/json',
|
|
237
|
-
'User-Agent': `robosystems-mcp/${PACKAGE_VERSION}`,
|
|
238
|
-
'X-MCP-Client': PACKAGE_VERSION,
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
// Initialize components
|
|
242
|
-
this.connectionPool = new SSEConnectionPool()
|
|
243
|
-
this.resultCache = new ResultCache()
|
|
244
|
-
this.maxRetries = 3
|
|
245
|
-
this.baseRetryDelay = 1000
|
|
246
|
-
|
|
247
|
-
// Workspace tracking
|
|
248
|
-
this.workspaces = new Map()
|
|
249
|
-
this.workspaces.set(graphId, {
|
|
250
|
-
type: 'primary',
|
|
251
|
-
name: 'main',
|
|
252
|
-
created_at: Date.now(),
|
|
253
|
-
parent_graph_id: null,
|
|
254
|
-
})
|
|
255
|
-
|
|
256
|
-
// Simple metrics
|
|
257
|
-
this.metrics = {
|
|
258
|
-
totalRequests: 0,
|
|
259
|
-
cacheHits: 0,
|
|
260
|
-
errors: 0,
|
|
261
|
-
workspaceSwitches: 0,
|
|
262
|
-
}
|
|
263
|
-
}
|
|
264
|
-
|
|
265
|
-
async getTools() {
|
|
266
|
-
try {
|
|
267
|
-
console.error(`Fetching tools from ${this.baseUrl}/v1/graphs/${this.activeGraphId}/mcp/tools`)
|
|
268
|
-
const response = await fetch(`${this.baseUrl}/v1/graphs/${this.activeGraphId}/mcp/tools`, {
|
|
269
|
-
headers: this.headers,
|
|
270
|
-
})
|
|
271
|
-
|
|
272
|
-
if (!response.ok) {
|
|
273
|
-
const text = await response.text()
|
|
274
|
-
console.error(`API returned ${response.status}: ${text}`)
|
|
275
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
276
|
-
}
|
|
277
|
-
|
|
278
|
-
const data = await response.json()
|
|
279
|
-
let tools = data.tools || []
|
|
280
|
-
// Per-graph routing guidance for the active graph. Surfaced to the host
|
|
281
|
-
// via the handshake `instructions` field (primary graph) and inline in
|
|
282
|
-
// switch-workspace results (switched graph).
|
|
283
|
-
this.instructions = data.instructions ?? null
|
|
284
|
-
console.error(`Got ${tools.length} tools from API`)
|
|
285
|
-
|
|
286
|
-
// Add client-side workspace tools (if not already provided by server)
|
|
287
|
-
const workspaceToolNames = [
|
|
288
|
-
'create-workspace',
|
|
289
|
-
'switch-workspace',
|
|
290
|
-
'delete-workspace',
|
|
291
|
-
'list-workspaces',
|
|
292
|
-
]
|
|
293
|
-
const hasWorkspaceTools = tools.some((t) => workspaceToolNames.includes(t.name))
|
|
294
|
-
|
|
295
|
-
if (!hasWorkspaceTools) {
|
|
296
|
-
const workspaceTools = this._getWorkspaceToolDefinitions()
|
|
297
|
-
tools = [...tools, ...workspaceTools]
|
|
298
|
-
console.error(`Added ${workspaceTools.length} client-side workspace tools`)
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
return tools
|
|
302
|
-
} catch (error) {
|
|
303
|
-
console.error(`Failed to get tools: ${error.message}`)
|
|
304
|
-
console.error(`Stack: ${error.stack}`)
|
|
305
|
-
this.instructions = null
|
|
306
|
-
return []
|
|
307
|
-
}
|
|
308
|
-
}
|
|
309
|
-
|
|
310
|
-
_getWorkspaceToolDefinitions() {
|
|
311
|
-
return [
|
|
312
|
-
{
|
|
313
|
-
name: 'create-workspace',
|
|
314
|
-
description:
|
|
315
|
-
'Create an isolated workspace (subgraph) for experimentation. Data and queries are isolated from the main graph.',
|
|
316
|
-
inputSchema: {
|
|
317
|
-
type: 'object',
|
|
318
|
-
properties: {
|
|
319
|
-
name: {
|
|
320
|
-
type: 'string',
|
|
321
|
-
description: 'Workspace name (alphanumeric only, 1-20 characters)',
|
|
322
|
-
},
|
|
323
|
-
description: {
|
|
324
|
-
type: 'string',
|
|
325
|
-
description: 'Optional workspace description',
|
|
326
|
-
},
|
|
327
|
-
fork_parent: {
|
|
328
|
-
type: 'boolean',
|
|
329
|
-
description: 'Copy data from parent graph to workspace',
|
|
330
|
-
default: false,
|
|
331
|
-
},
|
|
332
|
-
subgraph_type: {
|
|
333
|
-
type: 'string',
|
|
334
|
-
enum: ['static', 'knowledge'],
|
|
335
|
-
description:
|
|
336
|
-
'Type of subgraph: "static" for a standard isolated workspace, "knowledge" for one seeded with the knowledge schema',
|
|
337
|
-
default: 'static',
|
|
338
|
-
},
|
|
339
|
-
},
|
|
340
|
-
required: ['name'],
|
|
341
|
-
},
|
|
342
|
-
},
|
|
343
|
-
{
|
|
344
|
-
name: 'switch-workspace',
|
|
345
|
-
description:
|
|
346
|
-
'Switch to a different workspace or back to the primary graph. All subsequent operations will use the active workspace.',
|
|
347
|
-
inputSchema: {
|
|
348
|
-
type: 'object',
|
|
349
|
-
properties: {
|
|
350
|
-
workspace_id: {
|
|
351
|
-
type: 'string',
|
|
352
|
-
description: 'Workspace ID to switch to, or "primary" for main graph',
|
|
353
|
-
},
|
|
354
|
-
},
|
|
355
|
-
required: ['workspace_id'],
|
|
356
|
-
},
|
|
357
|
-
},
|
|
358
|
-
{
|
|
359
|
-
name: 'delete-workspace',
|
|
360
|
-
description:
|
|
361
|
-
'Delete a workspace and all its data. Cannot delete the primary graph. Switches back to primary if deleting active workspace.',
|
|
362
|
-
inputSchema: {
|
|
363
|
-
type: 'object',
|
|
364
|
-
properties: {
|
|
365
|
-
workspace_id: {
|
|
366
|
-
type: 'string',
|
|
367
|
-
description: 'Workspace ID to delete',
|
|
368
|
-
},
|
|
369
|
-
force: {
|
|
370
|
-
type: 'boolean',
|
|
371
|
-
description: 'Force deletion even if workspace contains data',
|
|
372
|
-
default: false,
|
|
373
|
-
},
|
|
374
|
-
},
|
|
375
|
-
required: ['workspace_id'],
|
|
376
|
-
},
|
|
377
|
-
},
|
|
378
|
-
{
|
|
379
|
-
name: 'list-workspaces',
|
|
380
|
-
description: 'List all workspaces and show which one is currently active',
|
|
381
|
-
inputSchema: {
|
|
382
|
-
type: 'object',
|
|
383
|
-
properties: {},
|
|
384
|
-
},
|
|
385
|
-
},
|
|
386
|
-
]
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
async callTool(name, args = {}) {
|
|
390
|
-
this.metrics.totalRequests++
|
|
391
|
-
|
|
392
|
-
// Intercept workspace management tools (client-side implementation)
|
|
393
|
-
if (name === 'create-workspace') {
|
|
394
|
-
return this._handleCreateWorkspace(args)
|
|
395
|
-
}
|
|
396
|
-
if (name === 'switch-workspace') {
|
|
397
|
-
return this._handleSwitchWorkspace(args)
|
|
398
|
-
}
|
|
399
|
-
if (name === 'delete-workspace') {
|
|
400
|
-
return this._handleDeleteWorkspace(args)
|
|
401
|
-
}
|
|
402
|
-
if (name === 'list-workspaces') {
|
|
403
|
-
return this._handleListWorkspaces()
|
|
404
|
-
}
|
|
405
|
-
|
|
406
|
-
// Check cache first for cacheable tools
|
|
407
|
-
if (this.isCacheable(name)) {
|
|
408
|
-
const cached = this.resultCache.get(name, args, this.activeGraphId)
|
|
409
|
-
if (cached) {
|
|
410
|
-
this.metrics.cacheHits++
|
|
411
|
-
return cached
|
|
412
|
-
}
|
|
413
|
-
}
|
|
414
|
-
|
|
415
|
-
// Execute with simple retry logic
|
|
416
|
-
return this.executeWithRetry(() => this._callToolInternal(name, args))
|
|
417
|
-
}
|
|
418
|
-
|
|
419
|
-
async _callToolInternal(name, args) {
|
|
420
|
-
try {
|
|
421
|
-
const headers = {
|
|
422
|
-
...this.headers,
|
|
423
|
-
Accept: 'text/event-stream, application/x-ndjson, application/json',
|
|
424
|
-
}
|
|
425
|
-
|
|
426
|
-
const response = await fetch(
|
|
427
|
-
`${this.baseUrl}/v1/graphs/${this.activeGraphId}/mcp/call-tool`,
|
|
428
|
-
{
|
|
429
|
-
method: 'POST',
|
|
430
|
-
headers,
|
|
431
|
-
body: JSON.stringify({ name, arguments: args }),
|
|
432
|
-
}
|
|
433
|
-
)
|
|
434
|
-
|
|
435
|
-
const contentType = response.headers.get('content-type') || ''
|
|
436
|
-
|
|
437
|
-
let result
|
|
438
|
-
if (contentType.includes('text/event-stream')) {
|
|
439
|
-
result = await this.handleSSEResponse(response, name)
|
|
440
|
-
} else if (contentType.includes('application/x-ndjson')) {
|
|
441
|
-
result = await this.handleNDJSONResponse(response, name)
|
|
442
|
-
} else if (response.status === 202) {
|
|
443
|
-
result = await this.handleQueuedResponse(response, name)
|
|
444
|
-
} else {
|
|
445
|
-
if (!response.ok) {
|
|
446
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
447
|
-
}
|
|
448
|
-
const data = await response.json()
|
|
449
|
-
// The API returns { result: { type: 'text', text: JSON.stringify(actualData) } }
|
|
450
|
-
if (data.result && data.result.type === 'text' && data.result.text) {
|
|
451
|
-
// Parse the text field if it contains JSON data
|
|
452
|
-
try {
|
|
453
|
-
const parsedText = JSON.parse(data.result.text)
|
|
454
|
-
result = { type: 'text', text: JSON.stringify(parsedText, null, 2) }
|
|
455
|
-
} catch (_e) {
|
|
456
|
-
// If it's not JSON, just use it as-is
|
|
457
|
-
result = data.result
|
|
458
|
-
}
|
|
459
|
-
} else {
|
|
460
|
-
result = data.result || { type: 'text', text: 'No result' }
|
|
461
|
-
}
|
|
462
|
-
}
|
|
463
|
-
|
|
464
|
-
// Cache the result if appropriate
|
|
465
|
-
if (this.isCacheable(name)) {
|
|
466
|
-
const ttl = this.getCacheTTL(name)
|
|
467
|
-
this.resultCache.set(name, args, result, ttl, this.activeGraphId)
|
|
468
|
-
}
|
|
469
|
-
|
|
470
|
-
return result
|
|
471
|
-
} catch (error) {
|
|
472
|
-
this.metrics.errors++
|
|
473
|
-
console.error(`Failed to call tool ${name}: ${error.message}`)
|
|
474
|
-
throw error
|
|
475
|
-
}
|
|
476
|
-
}
|
|
477
|
-
|
|
478
|
-
async executeWithRetry(fn) {
|
|
479
|
-
let lastError = null
|
|
480
|
-
|
|
481
|
-
for (let attempt = 0; attempt < this.maxRetries; attempt++) {
|
|
482
|
-
try {
|
|
483
|
-
return await fn()
|
|
484
|
-
} catch (error) {
|
|
485
|
-
lastError = error
|
|
486
|
-
|
|
487
|
-
// Don't retry on auth errors or client errors
|
|
488
|
-
if (
|
|
489
|
-
error.message.includes('401') ||
|
|
490
|
-
error.message.includes('403') ||
|
|
491
|
-
error.message.includes('400')
|
|
492
|
-
) {
|
|
493
|
-
break
|
|
494
|
-
}
|
|
495
|
-
|
|
496
|
-
if (attempt < this.maxRetries - 1) {
|
|
497
|
-
const delay = this.baseRetryDelay * Math.pow(2, attempt)
|
|
498
|
-
await new Promise((resolve) => setTimeout(resolve, delay))
|
|
499
|
-
}
|
|
500
|
-
}
|
|
501
|
-
}
|
|
502
|
-
|
|
503
|
-
return {
|
|
504
|
-
type: 'text',
|
|
505
|
-
text: `Error after ${this.maxRetries} attempts: ${lastError?.message || 'Unknown error'}`,
|
|
506
|
-
}
|
|
507
|
-
}
|
|
508
|
-
|
|
509
|
-
async handleSSEResponse(response, toolName) {
|
|
510
|
-
// Read SSE events directly from the POST response body instead of opening
|
|
511
|
-
// a new EventSource. EventSource always uses GET, which 405s on this
|
|
512
|
-
// POST-only endpoint. The SSE stream is already in the response body.
|
|
513
|
-
const events = []
|
|
514
|
-
const reader = response.body.getReader()
|
|
515
|
-
const decoder = new TextDecoder()
|
|
516
|
-
let buffer = ''
|
|
517
|
-
|
|
518
|
-
let timeoutId
|
|
519
|
-
const timeout = new Promise((_, reject) => {
|
|
520
|
-
timeoutId = setTimeout(() => reject(new Error('SSE timeout after 5 minutes')), 300000)
|
|
521
|
-
})
|
|
522
|
-
|
|
523
|
-
const readStream = async () => {
|
|
524
|
-
try {
|
|
525
|
-
while (true) {
|
|
526
|
-
const { done, value } = await reader.read()
|
|
527
|
-
if (done) break
|
|
528
|
-
|
|
529
|
-
buffer += decoder.decode(value, { stream: true })
|
|
530
|
-
const lines = buffer.split(/\r?\n/)
|
|
531
|
-
buffer = lines.pop() || ''
|
|
532
|
-
|
|
533
|
-
for (const line of lines) {
|
|
534
|
-
if (line.startsWith('data:')) {
|
|
535
|
-
const dataStr = line.slice(5).trim()
|
|
536
|
-
if (!dataStr || dataStr === '[DONE]') continue
|
|
537
|
-
|
|
538
|
-
let data
|
|
539
|
-
try {
|
|
540
|
-
data = JSON.parse(dataStr)
|
|
541
|
-
} catch (e) {
|
|
542
|
-
console.error('Failed to parse SSE event:', e)
|
|
543
|
-
continue
|
|
544
|
-
}
|
|
545
|
-
|
|
546
|
-
const eventType = data.event || 'message'
|
|
547
|
-
|
|
548
|
-
if (eventType === 'operation_error') {
|
|
549
|
-
throw new Error(data.data?.error || data.data?.message || 'Operation failed')
|
|
550
|
-
}
|
|
551
|
-
|
|
552
|
-
if (eventType === 'operation_progress' || eventType === 'progress') {
|
|
553
|
-
const progress = data.data?.percentage ? `${data.data.percentage}% - ` : ''
|
|
554
|
-
console.error(`Progress: ${progress}${data.data?.message || 'Processing...'}`)
|
|
555
|
-
continue
|
|
556
|
-
}
|
|
557
|
-
|
|
558
|
-
events.push({ event: eventType, data: data.data ?? data })
|
|
559
|
-
|
|
560
|
-
if (eventType === 'complete' || eventType === 'operation_completed') {
|
|
561
|
-
return
|
|
562
|
-
}
|
|
563
|
-
} else if (line.startsWith('event:')) {
|
|
564
|
-
// event: lines are handled via the data: payload's event field
|
|
565
|
-
}
|
|
566
|
-
}
|
|
567
|
-
}
|
|
568
|
-
} finally {
|
|
569
|
-
reader.cancel().catch(() => {})
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
try {
|
|
574
|
-
await Promise.race([readStream(), timeout])
|
|
575
|
-
} finally {
|
|
576
|
-
clearTimeout(timeoutId)
|
|
577
|
-
reader.cancel().catch(() => {})
|
|
578
|
-
}
|
|
579
|
-
|
|
580
|
-
if (events.length === 0) {
|
|
581
|
-
throw new Error('SSE connection failed')
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
return this.aggregateStreamedResults(events, toolName)
|
|
585
|
-
}
|
|
586
|
-
|
|
587
|
-
async handleNDJSONResponse(response) {
|
|
588
|
-
const events = []
|
|
589
|
-
const reader = response.body.getReader()
|
|
590
|
-
const decoder = new TextDecoder()
|
|
591
|
-
let buffer = ''
|
|
592
|
-
|
|
593
|
-
try {
|
|
594
|
-
while (true) {
|
|
595
|
-
const { done, value } = await reader.read()
|
|
596
|
-
if (done) break
|
|
597
|
-
|
|
598
|
-
buffer += decoder.decode(value, { stream: true })
|
|
599
|
-
const lines = buffer.split('\n')
|
|
600
|
-
buffer = lines.pop() || ''
|
|
601
|
-
|
|
602
|
-
for (const line of lines) {
|
|
603
|
-
if (line.trim()) {
|
|
604
|
-
try {
|
|
605
|
-
const event = JSON.parse(line)
|
|
606
|
-
events.push(event)
|
|
607
|
-
} catch (e) {
|
|
608
|
-
console.error('Failed to parse NDJSON line:', e)
|
|
609
|
-
}
|
|
610
|
-
}
|
|
611
|
-
}
|
|
612
|
-
}
|
|
613
|
-
|
|
614
|
-
if (buffer.trim()) {
|
|
615
|
-
try {
|
|
616
|
-
const event = JSON.parse(buffer)
|
|
617
|
-
events.push(event)
|
|
618
|
-
} catch (e) {
|
|
619
|
-
console.error('Failed to parse final NDJSON line:', e)
|
|
620
|
-
}
|
|
621
|
-
}
|
|
622
|
-
|
|
623
|
-
return this.aggregateStreamedResults(events, 'ndjson')
|
|
624
|
-
} catch (error) {
|
|
625
|
-
console.error('NDJSON parsing error:', error)
|
|
626
|
-
return { type: 'text', text: `Error parsing streaming response: ${error.message}` }
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
|
-
|
|
630
|
-
async handleQueuedResponse(response) {
|
|
631
|
-
const data = await response.json()
|
|
632
|
-
|
|
633
|
-
if (data.queued && data.queue_id) {
|
|
634
|
-
console.error(`Query queued with ID: ${data.queue_id}`)
|
|
635
|
-
|
|
636
|
-
const statusUrl =
|
|
637
|
-
data.status_url ||
|
|
638
|
-
`${this.baseUrl}/v1/graphs/${this.activeGraphId}/query/${data.queue_id}/status`
|
|
639
|
-
const resultUrl =
|
|
640
|
-
data.result_url ||
|
|
641
|
-
`${this.baseUrl}/v1/graphs/${this.activeGraphId}/query/${data.queue_id}/result`
|
|
642
|
-
|
|
643
|
-
// Simple polling with exponential backoff
|
|
644
|
-
let attempts = 0
|
|
645
|
-
let delay = 1000
|
|
646
|
-
const maxAttempts = 30
|
|
647
|
-
|
|
648
|
-
while (attempts < maxAttempts) {
|
|
649
|
-
await new Promise((resolve) => setTimeout(resolve, delay))
|
|
650
|
-
|
|
651
|
-
try {
|
|
652
|
-
const statusResponse = await fetch(statusUrl, { headers: this.headers })
|
|
653
|
-
|
|
654
|
-
if (statusResponse.ok) {
|
|
655
|
-
const status = await statusResponse.json()
|
|
656
|
-
|
|
657
|
-
if (status.status === 'completed') {
|
|
658
|
-
const resultResponse = await fetch(resultUrl, { headers: this.headers })
|
|
659
|
-
if (resultResponse.ok) {
|
|
660
|
-
const result = await resultResponse.json()
|
|
661
|
-
return { type: 'text', text: JSON.stringify(result, null, 2) }
|
|
662
|
-
}
|
|
663
|
-
} else if (status.status === 'failed') {
|
|
664
|
-
return { type: 'text', text: `Query failed: ${status.error || 'Unknown error'}` }
|
|
665
|
-
} else if (status.status === 'cancelled') {
|
|
666
|
-
return { type: 'text', text: 'Query was cancelled' }
|
|
667
|
-
}
|
|
668
|
-
}
|
|
669
|
-
} catch (e) {
|
|
670
|
-
console.error('Polling error:', e)
|
|
671
|
-
}
|
|
672
|
-
|
|
673
|
-
attempts++
|
|
674
|
-
delay = Math.min(delay * 1.5, 10000)
|
|
675
|
-
}
|
|
676
|
-
|
|
677
|
-
return { type: 'text', text: 'Query timed out waiting for result' }
|
|
678
|
-
}
|
|
679
|
-
|
|
680
|
-
return { type: 'text', text: JSON.stringify(data, null, 2) }
|
|
681
|
-
}
|
|
682
|
-
|
|
683
|
-
aggregateStreamedResults(events) {
|
|
684
|
-
// Check for errors
|
|
685
|
-
const errorEvent = events.find((e) => e.event === 'error' || e.event === 'operation_error')
|
|
686
|
-
if (errorEvent) {
|
|
687
|
-
return {
|
|
688
|
-
type: 'text',
|
|
689
|
-
text: `Error: ${errorEvent.data.error || errorEvent.data.message || 'Tool execution failed'}`,
|
|
690
|
-
}
|
|
691
|
-
}
|
|
692
|
-
|
|
693
|
-
// Check for non-streaming query results first (fallback path)
|
|
694
|
-
const queryResult = events.find((e) => e.event === 'query_result')
|
|
695
|
-
if (queryResult && queryResult.data) {
|
|
696
|
-
const result = queryResult.data.result
|
|
697
|
-
if (result) {
|
|
698
|
-
return {
|
|
699
|
-
type: 'text',
|
|
700
|
-
text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),
|
|
701
|
-
}
|
|
702
|
-
}
|
|
703
|
-
}
|
|
704
|
-
|
|
705
|
-
// Aggregate query chunks - check for both possible event names
|
|
706
|
-
const queryChunks = events.filter((e) => e.event === 'query_chunk' || e.event === 'data_chunk')
|
|
707
|
-
if (queryChunks.length > 0) {
|
|
708
|
-
const allRows = []
|
|
709
|
-
let columns = null
|
|
710
|
-
|
|
711
|
-
for (const chunk of queryChunks) {
|
|
712
|
-
if (!columns && chunk.data.columns) {
|
|
713
|
-
columns = chunk.data.columns
|
|
714
|
-
}
|
|
715
|
-
if (chunk.data.data) {
|
|
716
|
-
allRows.push(...chunk.data.data)
|
|
717
|
-
}
|
|
718
|
-
}
|
|
719
|
-
|
|
720
|
-
// Only return data if we actually got some
|
|
721
|
-
if (allRows.length > 0 || columns) {
|
|
722
|
-
return {
|
|
723
|
-
type: 'text',
|
|
724
|
-
text: JSON.stringify(
|
|
725
|
-
{
|
|
726
|
-
columns: columns || [],
|
|
727
|
-
data: allRows,
|
|
728
|
-
row_count: allRows.length,
|
|
729
|
-
},
|
|
730
|
-
null,
|
|
731
|
-
2
|
|
732
|
-
),
|
|
733
|
-
}
|
|
734
|
-
}
|
|
735
|
-
}
|
|
736
|
-
|
|
737
|
-
// Look for completion event - match what server actually sends
|
|
738
|
-
const resultEvent = events.find(
|
|
739
|
-
(e) =>
|
|
740
|
-
e.event === 'operation_completed' ||
|
|
741
|
-
e.event === 'complete' ||
|
|
742
|
-
e.event === 'query_complete' ||
|
|
743
|
-
e.event === 'result' ||
|
|
744
|
-
e.event === 'query_result'
|
|
745
|
-
)
|
|
746
|
-
if (resultEvent) {
|
|
747
|
-
const result = resultEvent.data.result || resultEvent.data
|
|
748
|
-
return {
|
|
749
|
-
type: 'text',
|
|
750
|
-
text: typeof result === 'string' ? result : JSON.stringify(result, null, 2),
|
|
751
|
-
}
|
|
752
|
-
}
|
|
753
|
-
|
|
754
|
-
// Default: return all events
|
|
755
|
-
return { type: 'text', text: JSON.stringify(events, null, 2) }
|
|
756
|
-
}
|
|
757
|
-
|
|
758
|
-
isCacheable(toolName) {
|
|
759
|
-
const cacheableTools = ['get-graph-schema', 'get-graph-info', 'describe-graph-structure']
|
|
760
|
-
return cacheableTools.includes(toolName)
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
getCacheTTL(toolName) {
|
|
764
|
-
const ttlMap = {
|
|
765
|
-
'get-graph-schema': 3600, // 1 hour
|
|
766
|
-
'get-graph-info': 300, // 5 minutes
|
|
767
|
-
'describe-graph-structure': 1800, // 30 minutes
|
|
768
|
-
}
|
|
769
|
-
return ttlMap[toolName] || 300
|
|
770
|
-
}
|
|
771
|
-
|
|
772
|
-
getMetrics() {
|
|
773
|
-
const cacheHitRate =
|
|
774
|
-
this.metrics.totalRequests > 0
|
|
775
|
-
? ((this.metrics.cacheHits / this.metrics.totalRequests) * 100).toFixed(1) + '%'
|
|
776
|
-
: '0%'
|
|
777
|
-
|
|
778
|
-
return {
|
|
779
|
-
totalRequests: this.metrics.totalRequests,
|
|
780
|
-
cacheHits: this.metrics.cacheHits,
|
|
781
|
-
cacheHitRate,
|
|
782
|
-
errors: this.metrics.errors,
|
|
783
|
-
activeConnections: this.connectionPool.connections.size,
|
|
784
|
-
workspaceSwitches: this.metrics.workspaceSwitches,
|
|
785
|
-
activeWorkspace: this.activeGraphId,
|
|
786
|
-
totalWorkspaces: this.workspaces.size,
|
|
787
|
-
}
|
|
788
|
-
}
|
|
789
|
-
|
|
790
|
-
// Workspace management methods
|
|
791
|
-
|
|
792
|
-
async _handleCreateWorkspace(args) {
|
|
793
|
-
const { name, description, fork_parent = false, subgraph_type = 'static' } = args
|
|
794
|
-
const validSubgraphTypes = ['static', 'knowledge']
|
|
795
|
-
|
|
796
|
-
if (!validSubgraphTypes.includes(subgraph_type)) {
|
|
797
|
-
throw new Error(
|
|
798
|
-
`Invalid subgraph_type "${subgraph_type}". Must be one of: ${validSubgraphTypes.join(', ')}`
|
|
799
|
-
)
|
|
800
|
-
}
|
|
801
|
-
|
|
802
|
-
try {
|
|
803
|
-
console.error(
|
|
804
|
-
`Creating workspace via MCP tool: ${name} (fork_parent: ${fork_parent}, type: ${subgraph_type})`
|
|
805
|
-
)
|
|
806
|
-
|
|
807
|
-
// Call the MCP tool endpoint (server handles the creation)
|
|
808
|
-
const response = await fetch(
|
|
809
|
-
`${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
|
|
810
|
-
{
|
|
811
|
-
method: 'POST',
|
|
812
|
-
headers: { ...this.headers, Accept: 'application/json' },
|
|
813
|
-
body: JSON.stringify({
|
|
814
|
-
name: 'create-subgraph',
|
|
815
|
-
arguments: { name, description, fork_parent, subgraph_type },
|
|
816
|
-
}),
|
|
817
|
-
}
|
|
818
|
-
)
|
|
819
|
-
|
|
820
|
-
if (!response.ok) {
|
|
821
|
-
const errorText = await response.text()
|
|
822
|
-
throw new Error(`HTTP ${response.status}: ${errorText}`)
|
|
823
|
-
}
|
|
824
|
-
|
|
825
|
-
const data = await response.json()
|
|
826
|
-
|
|
827
|
-
// Parse the result (server returns JSON in result.text)
|
|
828
|
-
let result
|
|
829
|
-
if (data.result && data.result.type === 'text' && data.result.text) {
|
|
830
|
-
try {
|
|
831
|
-
result = JSON.parse(data.result.text)
|
|
832
|
-
} catch (_e) {
|
|
833
|
-
result = { message: data.result.text }
|
|
834
|
-
}
|
|
835
|
-
} else {
|
|
836
|
-
result = data.result || data
|
|
837
|
-
}
|
|
838
|
-
|
|
839
|
-
// Check for errors from server
|
|
840
|
-
if (result.error) {
|
|
841
|
-
console.error(`Server error creating workspace: ${result.message}`)
|
|
842
|
-
return {
|
|
843
|
-
type: 'text',
|
|
844
|
-
text: JSON.stringify(result, null, 2),
|
|
845
|
-
}
|
|
846
|
-
}
|
|
847
|
-
|
|
848
|
-
// Server created the workspace successfully (`subgraph_id` on the
|
|
849
|
-
// current server; `workspace_id` accepted for older servers)
|
|
850
|
-
const workspaceId = result.subgraph_id ?? result.workspace_id
|
|
851
|
-
|
|
852
|
-
// Track the workspace
|
|
853
|
-
this.workspaces.set(workspaceId, {
|
|
854
|
-
type: 'workspace',
|
|
855
|
-
parent_graph_id: this.primaryGraphId,
|
|
856
|
-
name,
|
|
857
|
-
description: result.description || description,
|
|
858
|
-
created_at: Date.now(),
|
|
859
|
-
forked_from_parent: fork_parent,
|
|
860
|
-
})
|
|
861
|
-
|
|
862
|
-
// Automatically switch to the new workspace
|
|
863
|
-
const previousGraph = this.activeGraphId
|
|
864
|
-
this.activeGraphId = workspaceId
|
|
865
|
-
this.metrics.workspaceSwitches++
|
|
866
|
-
|
|
867
|
-
console.error(`Created and switched to workspace: ${workspaceId}`)
|
|
868
|
-
|
|
869
|
-
return {
|
|
870
|
-
type: 'text',
|
|
871
|
-
text: JSON.stringify(
|
|
872
|
-
{
|
|
873
|
-
success: true,
|
|
874
|
-
workspace_id: workspaceId,
|
|
875
|
-
name,
|
|
876
|
-
previous_workspace: previousGraph,
|
|
877
|
-
active: true,
|
|
878
|
-
forked_from_parent: fork_parent,
|
|
879
|
-
message: `Created workspace "${name}" and switched to it. All operations now use this isolated environment.`,
|
|
880
|
-
},
|
|
881
|
-
null,
|
|
882
|
-
2
|
|
883
|
-
),
|
|
884
|
-
}
|
|
885
|
-
} catch (error) {
|
|
886
|
-
console.error(`Failed to create workspace: ${error.message}`)
|
|
887
|
-
return {
|
|
888
|
-
type: 'text',
|
|
889
|
-
text: JSON.stringify(
|
|
890
|
-
{
|
|
891
|
-
error: 'Failed to create workspace',
|
|
892
|
-
message: error.message,
|
|
893
|
-
workspace_name: name,
|
|
894
|
-
},
|
|
895
|
-
null,
|
|
896
|
-
2
|
|
897
|
-
),
|
|
898
|
-
}
|
|
899
|
-
}
|
|
900
|
-
}
|
|
901
|
-
|
|
902
|
-
async _handleSwitchWorkspace(args) {
|
|
903
|
-
const { workspace_id } = args
|
|
904
|
-
|
|
905
|
-
// Handle "primary" alias
|
|
906
|
-
const targetGraphId = workspace_id === 'primary' ? this.primaryGraphId : workspace_id
|
|
907
|
-
|
|
908
|
-
// Validate workspace exists — if not found locally, refresh from server first
|
|
909
|
-
if (!this.workspaces.has(targetGraphId)) {
|
|
910
|
-
console.error(`Workspace "${targetGraphId}" not in local cache, refreshing from server...`)
|
|
911
|
-
await this._refreshWorkspacesCache()
|
|
912
|
-
}
|
|
913
|
-
|
|
914
|
-
if (!this.workspaces.has(targetGraphId)) {
|
|
915
|
-
return {
|
|
916
|
-
type: 'text',
|
|
917
|
-
text: JSON.stringify(
|
|
918
|
-
{
|
|
919
|
-
error: 'Unknown workspace',
|
|
920
|
-
workspace_id: targetGraphId,
|
|
921
|
-
message: `Workspace "${targetGraphId}" not found.`,
|
|
922
|
-
available_workspaces: Array.from(this.workspaces.keys()),
|
|
923
|
-
},
|
|
924
|
-
null,
|
|
925
|
-
2
|
|
926
|
-
),
|
|
927
|
-
}
|
|
928
|
-
}
|
|
929
|
-
|
|
930
|
-
// Already in this workspace?
|
|
931
|
-
if (this.activeGraphId === targetGraphId) {
|
|
932
|
-
return {
|
|
933
|
-
type: 'text',
|
|
934
|
-
text: JSON.stringify(
|
|
935
|
-
{
|
|
936
|
-
success: true,
|
|
937
|
-
workspace_id: targetGraphId,
|
|
938
|
-
message: `Already in workspace "${targetGraphId}"`,
|
|
939
|
-
},
|
|
940
|
-
null,
|
|
941
|
-
2
|
|
942
|
-
),
|
|
943
|
-
}
|
|
944
|
-
}
|
|
945
|
-
|
|
946
|
-
// Switch workspace
|
|
947
|
-
const previousGraph = this.activeGraphId
|
|
948
|
-
this.activeGraphId = targetGraphId
|
|
949
|
-
this.metrics.workspaceSwitches++
|
|
950
|
-
|
|
951
|
-
const workspace = this.workspaces.get(targetGraphId)
|
|
952
|
-
console.error(`Switched from ${previousGraph} to ${targetGraphId}`)
|
|
953
|
-
|
|
954
|
-
// The handshake `instructions` field is immutable mid-session, so surface
|
|
955
|
-
// the now-active graph's routing guidance inline in the switch result.
|
|
956
|
-
let instructions
|
|
957
|
-
try {
|
|
958
|
-
await this.getTools()
|
|
959
|
-
instructions = this.instructions || undefined
|
|
960
|
-
} catch (error) {
|
|
961
|
-
console.error(`Could not load instructions for ${targetGraphId}: ${error.message}`)
|
|
962
|
-
}
|
|
963
|
-
|
|
964
|
-
return {
|
|
965
|
-
type: 'text',
|
|
966
|
-
text: JSON.stringify(
|
|
967
|
-
{
|
|
968
|
-
success: true,
|
|
969
|
-
switched_from: previousGraph,
|
|
970
|
-
switched_to: targetGraphId,
|
|
971
|
-
workspace_type: workspace.type,
|
|
972
|
-
message: `Switched to ${workspace.type === 'primary' ? 'primary graph' : `workspace "${workspace.name}"`}. All operations now use this environment.`,
|
|
973
|
-
...(instructions ? { instructions } : {}),
|
|
974
|
-
},
|
|
975
|
-
null,
|
|
976
|
-
2
|
|
977
|
-
),
|
|
978
|
-
}
|
|
979
|
-
}
|
|
980
|
-
|
|
981
|
-
async _handleDeleteWorkspace(args) {
|
|
982
|
-
const { workspace_id, force = false } = args
|
|
983
|
-
|
|
984
|
-
try {
|
|
985
|
-
console.error(`Deleting workspace via MCP tool: ${workspace_id} (force: ${force})`)
|
|
986
|
-
|
|
987
|
-
// Call the MCP tool endpoint (server handles the deletion)
|
|
988
|
-
const response = await fetch(
|
|
989
|
-
`${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
|
|
990
|
-
{
|
|
991
|
-
method: 'POST',
|
|
992
|
-
headers: { ...this.headers, Accept: 'application/json' },
|
|
993
|
-
body: JSON.stringify({
|
|
994
|
-
name: 'delete-subgraph',
|
|
995
|
-
arguments: { subgraph_id: workspace_id, force },
|
|
996
|
-
}),
|
|
997
|
-
}
|
|
998
|
-
)
|
|
999
|
-
|
|
1000
|
-
if (!response.ok) {
|
|
1001
|
-
const errorText = await response.text()
|
|
1002
|
-
throw new Error(`HTTP ${response.status}: ${errorText}`)
|
|
1003
|
-
}
|
|
1004
|
-
|
|
1005
|
-
const data = await response.json()
|
|
1006
|
-
|
|
1007
|
-
// Parse the result
|
|
1008
|
-
let result
|
|
1009
|
-
if (data.result && data.result.type === 'text' && data.result.text) {
|
|
1010
|
-
try {
|
|
1011
|
-
result = JSON.parse(data.result.text)
|
|
1012
|
-
} catch (_e) {
|
|
1013
|
-
result = { message: data.result.text }
|
|
1014
|
-
}
|
|
1015
|
-
} else {
|
|
1016
|
-
result = data.result || data
|
|
1017
|
-
}
|
|
1018
|
-
|
|
1019
|
-
// Check for errors from server
|
|
1020
|
-
if (result.error) {
|
|
1021
|
-
console.error(`Server error deleting workspace: ${result.message}`)
|
|
1022
|
-
return {
|
|
1023
|
-
type: 'text',
|
|
1024
|
-
text: JSON.stringify(result, null, 2),
|
|
1025
|
-
}
|
|
1026
|
-
}
|
|
1027
|
-
|
|
1028
|
-
// Server deleted the workspace successfully
|
|
1029
|
-
const workspace = this.workspaces.get(workspace_id)
|
|
1030
|
-
if (workspace) {
|
|
1031
|
-
this.workspaces.delete(workspace_id)
|
|
1032
|
-
}
|
|
1033
|
-
|
|
1034
|
-
// Switch back to primary if we deleted the active workspace
|
|
1035
|
-
const switchedBack = this.activeGraphId === workspace_id
|
|
1036
|
-
if (switchedBack) {
|
|
1037
|
-
this.activeGraphId = this.primaryGraphId
|
|
1038
|
-
this.metrics.workspaceSwitches++
|
|
1039
|
-
}
|
|
1040
|
-
|
|
1041
|
-
console.error(
|
|
1042
|
-
`Deleted workspace: ${workspace_id}${switchedBack ? ' (switched back to primary)' : ''}`
|
|
1043
|
-
)
|
|
1044
|
-
|
|
1045
|
-
return {
|
|
1046
|
-
type: 'text',
|
|
1047
|
-
text: JSON.stringify(
|
|
1048
|
-
{
|
|
1049
|
-
success: true,
|
|
1050
|
-
deleted: workspace_id,
|
|
1051
|
-
active_workspace: this.activeGraphId,
|
|
1052
|
-
switched_back_to_primary: switchedBack,
|
|
1053
|
-
message:
|
|
1054
|
-
result.message ||
|
|
1055
|
-
`Deleted workspace "${workspace_id}"${switchedBack ? ' and switched back to primary graph' : ''}.`,
|
|
1056
|
-
},
|
|
1057
|
-
null,
|
|
1058
|
-
2
|
|
1059
|
-
),
|
|
1060
|
-
}
|
|
1061
|
-
} catch (error) {
|
|
1062
|
-
console.error(`Failed to delete workspace: ${error.message}`)
|
|
1063
|
-
return {
|
|
1064
|
-
type: 'text',
|
|
1065
|
-
text: JSON.stringify(
|
|
1066
|
-
{
|
|
1067
|
-
error: 'Failed to delete workspace',
|
|
1068
|
-
message: error.message,
|
|
1069
|
-
workspace_id,
|
|
1070
|
-
},
|
|
1071
|
-
null,
|
|
1072
|
-
2
|
|
1073
|
-
),
|
|
1074
|
-
}
|
|
1075
|
-
}
|
|
1076
|
-
}
|
|
1077
|
-
|
|
1078
|
-
async _refreshWorkspacesCache() {
|
|
1079
|
-
try {
|
|
1080
|
-
// The server tool family speaks "subgraphs" (`list-subgraphs`,
|
|
1081
|
-
// `subgraphs[].subgraph_id`); this client keeps the "workspace"
|
|
1082
|
-
// vocabulary on its own surface and normalizes here.
|
|
1083
|
-
const response = await fetch(
|
|
1084
|
-
`${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
|
|
1085
|
-
{
|
|
1086
|
-
method: 'POST',
|
|
1087
|
-
headers: { ...this.headers, Accept: 'application/json' },
|
|
1088
|
-
body: JSON.stringify({ name: 'list-subgraphs', arguments: {} }),
|
|
1089
|
-
}
|
|
1090
|
-
)
|
|
1091
|
-
|
|
1092
|
-
if (!response.ok) {
|
|
1093
|
-
const errorText = await response.text()
|
|
1094
|
-
throw new Error(`HTTP ${response.status}: ${errorText}`)
|
|
1095
|
-
}
|
|
1096
|
-
|
|
1097
|
-
const data = await response.json()
|
|
1098
|
-
|
|
1099
|
-
let result
|
|
1100
|
-
if (data.result && data.result.type === 'text' && data.result.text) {
|
|
1101
|
-
try {
|
|
1102
|
-
result = JSON.parse(data.result.text)
|
|
1103
|
-
} catch (_e) {
|
|
1104
|
-
result = { message: data.result.text }
|
|
1105
|
-
}
|
|
1106
|
-
} else {
|
|
1107
|
-
result = data.result || data
|
|
1108
|
-
}
|
|
1109
|
-
|
|
1110
|
-
if (!result.subgraphs) {
|
|
1111
|
-
return result
|
|
1112
|
-
}
|
|
1113
|
-
|
|
1114
|
-
const workspaces = result.subgraphs.map((sg) => ({
|
|
1115
|
-
workspace_id: sg.subgraph_id,
|
|
1116
|
-
type: sg.type === 'primary' ? 'primary' : 'workspace',
|
|
1117
|
-
name: sg.name,
|
|
1118
|
-
description: sg.description,
|
|
1119
|
-
parent_graph_id: sg.parent_graph_id,
|
|
1120
|
-
created_at: sg.created_at,
|
|
1121
|
-
}))
|
|
1122
|
-
|
|
1123
|
-
this.workspaces.clear()
|
|
1124
|
-
for (const ws of workspaces) {
|
|
1125
|
-
this.workspaces.set(ws.workspace_id, {
|
|
1126
|
-
type: ws.type,
|
|
1127
|
-
name: ws.name,
|
|
1128
|
-
description: ws.description,
|
|
1129
|
-
parent_graph_id: ws.parent_graph_id,
|
|
1130
|
-
created_at: ws.created_at ? new Date(ws.created_at).getTime() : Date.now(),
|
|
1131
|
-
})
|
|
1132
|
-
}
|
|
1133
|
-
|
|
1134
|
-
return {
|
|
1135
|
-
primary_graph_id: result.primary_graph_id,
|
|
1136
|
-
workspaces,
|
|
1137
|
-
}
|
|
1138
|
-
} catch (error) {
|
|
1139
|
-
console.error(`Failed to refresh workspaces cache: ${error.message}`)
|
|
1140
|
-
return null
|
|
1141
|
-
}
|
|
1142
|
-
}
|
|
1143
|
-
|
|
1144
|
-
async _handleListWorkspaces() {
|
|
1145
|
-
console.error('Listing workspaces via MCP tool')
|
|
1146
|
-
const result = await this._refreshWorkspacesCache()
|
|
1147
|
-
|
|
1148
|
-
if (!result) {
|
|
1149
|
-
// Fallback to client-side tracking
|
|
1150
|
-
const workspaces = Array.from(this.workspaces.entries()).map(([id, meta]) => ({
|
|
1151
|
-
workspace_id: id,
|
|
1152
|
-
type: meta.type,
|
|
1153
|
-
name: meta.name,
|
|
1154
|
-
description: meta.description,
|
|
1155
|
-
active: id === this.activeGraphId,
|
|
1156
|
-
created_at: new Date(meta.created_at).toISOString(),
|
|
1157
|
-
parent_graph_id: meta.parent_graph_id,
|
|
1158
|
-
}))
|
|
1159
|
-
|
|
1160
|
-
return {
|
|
1161
|
-
type: 'text',
|
|
1162
|
-
text: JSON.stringify(
|
|
1163
|
-
{
|
|
1164
|
-
primary_graph_id: this.primaryGraphId,
|
|
1165
|
-
active_workspace: this.activeGraphId,
|
|
1166
|
-
total_workspaces: workspaces.length,
|
|
1167
|
-
workspaces,
|
|
1168
|
-
_note: 'Fallback to client-side tracking due to error',
|
|
1169
|
-
},
|
|
1170
|
-
null,
|
|
1171
|
-
2
|
|
1172
|
-
),
|
|
1173
|
-
}
|
|
1174
|
-
}
|
|
1175
|
-
|
|
1176
|
-
if (result.error) {
|
|
1177
|
-
console.error(`Server error listing workspaces: ${result.message}`)
|
|
1178
|
-
return {
|
|
1179
|
-
type: 'text',
|
|
1180
|
-
text: JSON.stringify(result, null, 2),
|
|
1181
|
-
}
|
|
1182
|
-
}
|
|
1183
|
-
|
|
1184
|
-
if (!result.workspaces) {
|
|
1185
|
-
return {
|
|
1186
|
-
type: 'text',
|
|
1187
|
-
text: JSON.stringify(result, null, 2),
|
|
1188
|
-
}
|
|
1189
|
-
}
|
|
1190
|
-
|
|
1191
|
-
// Validate that the current activeGraphId still exists
|
|
1192
|
-
if (!this.workspaces.has(this.activeGraphId)) {
|
|
1193
|
-
console.error(
|
|
1194
|
-
`Active workspace ${this.activeGraphId} no longer exists on server, switching to primary`
|
|
1195
|
-
)
|
|
1196
|
-
this.activeGraphId = this.primaryGraphId
|
|
1197
|
-
this.metrics.workspaceSwitches++
|
|
1198
|
-
}
|
|
1199
|
-
|
|
1200
|
-
const workspaces = result.workspaces.map((ws) => ({
|
|
1201
|
-
...ws,
|
|
1202
|
-
active: ws.workspace_id === this.activeGraphId,
|
|
1203
|
-
}))
|
|
1204
|
-
|
|
1205
|
-
return {
|
|
1206
|
-
type: 'text',
|
|
1207
|
-
text: JSON.stringify(
|
|
1208
|
-
{
|
|
1209
|
-
primary_graph_id: result.primary_graph_id,
|
|
1210
|
-
active_workspace: this.activeGraphId,
|
|
1211
|
-
total_workspaces: workspaces.length,
|
|
1212
|
-
workspaces,
|
|
1213
|
-
},
|
|
1214
|
-
null,
|
|
1215
|
-
2
|
|
1216
|
-
),
|
|
1217
|
-
}
|
|
1218
|
-
}
|
|
1219
|
-
|
|
1220
|
-
cleanup() {
|
|
1221
|
-
this.connectionPool.closeAll()
|
|
1222
|
-
this.resultCache.clear()
|
|
1223
|
-
}
|
|
82
|
+
export function resolveEndpoint({ baseUrl, graphId, mcpUrl }) {
|
|
83
|
+
if (mcpUrl) return mcpUrl
|
|
84
|
+
if (!graphId) return null
|
|
85
|
+
return `${(baseUrl || 'https://api.robosystems.ai').replace(/\/$/, '')}/v1/graphs/${graphId}/mcp`
|
|
1224
86
|
}
|
|
1225
87
|
|
|
1226
88
|
async function main() {
|
|
1227
|
-
const
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
// Proxy mode (the default): forward stdio JSON-RPC straight to the
|
|
1232
|
-
// platform's native MCP endpoint (Streamable HTTP) instead of running the
|
|
1233
|
-
// legacy REST bridge. ROBOSYSTEMS_MCP_MODE=legacy opts back into the bridge
|
|
1234
|
-
// (needed only against API deployments predating the MCP transport, or for
|
|
1235
|
-
// the bridge's client-side workspace tools); ROBOSYSTEMS_MCP_URL or a
|
|
1236
|
-
// --proxy flag force proxy mode regardless.
|
|
1237
|
-
const mcpUrl = process.env.ROBOSYSTEMS_MCP_URL
|
|
1238
|
-
const legacyMode =
|
|
1239
|
-
!mcpUrl &&
|
|
1240
|
-
!process.argv.includes('--proxy') &&
|
|
1241
|
-
(process.env.ROBOSYSTEMS_MCP_MODE === 'legacy' || process.env.ROBOSYSTEMS_MCP_MODE === 'bridge')
|
|
1242
|
-
|
|
1243
|
-
if (!legacyMode) {
|
|
1244
|
-
if (!mcpUrl && !graphId) {
|
|
1245
|
-
console.error('ROBOSYSTEMS_GRAPH_ID (or a full ROBOSYSTEMS_MCP_URL) is required')
|
|
1246
|
-
console.error('Set one of them in your MCP configuration')
|
|
1247
|
-
process.exit(1)
|
|
1248
|
-
}
|
|
1249
|
-
const url = mcpUrl || `${baseUrl.replace(/\/$/, '')}/v1/graphs/${graphId}/mcp`
|
|
1250
|
-
void checkForUpdate() // fire-and-forget stale-version warning (stderr only)
|
|
1251
|
-
await runProxy({ url, apiKey, version: PACKAGE_VERSION })
|
|
1252
|
-
return
|
|
1253
|
-
}
|
|
1254
|
-
|
|
1255
|
-
if (!apiKey) {
|
|
1256
|
-
console.error('ROBOSYSTEMS_API_KEY environment variable is required')
|
|
1257
|
-
console.error('Please set ROBOSYSTEMS_API_KEY in your MCP configuration')
|
|
1258
|
-
process.exit(1)
|
|
1259
|
-
}
|
|
1260
|
-
|
|
1261
|
-
if (!graphId) {
|
|
1262
|
-
console.error('ROBOSYSTEMS_GRAPH_ID environment variable is required')
|
|
1263
|
-
console.error('Please set ROBOSYSTEMS_GRAPH_ID in your MCP configuration')
|
|
1264
|
-
process.exit(1)
|
|
1265
|
-
}
|
|
1266
|
-
|
|
1267
|
-
console.error(`RoboSystems MCP Client v${PACKAGE_VERSION}`)
|
|
1268
|
-
void checkForUpdate() // fire-and-forget stale-version warning (stderr only)
|
|
1269
|
-
console.error(`Connecting to ${baseUrl}`)
|
|
1270
|
-
console.error(`Primary graph: ${graphId}`)
|
|
1271
|
-
console.error(`API Key: ${apiKey.substring(0, 10)}...`)
|
|
1272
|
-
|
|
1273
|
-
const remoteClient = new RoboSystemsMCPClient(baseUrl, apiKey, graphId)
|
|
1274
|
-
|
|
1275
|
-
// Prefetch the primary graph's tools + instructions BEFORE constructing the
|
|
1276
|
-
// server. The MCP `instructions` field ships in the initialize handshake and
|
|
1277
|
-
// is immutable afterward, so it must be present at construction time (unlike
|
|
1278
|
-
// tools, which are fetched lazily per ListTools request). This also serves as
|
|
1279
|
-
// the initial connection test.
|
|
1280
|
-
let primaryInstructions
|
|
1281
|
-
try {
|
|
1282
|
-
console.error('Testing API connection...')
|
|
1283
|
-
const tools = await remoteClient.getTools()
|
|
1284
|
-
const toolNames = tools.map((t) => t.name)
|
|
1285
|
-
console.error(`Connected successfully. Available tools: ${toolNames.join(', ')}`)
|
|
1286
|
-
primaryInstructions = remoteClient.instructions || undefined
|
|
1287
|
-
if (primaryInstructions) {
|
|
1288
|
-
console.error(
|
|
1289
|
-
`Loaded per-graph instructions for ${graphId} (${primaryInstructions.length} chars)`
|
|
1290
|
-
)
|
|
1291
|
-
}
|
|
1292
|
-
} catch (error) {
|
|
1293
|
-
console.error(`Initial connection test failed: ${error.message}`)
|
|
1294
|
-
// Continue anyway: ListTools retries on demand; instructions stay unset.
|
|
1295
|
-
}
|
|
1296
|
-
|
|
1297
|
-
const serverOptions = {
|
|
1298
|
-
capabilities: {
|
|
1299
|
-
tools: {},
|
|
1300
|
-
},
|
|
1301
|
-
}
|
|
1302
|
-
if (primaryInstructions) {
|
|
1303
|
-
serverOptions.instructions = primaryInstructions
|
|
1304
|
-
}
|
|
1305
|
-
|
|
1306
|
-
const server = new Server(
|
|
1307
|
-
{
|
|
1308
|
-
name: 'robosystems-mcp',
|
|
1309
|
-
version: PACKAGE_VERSION,
|
|
1310
|
-
},
|
|
1311
|
-
serverOptions
|
|
1312
|
-
)
|
|
1313
|
-
|
|
1314
|
-
// List tools handler
|
|
1315
|
-
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
1316
|
-
try {
|
|
1317
|
-
const toolsData = await remoteClient.getTools()
|
|
1318
|
-
const tools = toolsData.map((toolData) => ({
|
|
1319
|
-
name: toolData.name,
|
|
1320
|
-
description: toolData.description,
|
|
1321
|
-
inputSchema: toolData.inputSchema,
|
|
1322
|
-
}))
|
|
1323
|
-
return { tools }
|
|
1324
|
-
} catch (error) {
|
|
1325
|
-
console.error(`Error listing tools: ${error.message}`)
|
|
1326
|
-
return { tools: [] }
|
|
1327
|
-
}
|
|
89
|
+
const url = resolveEndpoint({
|
|
90
|
+
baseUrl: process.env.ROBOSYSTEMS_API_URL,
|
|
91
|
+
graphId: process.env.ROBOSYSTEMS_GRAPH_ID,
|
|
92
|
+
mcpUrl: process.env.ROBOSYSTEMS_MCP_URL,
|
|
1328
93
|
})
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
try {
|
|
1333
|
-
const { name, arguments: args } = request.params
|
|
1334
|
-
const result = await remoteClient.callTool(name, args || {})
|
|
1335
|
-
|
|
1336
|
-
const content = []
|
|
1337
|
-
if (result.type === 'text') {
|
|
1338
|
-
content.push({ type: 'text', text: result.text })
|
|
1339
|
-
} else {
|
|
1340
|
-
content.push({ type: 'text', text: JSON.stringify(result, null, 2) })
|
|
1341
|
-
}
|
|
1342
|
-
|
|
1343
|
-
return { content }
|
|
1344
|
-
} catch (error) {
|
|
1345
|
-
console.error(`Error calling tool ${request.params.name}: ${error.message}`)
|
|
1346
|
-
return {
|
|
1347
|
-
content: [
|
|
1348
|
-
{
|
|
1349
|
-
type: 'text',
|
|
1350
|
-
text: `Error: ${error.message}`,
|
|
1351
|
-
},
|
|
1352
|
-
],
|
|
1353
|
-
}
|
|
1354
|
-
}
|
|
1355
|
-
})
|
|
1356
|
-
|
|
1357
|
-
// Start server (connection + tools already verified during prefetch above)
|
|
1358
|
-
try {
|
|
1359
|
-
const transport = new StdioServerTransport()
|
|
1360
|
-
console.error('Starting MCP stdio transport...')
|
|
1361
|
-
await server.connect(transport)
|
|
1362
|
-
|
|
1363
|
-
console.error('RoboSystems MCP server running')
|
|
1364
|
-
console.error(
|
|
1365
|
-
'Features: Workspace management, connection pooling, smart caching, retry logic, progress tracking'
|
|
1366
|
-
)
|
|
1367
|
-
console.error(`Active workspace: ${remoteClient.activeGraphId}`)
|
|
1368
|
-
|
|
1369
|
-
// Log metrics every 5 minutes
|
|
1370
|
-
metricsInterval = setInterval(() => {
|
|
1371
|
-
const metrics = remoteClient.getMetrics()
|
|
1372
|
-
console.error(`Metrics: ${JSON.stringify(metrics)}`)
|
|
1373
|
-
}, 300000)
|
|
1374
|
-
|
|
1375
|
-
// Keep the process alive
|
|
1376
|
-
await new Promise(() => {})
|
|
1377
|
-
} catch (error) {
|
|
1378
|
-
console.error(`MCP server error: ${error.message}`)
|
|
94
|
+
if (!url) {
|
|
95
|
+
console.error('ROBOSYSTEMS_GRAPH_ID (or a full ROBOSYSTEMS_MCP_URL) is required')
|
|
96
|
+
console.error('Set one of them in your MCP configuration')
|
|
1379
97
|
process.exit(1)
|
|
1380
98
|
}
|
|
1381
|
-
}
|
|
1382
99
|
|
|
1383
|
-
//
|
|
1384
|
-
|
|
1385
|
-
const cleanup = () => {
|
|
1386
|
-
console.error('Shutting down RoboSystems MCP client')
|
|
1387
|
-
if (metricsInterval) {
|
|
1388
|
-
clearInterval(metricsInterval)
|
|
1389
|
-
}
|
|
1390
|
-
process.exit(0)
|
|
100
|
+
void checkForUpdate() // fire-and-forget stale-version warning (stderr only)
|
|
101
|
+
await runProxy({ url, apiKey: process.env.ROBOSYSTEMS_API_KEY, version: PACKAGE_VERSION })
|
|
1391
102
|
}
|
|
1392
103
|
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
// Export for programmatic use
|
|
1397
|
-
export { RoboSystemsMCPClient, SSEConnectionPool, ResultCache }
|
|
1398
|
-
|
|
1399
|
-
// Only run as server if this is the main module
|
|
1400
|
-
// Check if we're being run directly (not imported)
|
|
1401
|
-
// This works with both `node index.js` and `npx` invocations
|
|
104
|
+
// Only run as the proxy if this is the main module (works for `node index.js`
|
|
105
|
+
// and the npx binary names); never under the test runner.
|
|
1402
106
|
const isMainModule =
|
|
1403
107
|
import.meta.url === `file://${process.argv[1]}` ||
|
|
1404
|
-
process.argv[1]?.endsWith('/mcp') ||
|
|
1405
|
-
process.argv[1]?.endsWith('/@robosystems/mcp') ||
|
|
1406
|
-
process.argv[1]?.includes('robosystems-mcp')
|
|
1407
|
-
|
|
1408
|
-
// Don't run in test mode
|
|
108
|
+
process.argv[1]?.endsWith('/mcp') ||
|
|
109
|
+
process.argv[1]?.endsWith('/@robosystems/mcp') ||
|
|
110
|
+
process.argv[1]?.includes('robosystems-mcp')
|
|
1409
111
|
const isTestMode = process.env.VITEST === 'true' || process.env.NODE_ENV === 'test'
|
|
1410
112
|
|
|
1411
113
|
if (isMainModule && !isTestMode) {
|
|
1412
|
-
// Run the server
|
|
1413
114
|
main().catch((error) => {
|
|
1414
115
|
console.error(`Fatal error: ${error.message}`)
|
|
1415
116
|
process.exit(1)
|