@robosystems/mcp 0.1.2 → 0.2.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.
- package/README.md +143 -15
- package/index.js +626 -87
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -8,36 +8,164 @@ MCP (Model Context Protocol) server for accessing RoboSystems Financial Knowledg
|
|
|
8
8
|
npm install -g @robosystems/mcp
|
|
9
9
|
```
|
|
10
10
|
|
|
11
|
-
##
|
|
11
|
+
## Quick Start
|
|
12
12
|
|
|
13
13
|
Add to your Claude Desktop configuration:
|
|
14
14
|
|
|
15
15
|
```json
|
|
16
|
-
|
|
17
|
-
"
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
16
|
+
{
|
|
17
|
+
"mcpServers": {
|
|
18
|
+
"robosystems": {
|
|
19
|
+
"command": "npx",
|
|
20
|
+
"args": ["-y", "@robosystems/mcp"],
|
|
21
|
+
"env": {
|
|
22
|
+
"ROBOSYSTEMS_API_URL": "https://api.robosystems.ai",
|
|
23
|
+
"ROBOSYSTEMS_API_KEY": "your-api-key-here",
|
|
24
|
+
"ROBOSYSTEMS_GRAPH_ID": "your-graph-id"
|
|
25
|
+
}
|
|
26
|
+
}
|
|
23
27
|
}
|
|
24
28
|
}
|
|
25
29
|
```
|
|
26
30
|
|
|
27
31
|
## Environment Variables
|
|
28
32
|
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
33
|
+
| Variable | Description | Default |
|
|
34
|
+
|----------|-------------|---------|
|
|
35
|
+
| `ROBOSYSTEMS_API_URL` | The RoboSystems API endpoint | `http://localhost:8000` |
|
|
36
|
+
| `ROBOSYSTEMS_API_KEY` | Your API key | **Required** |
|
|
37
|
+
| `ROBOSYSTEMS_GRAPH_ID` | The graph database ID to connect to | `default` |
|
|
38
|
+
|
|
39
|
+
## Configuration Details
|
|
40
|
+
|
|
41
|
+
### Connection Pooling
|
|
42
|
+
- **Maximum Connections**: 5 concurrent SSE connections (hardcoded)
|
|
43
|
+
- **Connection TTL**: 30 seconds before automatic cleanup
|
|
44
|
+
- Connections are reused across requests for better performance
|
|
45
|
+
|
|
46
|
+
### Smart Caching
|
|
47
|
+
Cache TTL values per tool type:
|
|
48
|
+
- **`get-graph-schema`**: 1 hour (3600 seconds)
|
|
49
|
+
- **`get-graph-info`**: 5 minutes (300 seconds)
|
|
50
|
+
- **`describe-graph-structure`**: 30 minutes (1800 seconds)
|
|
51
|
+
- **Other tools**: 5 minutes (300 seconds) default
|
|
52
|
+
|
|
53
|
+
### Timeouts
|
|
54
|
+
- **SSE Timeout**: 5 minutes for streaming operations
|
|
55
|
+
- **Metrics Logging**: Every 5 minutes
|
|
32
56
|
|
|
33
57
|
## Available Tools
|
|
34
58
|
|
|
35
|
-
|
|
36
|
-
-
|
|
37
|
-
-
|
|
59
|
+
### Core Query Tools
|
|
60
|
+
- **`read-graph-cypher`**: Execute read-only Cypher queries on the graph database
|
|
61
|
+
- Supports streaming for large result sets
|
|
62
|
+
- Automatic result aggregation
|
|
63
|
+
- Progress tracking for complex queries
|
|
64
|
+
|
|
65
|
+
### Schema & Information Tools
|
|
66
|
+
- **`get-graph-schema`**: Retrieve the complete database schema
|
|
67
|
+
- Returns node types and relationship definitions
|
|
68
|
+
|
|
69
|
+
- **`get-graph-info`**: Get basic information about the graph
|
|
70
|
+
- Includes node counts, relationship counts, and metadata
|
|
71
|
+
|
|
72
|
+
- **`describe-graph-structure`**: Get natural language description of the graph
|
|
73
|
+
- AI-friendly format for better understanding
|
|
74
|
+
|
|
75
|
+
## Features
|
|
76
|
+
|
|
77
|
+
### Multiple Response Formats
|
|
78
|
+
The MCP server automatically handles:
|
|
79
|
+
- **JSON**: Standard synchronous responses
|
|
80
|
+
- **SSE (Server-Sent Events)**: Real-time streaming for long operations
|
|
81
|
+
- **NDJSON**: Newline-delimited JSON for batch processing
|
|
82
|
+
- **Queued**: Queued operations with status polling
|
|
83
|
+
|
|
84
|
+
### Performance Optimizations
|
|
85
|
+
- **Connection Pooling**: Reuses SSE connections for better performance
|
|
86
|
+
- **Smart Caching**: Frequently accessed data (like schemas) cached automatically
|
|
87
|
+
- **Retry Logic**: Automatic retry with exponential backoff for network issues
|
|
88
|
+
- **Progress Tracking**: Real-time updates for long-running operations
|
|
89
|
+
|
|
90
|
+
## Integration Examples
|
|
91
|
+
|
|
92
|
+
### Claude Desktop
|
|
93
|
+
```json
|
|
94
|
+
{
|
|
95
|
+
"mcpServers": {
|
|
96
|
+
"robosystems": {
|
|
97
|
+
"command": "npx",
|
|
98
|
+
"args": ["-y", "@robosystems/mcp"],
|
|
99
|
+
"env": {
|
|
100
|
+
"ROBOSYSTEMS_API_URL": "https://api.robosystems.ai",
|
|
101
|
+
"ROBOSYSTEMS_API_KEY": "your-api-key-here",
|
|
102
|
+
"ROBOSYSTEMS_GRAPH_ID": "your-graph-id"
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### Local Development
|
|
110
|
+
```json
|
|
111
|
+
{
|
|
112
|
+
"mcpServers": {
|
|
113
|
+
"robosystems-local": {
|
|
114
|
+
"command": "npx",
|
|
115
|
+
"args": ["-y", "@robosystems/mcp"],
|
|
116
|
+
"env": {
|
|
117
|
+
"ROBOSYSTEMS_API_URL": "http://localhost:8000",
|
|
118
|
+
"ROBOSYSTEMS_API_KEY": "your-api-dev-key-here",
|
|
119
|
+
"ROBOSYSTEMS_GRAPH_ID": "your-dev-graph-id"
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## Usage Examples
|
|
127
|
+
|
|
128
|
+
Once configured, you can ask Claude to:
|
|
129
|
+
|
|
130
|
+
- **Query the graph**: "Show me all companies in the technology sector"
|
|
131
|
+
- **Get schema information**: "What types of data are available in this graph?"
|
|
132
|
+
- **Explore relationships**: "How are companies connected to their financial reports?"
|
|
133
|
+
- **Run complex analyses**: "Find companies with revenue growth over 20% in the last year"
|
|
134
|
+
|
|
135
|
+
## Troubleshooting
|
|
136
|
+
|
|
137
|
+
### Common Issues
|
|
138
|
+
|
|
139
|
+
**Connection Errors**
|
|
140
|
+
- Verify your API key is correct and has proper permissions
|
|
141
|
+
- Check that the API URL is reachable
|
|
142
|
+
- Ensure your graph ID exists
|
|
143
|
+
|
|
144
|
+
**Slow Responses**
|
|
145
|
+
- Large queries may take time to complete
|
|
146
|
+
- Progress updates will show in the logs
|
|
147
|
+
- Consider breaking complex queries into smaller parts
|
|
148
|
+
|
|
149
|
+
**Cache Issues**
|
|
150
|
+
- Schema data is cached for better performance
|
|
151
|
+
- Restart the MCP server to clear caches if needed
|
|
152
|
+
|
|
153
|
+
### Getting Help
|
|
154
|
+
|
|
155
|
+
For support with the RoboSystems platform:
|
|
156
|
+
- Visit our documentation at [api.robosystems.ai](https://api.robosystems.ai)
|
|
157
|
+
- Contact our support team
|
|
158
|
+
- Check the API status page
|
|
159
|
+
|
|
160
|
+
## Security
|
|
161
|
+
|
|
162
|
+
- API keys are transmitted securely via headers
|
|
163
|
+
- All queries are read-only by default
|
|
164
|
+
- No sensitive data is cached locally
|
|
165
|
+
- Connections are automatically cleaned up
|
|
38
166
|
|
|
39
167
|
## License
|
|
40
168
|
|
|
41
169
|
This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details.
|
|
42
170
|
|
|
43
|
-
MIT ©
|
|
171
|
+
MIT © 2025 Harbinger FinLab
|
package/index.js
CHANGED
|
@@ -1,9 +1,18 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
|
-
* RoboSystems MCP Client
|
|
4
|
+
* RoboSystems MCP Client
|
|
5
5
|
*
|
|
6
6
|
* This client connects to the RoboSystems HTTP API and exposes it as MCP tools.
|
|
7
|
+
* It handles multiple response formats (JSON, SSE, NDJSON) and provides a
|
|
8
|
+
* unified interface to AI agents like Claude Desktop.
|
|
9
|
+
*
|
|
10
|
+
* Features:
|
|
11
|
+
* - SSE connection pooling for performance
|
|
12
|
+
* - Smart caching for frequently accessed data
|
|
13
|
+
* - Retry logic for network resilience
|
|
14
|
+
* - Progress tracking for long operations
|
|
15
|
+
* - Clean resource management
|
|
7
16
|
*/
|
|
8
17
|
|
|
9
18
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
@@ -12,7 +21,153 @@ import {
|
|
|
12
21
|
CallToolRequestSchema,
|
|
13
22
|
ListToolsRequestSchema,
|
|
14
23
|
} from '@modelcontextprotocol/sdk/types.js'
|
|
24
|
+
import { EventSource } from 'eventsource'
|
|
25
|
+
import { readFileSync } from 'fs'
|
|
26
|
+
import { fileURLToPath } from 'url'
|
|
27
|
+
import { dirname, join } from 'path'
|
|
28
|
+
import { createHash } from 'crypto'
|
|
15
29
|
|
|
30
|
+
// Get package version dynamically
|
|
31
|
+
const __filename = fileURLToPath(import.meta.url)
|
|
32
|
+
const __dirname = dirname(__filename)
|
|
33
|
+
const packageJson = JSON.parse(readFileSync(join(__dirname, 'package.json'), 'utf8'))
|
|
34
|
+
const PACKAGE_VERSION = packageJson.version
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Simple SSE Connection Pool
|
|
38
|
+
* Reuses connections for better performance
|
|
39
|
+
*/
|
|
40
|
+
class SSEConnectionPool {
|
|
41
|
+
constructor(maxConnections = 5) {
|
|
42
|
+
this.connections = new Map()
|
|
43
|
+
this.maxConnections = maxConnections
|
|
44
|
+
this.connectionTTL = 30000 // 30 seconds
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
getConnection(operationId, url, headers) {
|
|
48
|
+
// Check for existing connection
|
|
49
|
+
if (this.connections.has(operationId)) {
|
|
50
|
+
const conn = this.connections.get(operationId)
|
|
51
|
+
conn.lastUsed = Date.now()
|
|
52
|
+
return conn.eventSource
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Clean up old connections if at limit
|
|
56
|
+
if (this.connections.size >= this.maxConnections) {
|
|
57
|
+
this.evictOldest()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Create new connection
|
|
61
|
+
const eventSource = new EventSource(url, { headers })
|
|
62
|
+
this.connections.set(operationId, {
|
|
63
|
+
eventSource,
|
|
64
|
+
createdAt: Date.now(),
|
|
65
|
+
lastUsed: Date.now(),
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
// Auto-cleanup after TTL
|
|
69
|
+
setTimeout(() => {
|
|
70
|
+
this.closeConnection(operationId)
|
|
71
|
+
}, this.connectionTTL)
|
|
72
|
+
|
|
73
|
+
return eventSource
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
evictOldest() {
|
|
77
|
+
let oldest = null
|
|
78
|
+
let oldestTime = Date.now()
|
|
79
|
+
|
|
80
|
+
for (const [id, conn] of this.connections) {
|
|
81
|
+
if (conn.lastUsed < oldestTime) {
|
|
82
|
+
oldest = id
|
|
83
|
+
oldestTime = conn.lastUsed
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (oldest) {
|
|
88
|
+
this.closeConnection(oldest)
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
closeConnection(operationId) {
|
|
93
|
+
const conn = this.connections.get(operationId)
|
|
94
|
+
if (conn) {
|
|
95
|
+
conn.eventSource.close()
|
|
96
|
+
this.connections.delete(operationId)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
closeAll() {
|
|
101
|
+
for (const [id] of this.connections) {
|
|
102
|
+
this.closeConnection(id)
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* Simple Result Cache
|
|
109
|
+
* Caches frequently accessed data like schemas
|
|
110
|
+
*/
|
|
111
|
+
class ResultCache {
|
|
112
|
+
constructor() {
|
|
113
|
+
this.cache = new Map()
|
|
114
|
+
this.cacheExpiry = new Map()
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
generateKey(tool, args) {
|
|
118
|
+
// Sort object keys to ensure deterministic cache keys
|
|
119
|
+
const sortedArgs = this._sortObjectKeys(args)
|
|
120
|
+
const data = JSON.stringify({ tool, args: sortedArgs }, null, 0)
|
|
121
|
+
return createHash('sha256').update(data).digest('hex')
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
_sortObjectKeys(obj) {
|
|
125
|
+
if (obj === null || typeof obj !== 'object') {
|
|
126
|
+
return obj
|
|
127
|
+
}
|
|
128
|
+
if (Array.isArray(obj)) {
|
|
129
|
+
return obj.map(item => this._sortObjectKeys(item))
|
|
130
|
+
}
|
|
131
|
+
const sortedObj = {}
|
|
132
|
+
Object.keys(obj).sort().forEach(key => {
|
|
133
|
+
sortedObj[key] = this._sortObjectKeys(obj[key])
|
|
134
|
+
})
|
|
135
|
+
return sortedObj
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
get(tool, args) {
|
|
139
|
+
const key = this.generateKey(tool, args)
|
|
140
|
+
|
|
141
|
+
if (this.cache.has(key)) {
|
|
142
|
+
const expiry = this.cacheExpiry.get(key)
|
|
143
|
+
if (expiry > Date.now()) {
|
|
144
|
+
return this.cache.get(key)
|
|
145
|
+
} else {
|
|
146
|
+
// Expired - remove from cache
|
|
147
|
+
this.cache.delete(key)
|
|
148
|
+
this.cacheExpiry.delete(key)
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
return null
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
set(tool, args, result, ttlSeconds = 300) {
|
|
156
|
+
const key = this.generateKey(tool, args)
|
|
157
|
+
this.cache.set(key, result)
|
|
158
|
+
this.cacheExpiry.set(key, Date.now() + (ttlSeconds * 1000))
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
clear() {
|
|
162
|
+
this.cache.clear()
|
|
163
|
+
this.cacheExpiry.clear()
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* RoboSystems MCP Client
|
|
169
|
+
* Handles communication with the RoboSystems API
|
|
170
|
+
*/
|
|
16
171
|
class RoboSystemsMCPClient {
|
|
17
172
|
constructor(baseUrl, apiKey, graphId) {
|
|
18
173
|
this.baseUrl = baseUrl.replace(/\/$/, '') // Remove trailing slash
|
|
@@ -21,6 +176,21 @@ class RoboSystemsMCPClient {
|
|
|
21
176
|
this.headers = {
|
|
22
177
|
'X-API-Key': apiKey,
|
|
23
178
|
'Content-Type': 'application/json',
|
|
179
|
+
'User-Agent': `robosystems-mcp/${PACKAGE_VERSION}`,
|
|
180
|
+
'X-MCP-Client': PACKAGE_VERSION,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// Initialize components
|
|
184
|
+
this.connectionPool = new SSEConnectionPool()
|
|
185
|
+
this.resultCache = new ResultCache()
|
|
186
|
+
this.maxRetries = 3
|
|
187
|
+
this.baseRetryDelay = 1000
|
|
188
|
+
|
|
189
|
+
// Simple metrics
|
|
190
|
+
this.metrics = {
|
|
191
|
+
totalRequests: 0,
|
|
192
|
+
cacheHits: 0,
|
|
193
|
+
errors: 0,
|
|
24
194
|
}
|
|
25
195
|
}
|
|
26
196
|
|
|
@@ -46,31 +216,409 @@ class RoboSystemsMCPClient {
|
|
|
46
216
|
}
|
|
47
217
|
|
|
48
218
|
async callTool(name, args = {}) {
|
|
219
|
+
this.metrics.totalRequests++
|
|
220
|
+
|
|
221
|
+
// Check cache first for cacheable tools
|
|
222
|
+
if (this.isCacheable(name)) {
|
|
223
|
+
const cached = this.resultCache.get(name, args)
|
|
224
|
+
if (cached) {
|
|
225
|
+
this.metrics.cacheHits++
|
|
226
|
+
return cached
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
// Execute with simple retry logic
|
|
231
|
+
return this.executeWithRetry(() => this._callToolInternal(name, args))
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
async _callToolInternal(name, args) {
|
|
49
235
|
try {
|
|
236
|
+
const headers = {
|
|
237
|
+
...this.headers,
|
|
238
|
+
'Accept': 'text/event-stream, application/x-ndjson, application/json',
|
|
239
|
+
}
|
|
240
|
+
|
|
50
241
|
const response = await fetch(
|
|
51
242
|
`${this.baseUrl}/v1/${this.graphId}/mcp/call-tool`,
|
|
52
243
|
{
|
|
53
244
|
method: 'POST',
|
|
54
|
-
headers
|
|
245
|
+
headers,
|
|
55
246
|
body: JSON.stringify({ name, arguments: args }),
|
|
56
247
|
}
|
|
57
248
|
)
|
|
58
249
|
|
|
59
|
-
|
|
60
|
-
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
61
|
-
}
|
|
250
|
+
const contentType = response.headers.get('content-type') || ''
|
|
62
251
|
|
|
63
|
-
|
|
64
|
-
|
|
252
|
+
let result
|
|
253
|
+
if (contentType.includes('text/event-stream')) {
|
|
254
|
+
result = await this.handleSSEResponse(response, name)
|
|
255
|
+
} else if (contentType.includes('application/x-ndjson')) {
|
|
256
|
+
result = await this.handleNDJSONResponse(response, name)
|
|
257
|
+
} else if (response.status === 202) {
|
|
258
|
+
result = await this.handleQueuedResponse(response, name)
|
|
259
|
+
} else {
|
|
260
|
+
if (!response.ok) {
|
|
261
|
+
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
|
262
|
+
}
|
|
263
|
+
const data = await response.json()
|
|
264
|
+
// The API returns { result: { type: 'text', text: JSON.stringify(actualData) } }
|
|
265
|
+
if (data.result && data.result.type === 'text' && data.result.text) {
|
|
266
|
+
// Parse the text field if it contains JSON data
|
|
267
|
+
try {
|
|
268
|
+
const parsedText = JSON.parse(data.result.text)
|
|
269
|
+
result = { type: 'text', text: JSON.stringify(parsedText, null, 2) }
|
|
270
|
+
} catch (e) {
|
|
271
|
+
// If it's not JSON, just use it as-is
|
|
272
|
+
result = data.result
|
|
273
|
+
}
|
|
274
|
+
} else {
|
|
275
|
+
result = data.result || { type: 'text', text: 'No result' }
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// Cache the result if appropriate
|
|
280
|
+
if (this.isCacheable(name)) {
|
|
281
|
+
const ttl = this.getCacheTTL(name)
|
|
282
|
+
this.resultCache.set(name, args, result, ttl)
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
return result
|
|
65
286
|
} catch (error) {
|
|
287
|
+
this.metrics.errors++
|
|
66
288
|
console.error(`Failed to call tool ${name}: ${error.message}`)
|
|
67
|
-
|
|
289
|
+
throw error
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
async executeWithRetry(fn) {
|
|
294
|
+
let lastError = null
|
|
295
|
+
|
|
296
|
+
for (let attempt = 0; attempt < this.maxRetries; attempt++) {
|
|
297
|
+
try {
|
|
298
|
+
return await fn()
|
|
299
|
+
} catch (error) {
|
|
300
|
+
lastError = error
|
|
301
|
+
|
|
302
|
+
// Don't retry on auth errors or client errors
|
|
303
|
+
if (error.message.includes('401') ||
|
|
304
|
+
error.message.includes('403') ||
|
|
305
|
+
error.message.includes('400')) {
|
|
306
|
+
break
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if (attempt < this.maxRetries - 1) {
|
|
310
|
+
const delay = this.baseRetryDelay * Math.pow(2, attempt)
|
|
311
|
+
await new Promise(resolve => setTimeout(resolve, delay))
|
|
312
|
+
}
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
return {
|
|
317
|
+
type: 'text',
|
|
318
|
+
text: `Error after ${this.maxRetries} attempts: ${lastError?.message || 'Unknown error'}`
|
|
68
319
|
}
|
|
69
320
|
}
|
|
321
|
+
|
|
322
|
+
async handleSSEResponse(response, toolName) {
|
|
323
|
+
return new Promise((resolve, reject) => {
|
|
324
|
+
const events = []
|
|
325
|
+
const operationId = response.headers.get('x-operation-id') || `sse-${Date.now()}`
|
|
326
|
+
|
|
327
|
+
const eventSource = this.connectionPool.getConnection(
|
|
328
|
+
operationId,
|
|
329
|
+
response.url,
|
|
330
|
+
this.headers
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
const timeout = setTimeout(() => {
|
|
334
|
+
this.connectionPool.closeConnection(operationId)
|
|
335
|
+
reject(new Error('SSE timeout after 5 minutes'))
|
|
336
|
+
}, 300000)
|
|
337
|
+
|
|
338
|
+
eventSource.onmessage = (event) => {
|
|
339
|
+
try {
|
|
340
|
+
const data = JSON.parse(event.data)
|
|
341
|
+
events.push({ event: event.type || 'message', data })
|
|
342
|
+
} catch (e) {
|
|
343
|
+
console.error('Failed to parse SSE event:', e)
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
eventSource.addEventListener('complete', () => {
|
|
348
|
+
clearTimeout(timeout)
|
|
349
|
+
const result = this.aggregateStreamedResults(events, toolName)
|
|
350
|
+
resolve(result)
|
|
351
|
+
})
|
|
352
|
+
|
|
353
|
+
// Listen for the actual server event types
|
|
354
|
+
eventSource.addEventListener('operation_completed', () => {
|
|
355
|
+
clearTimeout(timeout)
|
|
356
|
+
this.connectionPool.closeConnection(operationId)
|
|
357
|
+
const result = this.aggregateStreamedResults(events, toolName)
|
|
358
|
+
resolve(result)
|
|
359
|
+
})
|
|
360
|
+
|
|
361
|
+
eventSource.addEventListener('operation_error', (event) => {
|
|
362
|
+
clearTimeout(timeout)
|
|
363
|
+
this.connectionPool.closeConnection(operationId)
|
|
364
|
+
try {
|
|
365
|
+
const data = JSON.parse(event.data)
|
|
366
|
+
reject(new Error(data.error || data.message || 'Operation failed'))
|
|
367
|
+
} catch (e) {
|
|
368
|
+
reject(new Error('Operation failed'))
|
|
369
|
+
}
|
|
370
|
+
})
|
|
371
|
+
|
|
372
|
+
eventSource.addEventListener('error', () => {
|
|
373
|
+
clearTimeout(timeout)
|
|
374
|
+
this.connectionPool.closeConnection(operationId)
|
|
375
|
+
|
|
376
|
+
if (events.length > 0) {
|
|
377
|
+
const result = this.aggregateStreamedResults(events, toolName)
|
|
378
|
+
resolve(result)
|
|
379
|
+
} else {
|
|
380
|
+
reject(new Error('SSE connection failed'))
|
|
381
|
+
}
|
|
382
|
+
})
|
|
383
|
+
|
|
384
|
+
// Handle specific event types
|
|
385
|
+
eventSource.addEventListener('query_chunk', (event) => {
|
|
386
|
+
try {
|
|
387
|
+
const data = JSON.parse(event.data)
|
|
388
|
+
events.push({ event: 'query_chunk', data })
|
|
389
|
+
} catch (e) {
|
|
390
|
+
console.error('Failed to parse query chunk:', e)
|
|
391
|
+
}
|
|
392
|
+
})
|
|
393
|
+
|
|
394
|
+
eventSource.addEventListener('progress', (event) => {
|
|
395
|
+
try {
|
|
396
|
+
const data = JSON.parse(event.data)
|
|
397
|
+
console.error(`Progress: ${data.message || 'Processing...'}`)
|
|
398
|
+
} catch (e) {
|
|
399
|
+
// Ignore progress parsing errors
|
|
400
|
+
}
|
|
401
|
+
})
|
|
402
|
+
|
|
403
|
+
// Also listen for operation_progress events
|
|
404
|
+
eventSource.addEventListener('operation_progress', (event) => {
|
|
405
|
+
try {
|
|
406
|
+
const data = JSON.parse(event.data)
|
|
407
|
+
const progress = data.percentage ? `${data.percentage}% - ` : ''
|
|
408
|
+
console.error(`Progress: ${progress}${data.message || 'Processing...'}`)
|
|
409
|
+
} catch (e) {
|
|
410
|
+
// Ignore progress parsing errors
|
|
411
|
+
}
|
|
412
|
+
})
|
|
413
|
+
})
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
async handleNDJSONResponse(response) {
|
|
417
|
+
const events = []
|
|
418
|
+
const reader = response.body.getReader()
|
|
419
|
+
const decoder = new TextDecoder()
|
|
420
|
+
let buffer = ''
|
|
421
|
+
|
|
422
|
+
try {
|
|
423
|
+
while (true) {
|
|
424
|
+
const { done, value } = await reader.read()
|
|
425
|
+
if (done) break
|
|
426
|
+
|
|
427
|
+
buffer += decoder.decode(value, { stream: true })
|
|
428
|
+
const lines = buffer.split('\n')
|
|
429
|
+
buffer = lines.pop() || ''
|
|
430
|
+
|
|
431
|
+
for (const line of lines) {
|
|
432
|
+
if (line.trim()) {
|
|
433
|
+
try {
|
|
434
|
+
const event = JSON.parse(line)
|
|
435
|
+
events.push(event)
|
|
436
|
+
} catch (e) {
|
|
437
|
+
console.error('Failed to parse NDJSON line:', e)
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
if (buffer.trim()) {
|
|
444
|
+
try {
|
|
445
|
+
const event = JSON.parse(buffer)
|
|
446
|
+
events.push(event)
|
|
447
|
+
} catch (e) {
|
|
448
|
+
console.error('Failed to parse final NDJSON line:', e)
|
|
449
|
+
}
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
return this.aggregateStreamedResults(events, 'ndjson')
|
|
453
|
+
} catch (error) {
|
|
454
|
+
console.error('NDJSON parsing error:', error)
|
|
455
|
+
return { type: 'text', text: `Error parsing streaming response: ${error.message}` }
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
async handleQueuedResponse(response) {
|
|
460
|
+
const data = await response.json()
|
|
461
|
+
|
|
462
|
+
if (data.queued && data.queue_id) {
|
|
463
|
+
console.error(`Query queued with ID: ${data.queue_id}`)
|
|
464
|
+
|
|
465
|
+
const statusUrl = data.status_url ||
|
|
466
|
+
`${this.baseUrl}/v1/${this.graphId}/query/${data.queue_id}/status`
|
|
467
|
+
const resultUrl = data.result_url ||
|
|
468
|
+
`${this.baseUrl}/v1/${this.graphId}/query/${data.queue_id}/result`
|
|
469
|
+
|
|
470
|
+
// Simple polling with exponential backoff
|
|
471
|
+
let attempts = 0
|
|
472
|
+
let delay = 1000
|
|
473
|
+
const maxAttempts = 30
|
|
474
|
+
|
|
475
|
+
while (attempts < maxAttempts) {
|
|
476
|
+
await new Promise(resolve => setTimeout(resolve, delay))
|
|
477
|
+
|
|
478
|
+
try {
|
|
479
|
+
const statusResponse = await fetch(statusUrl, { headers: this.headers })
|
|
480
|
+
|
|
481
|
+
if (statusResponse.ok) {
|
|
482
|
+
const status = await statusResponse.json()
|
|
483
|
+
|
|
484
|
+
if (status.status === 'completed') {
|
|
485
|
+
const resultResponse = await fetch(resultUrl, { headers: this.headers })
|
|
486
|
+
if (resultResponse.ok) {
|
|
487
|
+
const result = await resultResponse.json()
|
|
488
|
+
return { type: 'text', text: JSON.stringify(result, null, 2) }
|
|
489
|
+
}
|
|
490
|
+
} else if (status.status === 'failed') {
|
|
491
|
+
return { type: 'text', text: `Query failed: ${status.error || 'Unknown error'}` }
|
|
492
|
+
} else if (status.status === 'cancelled') {
|
|
493
|
+
return { type: 'text', text: 'Query was cancelled' }
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
} catch (e) {
|
|
497
|
+
console.error('Polling error:', e)
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
attempts++
|
|
501
|
+
delay = Math.min(delay * 1.5, 10000)
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
return { type: 'text', text: 'Query timed out waiting for result' }
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
return { type: 'text', text: JSON.stringify(data, null, 2) }
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
aggregateStreamedResults(events) {
|
|
511
|
+
// Check for errors
|
|
512
|
+
const errorEvent = events.find(e => e.event === 'error' || e.event === 'operation_error')
|
|
513
|
+
if (errorEvent) {
|
|
514
|
+
return {
|
|
515
|
+
type: 'text',
|
|
516
|
+
text: `Error: ${errorEvent.data.error || errorEvent.data.message || 'Tool execution failed'}`,
|
|
517
|
+
}
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
// Check for non-streaming query results first (fallback path)
|
|
521
|
+
const queryResult = events.find(e => e.event === 'query_result')
|
|
522
|
+
if (queryResult && queryResult.data) {
|
|
523
|
+
const result = queryResult.data.result
|
|
524
|
+
if (result) {
|
|
525
|
+
return {
|
|
526
|
+
type: 'text',
|
|
527
|
+
text: typeof result === 'string' ? result : JSON.stringify(result, null, 2)
|
|
528
|
+
}
|
|
529
|
+
}
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// Aggregate query chunks - check for both possible event names
|
|
533
|
+
const queryChunks = events.filter(e =>
|
|
534
|
+
e.event === 'query_chunk' ||
|
|
535
|
+
e.event === 'data_chunk'
|
|
536
|
+
)
|
|
537
|
+
if (queryChunks.length > 0) {
|
|
538
|
+
const allRows = []
|
|
539
|
+
let columns = null
|
|
540
|
+
|
|
541
|
+
for (const chunk of queryChunks) {
|
|
542
|
+
if (!columns && chunk.data.columns) {
|
|
543
|
+
columns = chunk.data.columns
|
|
544
|
+
}
|
|
545
|
+
if (chunk.data.data) {
|
|
546
|
+
allRows.push(...chunk.data.data)
|
|
547
|
+
}
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
// Only return data if we actually got some
|
|
551
|
+
if (allRows.length > 0 || columns) {
|
|
552
|
+
return {
|
|
553
|
+
type: 'text',
|
|
554
|
+
text: JSON.stringify({
|
|
555
|
+
columns: columns || [],
|
|
556
|
+
data: allRows,
|
|
557
|
+
row_count: allRows.length,
|
|
558
|
+
}, null, 2),
|
|
559
|
+
}
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// Look for completion event - match what server actually sends
|
|
564
|
+
const resultEvent = events.find(e =>
|
|
565
|
+
e.event === 'operation_completed' ||
|
|
566
|
+
e.event === 'complete' ||
|
|
567
|
+
e.event === 'query_complete' ||
|
|
568
|
+
e.event === 'result' ||
|
|
569
|
+
e.event === 'query_result'
|
|
570
|
+
)
|
|
571
|
+
if (resultEvent) {
|
|
572
|
+
const result = resultEvent.data.result || resultEvent.data
|
|
573
|
+
return {
|
|
574
|
+
type: 'text',
|
|
575
|
+
text: typeof result === 'string' ? result : JSON.stringify(result, null, 2)
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
// Default: return all events
|
|
580
|
+
return { type: 'text', text: JSON.stringify(events, null, 2) }
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
isCacheable(toolName) {
|
|
584
|
+
const cacheableTools = [
|
|
585
|
+
'get-graph-schema',
|
|
586
|
+
'get-graph-info',
|
|
587
|
+
'describe-graph-structure',
|
|
588
|
+
]
|
|
589
|
+
return cacheableTools.includes(toolName)
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
getCacheTTL(toolName) {
|
|
593
|
+
const ttlMap = {
|
|
594
|
+
'get-graph-schema': 3600, // 1 hour
|
|
595
|
+
'get-graph-info': 300, // 5 minutes
|
|
596
|
+
'describe-graph-structure': 1800, // 30 minutes
|
|
597
|
+
}
|
|
598
|
+
return ttlMap[toolName] || 300
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
getMetrics() {
|
|
602
|
+
const cacheHitRate = this.metrics.totalRequests > 0
|
|
603
|
+
? (this.metrics.cacheHits / this.metrics.totalRequests * 100).toFixed(1) + '%'
|
|
604
|
+
: '0%'
|
|
605
|
+
|
|
606
|
+
return {
|
|
607
|
+
totalRequests: this.metrics.totalRequests,
|
|
608
|
+
cacheHits: this.metrics.cacheHits,
|
|
609
|
+
cacheHitRate,
|
|
610
|
+
errors: this.metrics.errors,
|
|
611
|
+
activeConnections: this.connectionPool.connections.size,
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
cleanup() {
|
|
616
|
+
this.connectionPool.closeAll()
|
|
617
|
+
this.resultCache.clear()
|
|
618
|
+
}
|
|
70
619
|
}
|
|
71
620
|
|
|
72
621
|
async function main() {
|
|
73
|
-
// Get configuration from environment variables
|
|
74
622
|
const baseUrl = process.env.ROBOSYSTEMS_API_URL || 'http://localhost:8000'
|
|
75
623
|
const apiKey = process.env.ROBOSYSTEMS_API_KEY
|
|
76
624
|
const graphId = process.env.ROBOSYSTEMS_GRAPH_ID || 'default'
|
|
@@ -80,18 +628,15 @@ async function main() {
|
|
|
80
628
|
process.exit(1)
|
|
81
629
|
}
|
|
82
630
|
|
|
83
|
-
console.error(
|
|
84
|
-
|
|
85
|
-
)
|
|
631
|
+
console.error(`RoboSystems MCP Client v${PACKAGE_VERSION}`)
|
|
632
|
+
console.error(`Connecting to ${baseUrl} for graph ${graphId}`)
|
|
86
633
|
|
|
87
|
-
// Initialize the remote client
|
|
88
634
|
const remoteClient = new RoboSystemsMCPClient(baseUrl, apiKey, graphId)
|
|
89
635
|
|
|
90
|
-
// Create local MCP server that bridges to the remote service
|
|
91
636
|
const server = new Server(
|
|
92
637
|
{
|
|
93
638
|
name: 'robosystems-mcp',
|
|
94
|
-
version:
|
|
639
|
+
version: PACKAGE_VERSION,
|
|
95
640
|
},
|
|
96
641
|
{
|
|
97
642
|
capabilities: {
|
|
@@ -101,103 +646,97 @@ async function main() {
|
|
|
101
646
|
)
|
|
102
647
|
|
|
103
648
|
// List tools handler
|
|
104
|
-
server.setRequestHandler(
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
return { tools }
|
|
118
|
-
} catch (error) {
|
|
119
|
-
console.error(`Error listing tools: ${error.message}`)
|
|
120
|
-
return { tools: [] }
|
|
121
|
-
}
|
|
649
|
+
server.setRequestHandler(ListToolsRequestSchema, async () => {
|
|
650
|
+
try {
|
|
651
|
+
const toolsData = await remoteClient.getTools()
|
|
652
|
+
const tools = toolsData.map((toolData) => ({
|
|
653
|
+
name: toolData.name,
|
|
654
|
+
description: toolData.description,
|
|
655
|
+
inputSchema: toolData.inputSchema,
|
|
656
|
+
}))
|
|
657
|
+
return { tools }
|
|
658
|
+
} catch (error) {
|
|
659
|
+
console.error(`Error listing tools: ${error.message}`)
|
|
660
|
+
return { tools: [] }
|
|
122
661
|
}
|
|
123
|
-
)
|
|
662
|
+
})
|
|
124
663
|
|
|
125
664
|
// Call tool handler
|
|
126
|
-
server.setRequestHandler(
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
const { name, arguments: args } = request.params
|
|
131
|
-
|
|
132
|
-
const result = await remoteClient.callTool(name, args || {})
|
|
133
|
-
|
|
134
|
-
// Convert result to MCP content
|
|
135
|
-
const content = []
|
|
136
|
-
if (result.type === 'text') {
|
|
137
|
-
content.push({
|
|
138
|
-
type: 'text',
|
|
139
|
-
text: result.text,
|
|
140
|
-
})
|
|
141
|
-
} else {
|
|
142
|
-
content.push({
|
|
143
|
-
type: 'text',
|
|
144
|
-
text: JSON.stringify(result, null, 2),
|
|
145
|
-
})
|
|
146
|
-
}
|
|
665
|
+
server.setRequestHandler(CallToolRequestSchema, async (request) => {
|
|
666
|
+
try {
|
|
667
|
+
const { name, arguments: args } = request.params
|
|
668
|
+
const result = await remoteClient.callTool(name, args || {})
|
|
147
669
|
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
)
|
|
670
|
+
const content = []
|
|
671
|
+
if (result.type === 'text') {
|
|
672
|
+
content.push({ type: 'text', text: result.text })
|
|
673
|
+
} else {
|
|
674
|
+
content.push({ type: 'text', text: JSON.stringify(result, null, 2) })
|
|
675
|
+
}
|
|
153
676
|
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
}
|
|
677
|
+
return { content }
|
|
678
|
+
} catch (error) {
|
|
679
|
+
console.error(`Error calling tool ${request.params.name}: ${error.message}`)
|
|
680
|
+
return {
|
|
681
|
+
content: [{
|
|
682
|
+
type: 'text',
|
|
683
|
+
text: `Error: ${error.message}`,
|
|
684
|
+
}],
|
|
162
685
|
}
|
|
163
686
|
}
|
|
164
|
-
)
|
|
687
|
+
})
|
|
165
688
|
|
|
166
689
|
// Test connection and start server
|
|
167
690
|
try {
|
|
168
691
|
const tools = await remoteClient.getTools()
|
|
169
692
|
const toolNames = tools.map((t) => t.name)
|
|
170
|
-
console.error(
|
|
171
|
-
`Connected successfully. Available tools: ${toolNames.join(', ')}`
|
|
172
|
-
)
|
|
693
|
+
console.error(`Connected successfully. Available tools: ${toolNames.join(', ')}`)
|
|
173
694
|
|
|
174
|
-
// Start the MCP server
|
|
175
695
|
const transport = new StdioServerTransport()
|
|
176
696
|
await server.connect(transport)
|
|
177
697
|
|
|
178
|
-
console.error('RoboSystems MCP server running
|
|
698
|
+
console.error('RoboSystems MCP server running')
|
|
699
|
+
console.error('Features: Connection pooling, smart caching, retry logic, progress tracking')
|
|
700
|
+
|
|
701
|
+
// Log metrics every 5 minutes
|
|
702
|
+
metricsInterval = setInterval(() => {
|
|
703
|
+
const metrics = remoteClient.getMetrics()
|
|
704
|
+
console.error(`Metrics: ${JSON.stringify(metrics)}`)
|
|
705
|
+
}, 300000)
|
|
179
706
|
|
|
180
707
|
// Keep the process alive
|
|
181
|
-
await new Promise(() => {})
|
|
708
|
+
await new Promise(() => {})
|
|
182
709
|
} catch (error) {
|
|
183
710
|
console.error(`MCP server error: ${error.message}`)
|
|
184
711
|
process.exit(1)
|
|
185
712
|
}
|
|
186
713
|
}
|
|
187
714
|
|
|
188
|
-
//
|
|
189
|
-
|
|
715
|
+
// Graceful shutdown
|
|
716
|
+
let metricsInterval = null
|
|
717
|
+
const cleanup = () => {
|
|
190
718
|
console.error('Shutting down RoboSystems MCP client')
|
|
719
|
+
if (metricsInterval) {
|
|
720
|
+
clearInterval(metricsInterval)
|
|
721
|
+
}
|
|
191
722
|
process.exit(0)
|
|
192
|
-
}
|
|
723
|
+
}
|
|
193
724
|
|
|
194
|
-
process.on('
|
|
195
|
-
|
|
196
|
-
process.exit(0)
|
|
197
|
-
})
|
|
725
|
+
process.on('SIGINT', cleanup)
|
|
726
|
+
process.on('SIGTERM', cleanup)
|
|
198
727
|
|
|
199
|
-
//
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
728
|
+
// Export for programmatic use
|
|
729
|
+
export {
|
|
730
|
+
RoboSystemsMCPClient,
|
|
731
|
+
SSEConnectionPool,
|
|
732
|
+
ResultCache
|
|
733
|
+
}
|
|
734
|
+
|
|
735
|
+
// Only run as server if this is the main module
|
|
736
|
+
if (import.meta.url === `file://${process.argv[1]}`) {
|
|
737
|
+
// Run the server
|
|
738
|
+
main().catch((error) => {
|
|
739
|
+
console.error(`Fatal error: ${error.message}`)
|
|
740
|
+
process.exit(1)
|
|
741
|
+
})
|
|
742
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@robosystems/mcp",
|
|
3
|
-
"version": "0.1
|
|
4
|
-
"description": "MCP server for RoboSystems Financial Knowledge Graph API",
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "Production-ready MCP server for RoboSystems Financial Knowledge Graph API with connection pooling, caching, and retry logic",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
7
7
|
"bin": {
|
|
@@ -27,7 +27,8 @@
|
|
|
27
27
|
"author": "RoboSystems Team",
|
|
28
28
|
"license": "MIT",
|
|
29
29
|
"dependencies": {
|
|
30
|
-
"@modelcontextprotocol/sdk": "^1.
|
|
30
|
+
"@modelcontextprotocol/sdk": "^1.17.1",
|
|
31
|
+
"eventsource": "^4.0.0"
|
|
31
32
|
},
|
|
32
33
|
"engines": {
|
|
33
34
|
"node": ">=18.0.0"
|