@robosystems/mcp 0.3.11 → 0.4.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 +48 -11
- package/index.js +64 -21
- package/package.json +3 -1
- package/proxy.js +217 -0
package/README.md
CHANGED
|
@@ -3,17 +3,17 @@
|
|
|
3
3
|
[](https://www.npmjs.com/package/@robosystems/mcp)
|
|
4
4
|
[](https://opensource.org/licenses/MIT)
|
|
5
5
|
|
|
6
|
-
Official MCP (Model Context Protocol)
|
|
6
|
+
Official MCP (Model Context Protocol) stdio bridge for connecting stdio-only AI clients to the RoboSystems Financial Knowledge Graph API. Query financial statements, explore graph structures, resolve XBRL elements, and build fact grids.
|
|
7
|
+
|
|
8
|
+
> **The preferred way to connect is the hosted remote MCP endpoint — no install required.** Every RoboSystems graph serves the MCP Streamable HTTP transport directly: add `https://api.robosystems.ai/v1/graphs/{graph_id}/mcp` as a connector with your API key in the `X-API-Key` header, and Claude Code, Cursor, VS Code, or any HTTP-capable MCP client connects with zero setup. **This npx package is in maintenance mode** and exists for clients that only speak the stdio transport: by default it runs in [proxy mode](#proxy-mode-the-default), forwarding that same modern transport over stdio. See [Migrating to the remote endpoint](#migrating-to-the-remote-endpoint).
|
|
7
9
|
|
|
8
10
|
## Features
|
|
9
11
|
|
|
12
|
+
- **Native MCP transport over stdio** — the default proxy mode forwards the graph's Streamable HTTP endpoint verbatim: per-session instructions, live tool lists, and streamed progress notifications, identical to connecting the URL directly
|
|
10
13
|
- **Financial data tools** for statements, disclosures, and multidimensional fact grids
|
|
11
14
|
- **Graph exploration** with Cypher queries, schema introspection, and element resolution
|
|
12
15
|
- **Workspace management** for isolated subgraphs, staging data, and persistent agent memory
|
|
13
|
-
- **
|
|
14
|
-
- **Connection pooling** with LRU eviction for optimal performance
|
|
15
|
-
- **Smart caching** for frequently accessed schemas and metadata
|
|
16
|
-
- **Automatic retry logic** with exponential backoff
|
|
16
|
+
- **Legacy bridge mode** for pre-v1.7.0 servers, with client-side SSE/NDJSON aggregation, smart caching, and retry logic
|
|
17
17
|
|
|
18
18
|
## Installation
|
|
19
19
|
|
|
@@ -37,15 +37,52 @@ Add to your MCP servers configuration:
|
|
|
37
37
|
|
|
38
38
|
### Environment Variables
|
|
39
39
|
|
|
40
|
-
| Variable | Description
|
|
41
|
-
| ---------------------- |
|
|
42
|
-
| `ROBOSYSTEMS_API_KEY` | Your API key
|
|
43
|
-
| `ROBOSYSTEMS_GRAPH_ID` | Primary graph ID (parent for workspaces)
|
|
44
|
-
| `ROBOSYSTEMS_API_URL` | API endpoint
|
|
40
|
+
| Variable | Description | Default |
|
|
41
|
+
| ---------------------- | ------------------------------------------------------------------ | ---------------------------- |
|
|
42
|
+
| `ROBOSYSTEMS_API_KEY` | Your API key | _(required)_ |
|
|
43
|
+
| `ROBOSYSTEMS_GRAPH_ID` | Primary graph ID (parent for workspaces) | _(required)_ |
|
|
44
|
+
| `ROBOSYSTEMS_API_URL` | API endpoint | `https://api.robosystems.ai` |
|
|
45
|
+
| `ROBOSYSTEMS_MCP_MODE` | Set to `legacy` to run the old REST-aggregation bridge (see below) | `proxy` |
|
|
46
|
+
| `ROBOSYSTEMS_MCP_URL` | Full MCP endpoint URL — overrides the URL derived from graph ID | _(derived from graph ID)_ |
|
|
47
|
+
|
|
48
|
+
### Proxy Mode (the default)
|
|
49
|
+
|
|
50
|
+
By default this package is a transparent pipe between your stdio client and the graph's native MCP endpoint (`POST /v1/graphs/{graph_id}/mcp`, Streamable HTTP). Every JSON-RPC message is forwarded verbatim, so per-session instructions, the live server tool list, and streamed progress notifications behave exactly as they do when connecting the URL directly — the only thing the proxy adds is the API-key header the stdio client can't send itself. The standard configuration above is all it needs.
|
|
51
|
+
|
|
52
|
+
To target a specific endpoint (for example a local stack), point `ROBOSYSTEMS_MCP_URL` at the full URL, e.g. `http://localhost:8000/v1/graphs/kg.../mcp` — no graph ID needed.
|
|
53
|
+
|
|
54
|
+
### Legacy Bridge Mode
|
|
55
|
+
|
|
56
|
+
Set `ROBOSYSTEMS_MCP_MODE: "legacy"` to run the original bridge, which aggregates the REST tool endpoints (`GET /mcp/tools` + `POST /mcp/call-tool`) client-side and adds its own workspace-switching tools. You only need this against an API deployment that predates the MCP transport (server versions before v1.7.0), or if you depend on the bridge's client-side `create-workspace`/`switch-workspace` tool names — current servers expose the same capabilities as `create-subgraph`/`switch-workspace` tools natively.
|
|
57
|
+
|
|
58
|
+
## Migrating to the Remote Endpoint
|
|
59
|
+
|
|
60
|
+
If your client supports HTTP transports, replace the npx entry with a direct connection — the URL picks the graph (`sec` for the public SEC repository, your `kg…` graph id for your own; a subgraph id like `kg…_dev` is just another URL), and your account-wide API key goes in the `X-API-Key` header, one connector per graph.
|
|
61
|
+
|
|
62
|
+
**Claude Code** — one command:
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
claude mcp add --transport http robosystems-sec \
|
|
66
|
+
https://api.robosystems.ai/v1/graphs/sec/mcp \
|
|
67
|
+
--header "X-API-Key: <your key>"
|
|
68
|
+
```
|
|
69
|
+
|
|
70
|
+
**Cursor / VS Code** — replace the `command`/`args`/`env` entry in `mcp.json` with:
|
|
71
|
+
|
|
72
|
+
```json
|
|
73
|
+
"robosystems-sec": {
|
|
74
|
+
"url": "https://api.robosystems.ai/v1/graphs/sec/mcp",
|
|
75
|
+
"headers": { "X-API-Key": "<your key>" }
|
|
76
|
+
}
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Local development uses the same shape against a local stack: `http://localhost:8000/v1/graphs/{graph_id}/mcp`.
|
|
80
|
+
|
|
81
|
+
**Claude (claude.ai / Desktop) cannot use the remote endpoint directly yet** — its custom connectors authenticate with OAuth only and have no custom-header field, so they cannot send an API key. Claude Desktop users should run this package via `claude_desktop_config.json` (the config file accepts only stdio-shaped `command` entries); in its default [proxy mode](#proxy-mode-the-default) it delivers the full remote-endpoint behavior over stdio.
|
|
45
82
|
|
|
46
83
|
## Tools
|
|
47
84
|
|
|
48
|
-
Tools are loaded dynamically from the RoboSystems API based on your graph.
|
|
85
|
+
Tools are loaded dynamically from the RoboSystems API based on your graph. In legacy bridge mode the client additionally provides its own workspace management tools (in proxy mode the server serves the equivalent subgraph tools natively).
|
|
49
86
|
|
|
50
87
|
### Financial Data
|
|
51
88
|
|
package/index.js
CHANGED
|
@@ -19,6 +19,7 @@ import { Server } from '@modelcontextprotocol/sdk/server/index.js'
|
|
|
19
19
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js'
|
|
20
20
|
import { CallToolRequestSchema, ListToolsRequestSchema } from '@modelcontextprotocol/sdk/types.js'
|
|
21
21
|
import { EventSource } from 'eventsource'
|
|
22
|
+
import { runProxy } from './proxy.js'
|
|
22
23
|
import { readFileSync } from 'fs'
|
|
23
24
|
import { fileURLToPath } from 'url'
|
|
24
25
|
import { dirname, join } from 'path'
|
|
@@ -330,9 +331,9 @@ class RoboSystemsMCPClient {
|
|
|
330
331
|
},
|
|
331
332
|
subgraph_type: {
|
|
332
333
|
type: 'string',
|
|
333
|
-
enum: ['static', '
|
|
334
|
+
enum: ['static', 'knowledge'],
|
|
334
335
|
description:
|
|
335
|
-
'Type of subgraph: "static" for standard isolated workspace, "
|
|
336
|
+
'Type of subgraph: "static" for a standard isolated workspace, "knowledge" for one seeded with the knowledge schema',
|
|
336
337
|
default: 'static',
|
|
337
338
|
},
|
|
338
339
|
},
|
|
@@ -790,7 +791,7 @@ class RoboSystemsMCPClient {
|
|
|
790
791
|
|
|
791
792
|
async _handleCreateWorkspace(args) {
|
|
792
793
|
const { name, description, fork_parent = false, subgraph_type = 'static' } = args
|
|
793
|
-
const validSubgraphTypes = ['static', '
|
|
794
|
+
const validSubgraphTypes = ['static', 'knowledge']
|
|
794
795
|
|
|
795
796
|
if (!validSubgraphTypes.includes(subgraph_type)) {
|
|
796
797
|
throw new Error(
|
|
@@ -810,7 +811,7 @@ class RoboSystemsMCPClient {
|
|
|
810
811
|
method: 'POST',
|
|
811
812
|
headers: { ...this.headers, Accept: 'application/json' },
|
|
812
813
|
body: JSON.stringify({
|
|
813
|
-
name: 'create-
|
|
814
|
+
name: 'create-subgraph',
|
|
814
815
|
arguments: { name, description, fork_parent, subgraph_type },
|
|
815
816
|
}),
|
|
816
817
|
}
|
|
@@ -844,8 +845,9 @@ class RoboSystemsMCPClient {
|
|
|
844
845
|
}
|
|
845
846
|
}
|
|
846
847
|
|
|
847
|
-
// Server created the workspace successfully
|
|
848
|
-
|
|
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
|
|
849
851
|
|
|
850
852
|
// Track the workspace
|
|
851
853
|
this.workspaces.set(workspaceId, {
|
|
@@ -989,8 +991,8 @@ class RoboSystemsMCPClient {
|
|
|
989
991
|
method: 'POST',
|
|
990
992
|
headers: { ...this.headers, Accept: 'application/json' },
|
|
991
993
|
body: JSON.stringify({
|
|
992
|
-
name: 'delete-
|
|
993
|
-
arguments: { workspace_id, force },
|
|
994
|
+
name: 'delete-subgraph',
|
|
995
|
+
arguments: { subgraph_id: workspace_id, force },
|
|
994
996
|
}),
|
|
995
997
|
}
|
|
996
998
|
)
|
|
@@ -1075,12 +1077,15 @@ class RoboSystemsMCPClient {
|
|
|
1075
1077
|
|
|
1076
1078
|
async _refreshWorkspacesCache() {
|
|
1077
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.
|
|
1078
1083
|
const response = await fetch(
|
|
1079
1084
|
`${this.baseUrl}/v1/graphs/${this.primaryGraphId}/mcp/call-tool`,
|
|
1080
1085
|
{
|
|
1081
1086
|
method: 'POST',
|
|
1082
1087
|
headers: { ...this.headers, Accept: 'application/json' },
|
|
1083
|
-
body: JSON.stringify({ name: 'list-
|
|
1088
|
+
body: JSON.stringify({ name: 'list-subgraphs', arguments: {} }),
|
|
1084
1089
|
}
|
|
1085
1090
|
)
|
|
1086
1091
|
|
|
@@ -1102,20 +1107,34 @@ class RoboSystemsMCPClient {
|
|
|
1102
1107
|
result = data.result || data
|
|
1103
1108
|
}
|
|
1104
1109
|
|
|
1105
|
-
if (result.
|
|
1106
|
-
|
|
1107
|
-
for (const ws of result.workspaces) {
|
|
1108
|
-
this.workspaces.set(ws.workspace_id, {
|
|
1109
|
-
type: ws.type,
|
|
1110
|
-
name: ws.name,
|
|
1111
|
-
description: ws.description,
|
|
1112
|
-
parent_graph_id: ws.parent_graph_id,
|
|
1113
|
-
created_at: ws.created_at ? new Date(ws.created_at).getTime() : Date.now(),
|
|
1114
|
-
})
|
|
1115
|
-
}
|
|
1110
|
+
if (!result.subgraphs) {
|
|
1111
|
+
return result
|
|
1116
1112
|
}
|
|
1117
1113
|
|
|
1118
|
-
|
|
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
|
+
}
|
|
1119
1138
|
} catch (error) {
|
|
1120
1139
|
console.error(`Failed to refresh workspaces cache: ${error.message}`)
|
|
1121
1140
|
return null
|
|
@@ -1209,6 +1228,30 @@ async function main() {
|
|
|
1209
1228
|
const apiKey = process.env.ROBOSYSTEMS_API_KEY
|
|
1210
1229
|
const graphId = process.env.ROBOSYSTEMS_GRAPH_ID
|
|
1211
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
|
+
|
|
1212
1255
|
if (!apiKey) {
|
|
1213
1256
|
console.error('ROBOSYSTEMS_API_KEY environment variable is required')
|
|
1214
1257
|
console.error('Please set ROBOSYSTEMS_API_KEY in your MCP configuration')
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@robosystems/mcp",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "MCP client adapter for connecting AI agents to RoboSystems Financial Knowledge Graph API endpoints with workspace support",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "index.js",
|
|
@@ -10,10 +10,12 @@
|
|
|
10
10
|
},
|
|
11
11
|
"files": [
|
|
12
12
|
"index.js",
|
|
13
|
+
"proxy.js",
|
|
13
14
|
"README.md",
|
|
14
15
|
"LICENSE"
|
|
15
16
|
],
|
|
16
17
|
"scripts": {
|
|
18
|
+
"prepare": "git config core.hooksPath .githooks || true",
|
|
17
19
|
"start": "node index.js",
|
|
18
20
|
"format": "prettier . --write",
|
|
19
21
|
"format:check": "prettier . --check",
|
package/proxy.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Streamable HTTP proxy mode.
|
|
3
|
+
*
|
|
4
|
+
* Instead of impersonating the MCP server over the REST tool endpoints
|
|
5
|
+
* (GET /mcp/tools + POST /mcp/call-tool), this mode is a transparent pipe
|
|
6
|
+
* between a stdio MCP client (Claude Desktop, or any stdio-only host) and the
|
|
7
|
+
* platform's native MCP endpoint (POST /v1/graphs/{graph_id}/mcp, Streamable
|
|
8
|
+
* HTTP). Every JSON-RPC message read from stdin is forwarded verbatim with the
|
|
9
|
+
* API key header attached; JSON and SSE responses are relayed back to stdout
|
|
10
|
+
* message-for-message. Per-session instructions, live tool lists, and streamed
|
|
11
|
+
* progress notifications all pass through untouched — connecting through the
|
|
12
|
+
* proxy behaves identically to connecting the URL directly.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { createInterface } from 'readline'
|
|
16
|
+
|
|
17
|
+
const JSONRPC_PARSE_ERROR = -32700
|
|
18
|
+
const JSONRPC_PROXY_ERROR = -32000
|
|
19
|
+
const ERROR_BODY_PREVIEW_CHARS = 300
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Parse a Server-Sent Events stream and deliver each event's JSON payload.
|
|
23
|
+
* Handles multi-line `data:` fields per the SSE spec and ignores comment
|
|
24
|
+
* (keepalive) lines. `event:`/`id:`/`retry:` fields carry no JSON-RPC content
|
|
25
|
+
* on this endpoint and are skipped.
|
|
26
|
+
*/
|
|
27
|
+
async function relaySSE(body, deliver) {
|
|
28
|
+
const reader = body.getReader()
|
|
29
|
+
const decoder = new TextDecoder()
|
|
30
|
+
let buffer = ''
|
|
31
|
+
let dataLines = []
|
|
32
|
+
|
|
33
|
+
const dispatch = () => {
|
|
34
|
+
if (dataLines.length === 0) return
|
|
35
|
+
const dataStr = dataLines.join('\n')
|
|
36
|
+
dataLines = []
|
|
37
|
+
if (!dataStr || dataStr === '[DONE]') return
|
|
38
|
+
try {
|
|
39
|
+
deliver(JSON.parse(dataStr))
|
|
40
|
+
} catch {
|
|
41
|
+
console.error('Proxy: skipping unparseable SSE event')
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
try {
|
|
46
|
+
while (true) {
|
|
47
|
+
const { done, value } = await reader.read()
|
|
48
|
+
if (done) break
|
|
49
|
+
|
|
50
|
+
buffer += decoder.decode(value, { stream: true })
|
|
51
|
+
const lines = buffer.split(/\r?\n/)
|
|
52
|
+
buffer = lines.pop() || ''
|
|
53
|
+
|
|
54
|
+
for (const line of lines) {
|
|
55
|
+
if (line === '') {
|
|
56
|
+
dispatch()
|
|
57
|
+
} else if (line.startsWith(':')) {
|
|
58
|
+
// Comment / keepalive — ignore
|
|
59
|
+
} else if (line.startsWith('data:')) {
|
|
60
|
+
dataLines.push(line.slice(5).replace(/^ /, ''))
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
// Flush a trailing event if the stream ended without a final blank line
|
|
65
|
+
if (buffer.startsWith('data:')) {
|
|
66
|
+
dataLines.push(buffer.slice(5).replace(/^ /, ''))
|
|
67
|
+
}
|
|
68
|
+
dispatch()
|
|
69
|
+
} finally {
|
|
70
|
+
reader.cancel().catch(() => {})
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Create a proxy instance bound to one MCP endpoint. Exposed separately from
|
|
76
|
+
* runProxy so tests can drive individual messages without real stdio.
|
|
77
|
+
*/
|
|
78
|
+
export function createProxy({ url, apiKey, version, output = process.stdout, fetchImpl = fetch }) {
|
|
79
|
+
// Captured from the initialize response and echoed back on subsequent
|
|
80
|
+
// requests via the MCP-Protocol-Version header, per Streamable HTTP.
|
|
81
|
+
let protocolVersion = null
|
|
82
|
+
|
|
83
|
+
const deliver = (message) => {
|
|
84
|
+
if (message && typeof message === 'object' && message.result?.protocolVersion) {
|
|
85
|
+
protocolVersion = message.result.protocolVersion
|
|
86
|
+
}
|
|
87
|
+
output.write(JSON.stringify(message) + '\n')
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
const buildHeaders = () => {
|
|
91
|
+
const headers = {
|
|
92
|
+
'Content-Type': 'application/json',
|
|
93
|
+
Accept: 'application/json, text/event-stream',
|
|
94
|
+
'User-Agent': `robosystems-mcp/${version}`,
|
|
95
|
+
'X-MCP-Client': version,
|
|
96
|
+
}
|
|
97
|
+
if (apiKey) {
|
|
98
|
+
headers['X-API-Key'] = apiKey
|
|
99
|
+
}
|
|
100
|
+
if (protocolVersion) {
|
|
101
|
+
headers['MCP-Protocol-Version'] = protocolVersion
|
|
102
|
+
}
|
|
103
|
+
return headers
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const handleLine = async (line) => {
|
|
107
|
+
const raw = line.trim()
|
|
108
|
+
if (!raw) return
|
|
109
|
+
|
|
110
|
+
let message
|
|
111
|
+
try {
|
|
112
|
+
message = JSON.parse(raw)
|
|
113
|
+
} catch {
|
|
114
|
+
deliver({
|
|
115
|
+
jsonrpc: '2.0',
|
|
116
|
+
id: null,
|
|
117
|
+
error: { code: JSONRPC_PARSE_ERROR, message: 'Parse error' },
|
|
118
|
+
})
|
|
119
|
+
return
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Requests carry both a method and an id and expect a reply; notifications
|
|
123
|
+
// and client→server responses get forwarded but never answered locally.
|
|
124
|
+
const expectsResponse = message.method !== undefined && message.id !== undefined
|
|
125
|
+
|
|
126
|
+
try {
|
|
127
|
+
const response = await fetchImpl(url, {
|
|
128
|
+
method: 'POST',
|
|
129
|
+
headers: buildHeaders(),
|
|
130
|
+
body: raw,
|
|
131
|
+
})
|
|
132
|
+
|
|
133
|
+
// 202 Accepted — notification or response delivered, nothing to relay
|
|
134
|
+
if (response.status === 202) return
|
|
135
|
+
|
|
136
|
+
if (!response.ok) {
|
|
137
|
+
const text = await response.text().catch(() => '')
|
|
138
|
+
if (expectsResponse) {
|
|
139
|
+
const detail = text ? `: ${text.slice(0, ERROR_BODY_PREVIEW_CHARS)}` : ''
|
|
140
|
+
deliver({
|
|
141
|
+
jsonrpc: '2.0',
|
|
142
|
+
id: message.id,
|
|
143
|
+
error: {
|
|
144
|
+
code: JSONRPC_PROXY_ERROR,
|
|
145
|
+
message: `HTTP ${response.status}${detail}`,
|
|
146
|
+
},
|
|
147
|
+
})
|
|
148
|
+
} else {
|
|
149
|
+
console.error(`Proxy: HTTP ${response.status} forwarding ${message.method || 'response'}`)
|
|
150
|
+
}
|
|
151
|
+
return
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const contentType = response.headers.get('content-type') || ''
|
|
155
|
+
if (contentType.includes('text/event-stream')) {
|
|
156
|
+
await relaySSE(response.body, deliver)
|
|
157
|
+
} else {
|
|
158
|
+
const text = await response.text()
|
|
159
|
+
if (!text.trim()) return
|
|
160
|
+
// Re-serialize to guarantee one message per stdout line
|
|
161
|
+
deliver(JSON.parse(text))
|
|
162
|
+
}
|
|
163
|
+
} catch (error) {
|
|
164
|
+
if (expectsResponse) {
|
|
165
|
+
deliver({
|
|
166
|
+
jsonrpc: '2.0',
|
|
167
|
+
id: message.id,
|
|
168
|
+
error: {
|
|
169
|
+
code: JSONRPC_PROXY_ERROR,
|
|
170
|
+
message: `Proxy request failed: ${error.message}`,
|
|
171
|
+
},
|
|
172
|
+
})
|
|
173
|
+
} else {
|
|
174
|
+
console.error(`Proxy request failed: ${error.message}`)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return {
|
|
180
|
+
handleLine,
|
|
181
|
+
getProtocolVersion: () => protocolVersion,
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Run the proxy over real stdio until the host closes stdin.
|
|
187
|
+
*/
|
|
188
|
+
export async function runProxy({
|
|
189
|
+
url,
|
|
190
|
+
apiKey,
|
|
191
|
+
version,
|
|
192
|
+
input = process.stdin,
|
|
193
|
+
output = process.stdout,
|
|
194
|
+
fetchImpl = fetch,
|
|
195
|
+
}) {
|
|
196
|
+
const proxy = createProxy({ url, apiKey, version, output, fetchImpl })
|
|
197
|
+
|
|
198
|
+
console.error(`RoboSystems MCP proxy v${version}`)
|
|
199
|
+
console.error(`Forwarding stdio <-> ${url}`)
|
|
200
|
+
if (!apiKey) {
|
|
201
|
+
console.error(
|
|
202
|
+
'No ROBOSYSTEMS_API_KEY set — forwarding without an X-API-Key header ' +
|
|
203
|
+
'(fine only if the endpoint URL itself carries credentials)'
|
|
204
|
+
)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const pending = new Set()
|
|
208
|
+
const rl = createInterface({ input, terminal: false })
|
|
209
|
+
|
|
210
|
+
rl.on('line', (line) => {
|
|
211
|
+
const task = proxy.handleLine(line).finally(() => pending.delete(task))
|
|
212
|
+
pending.add(task)
|
|
213
|
+
})
|
|
214
|
+
|
|
215
|
+
await new Promise((resolve) => rl.on('close', resolve))
|
|
216
|
+
await Promise.allSettled([...pending])
|
|
217
|
+
}
|