@robosystems/mcp 0.5.5 → 1.0.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 CHANGED
@@ -3,13 +3,16 @@
3
3
  [![npm version](https://badge.fury.io/js/@robosystems%2Fmcp.svg)](https://www.npmjs.com/package/@robosystems/mcp)
4
4
  [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
5
5
 
6
- **The stdio bridge to the MCP server of [RoboSystems](https://github.com/RoboFinSystems/robosystems), the open-source knowledge graph for finance.** Every graph is an MCP server over the Streamable HTTP transport; `@robosystems/mcp` connects MCP clients without HTTP transport to it. It is in maintenance mode.
6
+ **The stdio bridge to the MCP server of [RoboSystems](https://github.com/RoboFinSystems/robosystems), the open-source knowledge graph for finance.** Every graph is an MCP server over the Streamable HTTP transport; `@robosystems/mcp` connects a stdio MCP client to them with an API key. It runs in one of two modes:
7
7
 
8
- The bridge reads JSON-RPC messages from stdin, posts each one unchanged to a graph's MCP endpoint with your API key in the `X-API-Key` header, and writes the replies to stdout. The instructions, tools and progress notifications are the server's own; the bridge adds none. Diagnostics go to stderr, including a notice at startup when a newer version is on npm.
8
+ - **Catalog**: one connection for every graph your key reaches. Four tools take the graph as an argument, so you can work across graphs and use a subgraph the moment it is created
9
+ - **Proxy**: one connection for one graph. The bridge forwards every message unchanged, and the tools and instructions are the server's own
9
10
 
10
- ## Connect directly if you can
11
+ Diagnostics go to stderr, including a notice at startup when a newer version is on npm.
11
12
 
12
- An MCP client with HTTP transport does not need this package. Connect it to the hosted server instead:
13
+ ## Connect directly if one graph is enough
14
+
15
+ An MCP client with HTTP transport does not need this package to reach a single graph. Connect it to the hosted server instead:
13
16
 
14
17
  - **OAuth**: `https://api.robosystems.ai/v1/mcp`. Sign in and choose the graph on the consent screen. `https://api.robosystems.ai/v1/mcp/roboledger` is the same for RoboLedger graphs, with the accounting tools only
15
18
  - **API key**: `https://api.robosystems.ai/v1/graphs/{graph_id}/mcp`, with the key in the `X-API-Key` header and never in the URL. The URL picks the graph: `sec` for the public SEC repository, your graph id for your own
@@ -20,7 +23,7 @@ claude mcp add --transport http robosystems-sec \
20
23
  --header "X-API-Key: <your key>"
21
24
  ```
22
25
 
23
- The app's MCP page has the snippet for each client. The bridge authenticates with an API key only, so it connects to a per-graph URL, never to the OAuth endpoints.
26
+ The app's MCP page has the snippet for each client. A direct connection is one graph: each further graph or subgraph is another connection. The bridge authenticates with an API key only, never through the OAuth endpoints.
24
27
 
25
28
  ## Install
26
29
 
@@ -33,28 +36,64 @@ No install step: MCP clients run it through `npx`. Tested on Node.js 22, 24 and
33
36
  "command": "npx",
34
37
  "args": ["-y", "@robosystems/mcp@latest"],
35
38
  "env": {
36
- "ROBOSYSTEMS_API_KEY": "<your key>",
37
- "ROBOSYSTEMS_GRAPH_ID": "sec"
39
+ "ROBOSYSTEMS_API_KEY": "<your key>"
38
40
  }
39
41
  }
40
42
  }
41
43
  }
42
44
  ```
43
45
 
44
- This is the shape of `claude_desktop_config.json` and of other clients that take stdio `command` entries. Keep `@latest` in the arguments: a global `npm install -g @robosystems/mcp` can shadow `npx` and pin an old version.
46
+ This is the shape of `claude_desktop_config.json` and of other clients that take stdio `command` entries. With the key alone the bridge runs as a catalog; add `ROBOSYSTEMS_GRAPH_ID` to proxy one graph. Keep `@latest` in the arguments: a global `npm install -g @robosystems/mcp` can shadow `npx` and pin an old version.
47
+
48
+ ## Catalog mode
49
+
50
+ The bridge serves four tools, the same on every connection:
51
+
52
+ | Tool | Does |
53
+ | ----------------- | ------------------------------------------------------------------------------------------------------------------------ |
54
+ | `list-graphs` | Lists the graphs the connection reaches, with the id or alias to pass as `graph` |
55
+ | `get-tools` | For one graph: the index of its tools and its instructions; with `names`, the full description and input schema of those |
56
+ | `call-read-tool` | Runs one of a graph's read tools |
57
+ | `call-write-tool` | Runs one of a graph's write tools |
58
+
59
+ Every call names its graph. There is no current graph and nothing to switch, so two conversations sharing one bridge cannot redirect each other. Each call is forwarded to that graph's own endpoint with your key, where the server checks access as it does for a direct connection.
60
+
61
+ A subgraph is a graph: `create-subgraph` on the parent (through `call-write-tool`) returns an id that works as `graph` on the next call. The read and write split follows the hints the server publishes for each tool, so a client can approve reads without prompting and still show each write by name.
62
+
63
+ To limit a connection to some graphs, and to name them, set `ROBOSYSTEMS_GRAPH_IDS`:
64
+
65
+ ```json
66
+ "env": {
67
+ "ROBOSYSTEMS_API_KEY": "<your key>",
68
+ "ROBOSYSTEMS_GRAPH_IDS": "books=kg1a2b3c4d5e6f7a8b9c0d,sec"
69
+ }
70
+ ```
71
+
72
+ Each entry is a graph id or `alias=id`. The connection then reaches those graphs and their subgraphs, and refuses any other. A key scoped to one graph cannot list the account, so set its graph here.
73
+
74
+ ### Read-only
75
+
76
+ Text a model reads from one graph can try to steer a write on another. Two settings take writes off the table:
77
+
78
+ - `ROBOSYSTEMS_READ_ONLY=true` makes the whole connection read-only: `call-write-tool` is not listed and cannot be called
79
+ - A `:ro` suffix in `ROBOSYSTEMS_GRAPH_IDS` does the same for one graph and its subgraphs: `books=kg1a2b3c4d5e6f7a8b9c0d,sec:ro`
80
+
81
+ Either way the graph's write tools are left out of `get-tools`, and the server still enforces what the key itself may do.
45
82
 
46
83
  ## Configuration
47
84
 
48
- The bridge reads four environment variables and takes no command-line arguments.
85
+ The bridge reads six environment variables and takes no command-line arguments.
49
86
 
50
- | Variable | Purpose | Default |
51
- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------- | ---------------------------- |
52
- | `ROBOSYSTEMS_API_KEY` | API key, sent as `X-API-Key`; account-wide or scoped to one graph | none |
53
- | `ROBOSYSTEMS_GRAPH_ID` | The graph to connect: `sec`, a graph id, or a subgraph id such as `kg…_dev`. Required unless `ROBOSYSTEMS_MCP_URL` is set | none |
54
- | `ROBOSYSTEMS_API_URL` | Base URL the endpoint is derived from: `{ROBOSYSTEMS_API_URL}/v1/graphs/{ROBOSYSTEMS_GRAPH_ID}/mcp` | `https://api.robosystems.ai` |
55
- | `ROBOSYSTEMS_MCP_URL` | Full endpoint URL. Overrides the derived one, and needs no graph id | derived |
87
+ | Variable | Purpose | Default |
88
+ | ----------------------- | ------------------------------------------------------------------------------------------- | ---------------------------- |
89
+ | `ROBOSYSTEMS_API_KEY` | API key, sent as `X-API-Key`; account-wide or scoped to one graph. Required in catalog mode | none |
90
+ | `ROBOSYSTEMS_GRAPH_IDS` | Catalog mode: the graphs to reach, as ids or `alias=id` pairs separated by commas | every graph the key reaches |
91
+ | `ROBOSYSTEMS_READ_ONLY` | Catalog mode: `true` withholds every write tool | `false` |
92
+ | `ROBOSYSTEMS_GRAPH_ID` | Proxy mode: the one graph to connect, `sec`, a graph id, or a subgraph id such as `kg…_dev` | none |
93
+ | `ROBOSYSTEMS_API_URL` | Base URL of the API. A graph's endpoint is `{ROBOSYSTEMS_API_URL}/v1/graphs/{graph_id}/mcp` | `https://api.robosystems.ai` |
94
+ | `ROBOSYSTEMS_MCP_URL` | Proxy mode: a full endpoint URL. Overrides the derived one, and needs no graph id | derived |
56
95
 
57
- For a self-hosted stack, set `ROBOSYSTEMS_API_URL` to its address (`http://localhost:8000` in local development), or point `ROBOSYSTEMS_MCP_URL` at the full per-graph URL. See [Authentication & API Keys](https://robosystems.ai/docs/technical/authentication-and-api-keys) and [Self-Hosting on a Server](https://robosystems.ai/docs/technical/self-hosting-on-a-server).
96
+ Setting `ROBOSYSTEMS_GRAPH_ID` or `ROBOSYSTEMS_MCP_URL` selects proxy mode. For a self-hosted stack, set `ROBOSYSTEMS_API_URL` to its address (`http://localhost:8000` in local development). See [Authentication & API Keys](https://robosystems.ai/docs/technical/authentication-and-api-keys) and [Self-Hosting on a Server](https://robosystems.ai/docs/technical/self-hosting-on-a-server).
58
97
 
59
98
  ## Documentation
60
99
 
package/catalog.js ADDED
@@ -0,0 +1,755 @@
1
+ /**
2
+ * Catalog mode.
3
+ *
4
+ * One stdio connection for every graph an API key reaches. The bridge serves
5
+ * four fixed tools; each takes the graph as an argument and is forwarded to
6
+ * that graph's own MCP endpoint (POST /v1/graphs/{graph_id}/mcp). A graph's
7
+ * tools are data returned by `get-tools`, never part of this server's
8
+ * `tools/list`, so the list is the same on every connection and a subgraph is
9
+ * usable the moment it exists. There is no current graph: nothing here carries
10
+ * state from one call to the next except short-lived caches of server output.
11
+ *
12
+ * A connection, or a graph within it, can be read-only: its write tools are
13
+ * then neither listed nor callable.
14
+ */
15
+
16
+ import { createInterface } from 'readline'
17
+ import { relaySSE } from './proxy.js'
18
+
19
+ export const PROTOCOL_VERSION = '2025-06-18'
20
+
21
+ const JSONRPC_PARSE_ERROR = -32700
22
+ const JSONRPC_METHOD_NOT_FOUND = -32601
23
+ const JSONRPC_INVALID_PARAMS = -32602
24
+
25
+ // A graph reference becomes a URL path segment, so nothing outside this set
26
+ // is ever forwarded.
27
+ const GRAPH_REF = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/
28
+
29
+ const READ_ONLY_SUFFIX = ':ro'
30
+
31
+ const CACHE_TTL_MS = 60_000
32
+ const LOOKUP_TIMEOUT_MS = 30_000
33
+ const SUMMARY_CHARS = 180
34
+ const MAX_DEFINITIONS = 8
35
+ const MAX_QUERY_HITS = 25
36
+ const ERROR_BODY_PREVIEW_CHARS = 300
37
+
38
+ const GRAPH_ARGUMENT = {
39
+ type: 'string',
40
+ description:
41
+ 'The graph to act on: a graph id, a subgraph id (`{parent}_{name}`) or an alias, as `list-graphs` returns them',
42
+ }
43
+
44
+ export const CATALOG_TOOLS = [
45
+ {
46
+ name: 'list-graphs',
47
+ title: 'List graphs',
48
+ description:
49
+ 'List the graphs this connection can reach, with the id or alias to pass as `graph` to the ' +
50
+ 'other tools. Subgraphs are graphs: a parent’s are listed by its own `list-subgraphs` ' +
51
+ 'tool (through `call-read-tool`), and a subgraph id works as `graph` as soon as it exists.',
52
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
53
+ annotations: {
54
+ title: 'List graphs',
55
+ readOnlyHint: true,
56
+ destructiveHint: false,
57
+ idempotentHint: true,
58
+ openWorldHint: false,
59
+ },
60
+ },
61
+ {
62
+ name: 'get-tools',
63
+ title: 'Get a graph’s tools',
64
+ description:
65
+ 'Look up the tools one graph serves. Each graph has its own list: a ledger graph, a shared ' +
66
+ 'repository such as `sec` and a subgraph differ.\n\n' +
67
+ '- With `graph` alone: the index (every tool’s name and one-line summary, split into ' +
68
+ 'read and write tools) and the graph’s own instructions. Call this first for a graph ' +
69
+ 'you have not worked on in this conversation, and read the instructions.\n' +
70
+ '- With `names`: the full description and input schema of those tools. Read a tool’s ' +
71
+ 'definition before the first time you call it; never guess its arguments.\n' +
72
+ '- With `query`: the index filtered to tools matching the words given.',
73
+ inputSchema: {
74
+ type: 'object',
75
+ properties: {
76
+ graph: GRAPH_ARGUMENT,
77
+ names: {
78
+ type: 'array',
79
+ items: { type: 'string' },
80
+ maxItems: MAX_DEFINITIONS,
81
+ description: `Tool names to return in full, at most ${MAX_DEFINITIONS} per call`,
82
+ },
83
+ query: {
84
+ type: 'string',
85
+ description: 'Words to filter the index by, matched against names and descriptions',
86
+ },
87
+ },
88
+ required: ['graph'],
89
+ additionalProperties: false,
90
+ },
91
+ annotations: {
92
+ title: 'Get a graph’s tools',
93
+ readOnlyHint: true,
94
+ destructiveHint: false,
95
+ idempotentHint: true,
96
+ openWorldHint: false,
97
+ },
98
+ },
99
+ {
100
+ name: 'call-read-tool',
101
+ title: 'Call a read tool',
102
+ description:
103
+ 'Run one of a graph’s read tools (listed under `read_tools` by `get-tools`). `name` is ' +
104
+ 'the tool and `arguments` is its input, exactly as its definition describes. The result is ' +
105
+ 'the tool’s own. A write tool is refused here: use `call-write-tool`.',
106
+ inputSchema: {
107
+ type: 'object',
108
+ properties: {
109
+ graph: GRAPH_ARGUMENT,
110
+ name: { type: 'string', description: 'The tool to run' },
111
+ arguments: {
112
+ type: 'object',
113
+ description: 'The tool’s arguments, per its input schema',
114
+ additionalProperties: true,
115
+ },
116
+ },
117
+ required: ['graph', 'name'],
118
+ additionalProperties: false,
119
+ },
120
+ annotations: {
121
+ title: 'Call a read tool',
122
+ readOnlyHint: true,
123
+ destructiveHint: false,
124
+ idempotentHint: true,
125
+ openWorldHint: false,
126
+ },
127
+ },
128
+ {
129
+ name: 'call-write-tool',
130
+ title: 'Call a write tool',
131
+ description:
132
+ 'Run one of a graph’s write tools (listed under `write_tools` by `get-tools`). `name` ' +
133
+ 'is the tool and `arguments` is its input, exactly as its definition describes. This ' +
134
+ 'changes the graph named in `graph`: check it is the one you mean. `create-subgraph` on a ' +
135
+ 'parent returns a subgraph id that is usable as `graph` on the next call. A read tool is ' +
136
+ 'refused here: use `call-read-tool`.',
137
+ inputSchema: {
138
+ type: 'object',
139
+ properties: {
140
+ graph: GRAPH_ARGUMENT,
141
+ name: { type: 'string', description: 'The tool to run' },
142
+ arguments: {
143
+ type: 'object',
144
+ description: 'The tool’s arguments, per its input schema',
145
+ additionalProperties: true,
146
+ },
147
+ },
148
+ required: ['graph', 'name'],
149
+ additionalProperties: false,
150
+ },
151
+ annotations: {
152
+ title: 'Call a write tool',
153
+ readOnlyHint: false,
154
+ destructiveHint: true,
155
+ idempotentHint: false,
156
+ openWorldHint: true,
157
+ },
158
+ },
159
+ ]
160
+
161
+ /**
162
+ * Parse ROBOSYSTEMS_GRAPH_IDS: a comma-separated list of graph ids, each
163
+ * optionally named (`rfs=kg1a…`) and optionally read-only (`sec:ro`).
164
+ * Returns null when unset, which means every graph the key reaches. Throws on
165
+ * anything that is not a safe reference.
166
+ */
167
+ export function parseGraphSet(raw) {
168
+ if (!raw || !raw.trim()) return null
169
+ const entries = []
170
+ const ids = new Set()
171
+ const aliases = new Map()
172
+ const readOnly = new Set()
173
+ for (const part of raw.split(',')) {
174
+ const item = part.trim()
175
+ if (!item) continue
176
+ const isReadOnly = item.endsWith(READ_ONLY_SUFFIX)
177
+ const pair = isReadOnly ? item.slice(0, -READ_ONLY_SUFFIX.length).trim() : item
178
+ const eq = pair.indexOf('=')
179
+ const alias = eq === -1 ? null : pair.slice(0, eq).trim()
180
+ const id = eq === -1 ? pair : pair.slice(eq + 1).trim()
181
+ if (!GRAPH_REF.test(id) || (alias !== null && !GRAPH_REF.test(alias))) {
182
+ throw new Error(
183
+ `ROBOSYSTEMS_GRAPH_IDS: "${item}" is not a graph id or alias=id pair ` +
184
+ `(add "${READ_ONLY_SUFFIX}" for read-only)`
185
+ )
186
+ }
187
+ if (ids.has(id)) continue
188
+ ids.add(id)
189
+ if (alias) aliases.set(alias, id)
190
+ if (isReadOnly) readOnly.add(id)
191
+ entries.push({ id, alias, readOnly: isReadOnly })
192
+ }
193
+ // Set but empty must not quietly widen the connection to every graph.
194
+ if (entries.length === 0) throw new Error('ROBOSYSTEMS_GRAPH_IDS is set but names no graph')
195
+ for (const alias of aliases.keys()) {
196
+ if (ids.has(alias)) {
197
+ throw new Error(`ROBOSYSTEMS_GRAPH_IDS: alias "${alias}" is also a graph id`)
198
+ }
199
+ }
200
+ return { entries, ids, aliases, readOnly }
201
+ }
202
+
203
+ /**
204
+ * Turn the model's `graph` argument into a graph id, or throw with a message
205
+ * the model can act on. With a configured set, only its graphs and their
206
+ * subgraphs resolve; without one, any safe id is forwarded and the server
207
+ * decides what the key may reach.
208
+ */
209
+ export function resolveGraph(ref, graphSet) {
210
+ if (typeof ref !== 'string' || !GRAPH_REF.test(ref)) {
211
+ throw new Error('`graph` must be a graph id or alias from `list-graphs`')
212
+ }
213
+ if (!graphSet) return ref
214
+ if (graphSet.aliases.has(ref)) return graphSet.aliases.get(ref)
215
+ if (graphSet.ids.has(ref)) return ref
216
+ for (const id of graphSet.ids) {
217
+ if (ref.startsWith(`${id}_`)) return ref
218
+ }
219
+ const allowed = graphSet.entries.map((e) => e.alias || e.id).join(', ')
220
+ throw new Error(
221
+ `Graph "${ref}" is outside this connection. It reaches: ${allowed}, and their subgraphs`
222
+ )
223
+ }
224
+
225
+ /** Whether writes are withheld for a graph: its own mark, or its parent's. */
226
+ export function isGraphReadOnly(graphId, graphSet) {
227
+ if (!graphSet) return false
228
+ if (graphSet.readOnly.has(graphId)) return true
229
+ for (const id of graphSet.readOnly) {
230
+ if (graphId.startsWith(`${id}_`)) return true
231
+ }
232
+ return false
233
+ }
234
+
235
+ /** The first paragraph of a tool description that says what the tool does. */
236
+ export function summarize(description) {
237
+ const paragraphs = String(description || '')
238
+ .split(/\n\s*\n/)
239
+ .map((p) => p.replace(/\s+/g, ' ').trim())
240
+ .filter(Boolean)
241
+ const lead = paragraphs.find((p) => !p.startsWith('**GRAPH:**')) || ''
242
+ return lead.length > SUMMARY_CHARS ? `${lead.slice(0, SUMMARY_CHARS - 1).trimEnd()}…` : lead
243
+ }
244
+
245
+ const isReadTool = (tool) => tool?.annotations?.readOnlyHint === true
246
+
247
+ function searchTools(tools, query) {
248
+ const words = query.toLowerCase().split(/\s+/).filter(Boolean)
249
+ return tools
250
+ .map((tool) => {
251
+ const name = tool.name.toLowerCase()
252
+ const title = String(tool.title || '').toLowerCase()
253
+ const description = String(tool.description || '').toLowerCase()
254
+ let score = 0
255
+ for (const word of words) {
256
+ if (name.includes(word)) score += 3
257
+ else if (title.includes(word)) score += 2
258
+ else if (description.includes(word)) score += 1
259
+ }
260
+ return { tool, score }
261
+ })
262
+ .filter((hit) => hit.score > 0)
263
+ .sort((a, b) => b.score - a.score)
264
+ .slice(0, MAX_QUERY_HITS)
265
+ .map((hit) => hit.tool)
266
+ }
267
+
268
+ function buildInstructions(graphSet, readOnly) {
269
+ const scope = graphSet
270
+ ? `This connection is limited to these graphs and their subgraphs: ${graphSet.entries
271
+ .map((e) => {
272
+ const label = e.alias ? `\`${e.alias}\` (\`${e.id}\`)` : `\`${e.id}\``
273
+ return e.readOnly && !readOnly ? `${label}, read-only` : label
274
+ })
275
+ .join(', ')}.`
276
+ : 'This connection reaches every graph the API key can.'
277
+ if (readOnly) {
278
+ return [
279
+ 'RoboSystems, through one read-only connection for many graphs. Each graph is its own MCP ' +
280
+ 'server with its own tools and instructions; this connection looks them up and calls ' +
281
+ 'them for you.',
282
+ scope,
283
+ 'This connection cannot change anything: write tools are neither listed nor callable.',
284
+ 'HOW TO WORK',
285
+ '- `list-graphs` says what you can reach. Every other tool takes `graph`: there is no ' +
286
+ 'current or default graph, so name it on every call.',
287
+ '- Before working on a graph, call `get-tools` with `graph` alone and read the ' +
288
+ 'instructions it returns. They are that graph’s own and they differ from graph to ' +
289
+ 'graph. Where they describe a write, it is not available here.',
290
+ '- Before the first call to a tool, call `get-tools` with its name in `names` and follow ' +
291
+ 'its description and input schema, then run it with `call-read-tool`.',
292
+ 'When several graphs are in play, say which graph a figure belongs to.',
293
+ ].join('\n')
294
+ }
295
+ return [
296
+ 'RoboSystems, through one connection for many graphs. Each graph is its own MCP server with ' +
297
+ 'its own tools and instructions; this connection looks them up and calls them for you.',
298
+ scope,
299
+ 'HOW TO WORK',
300
+ '- `list-graphs` says what you can reach. Every other tool takes `graph`: there is no ' +
301
+ 'current or default graph, so name it on every call.',
302
+ '- Before working on a graph, call `get-tools` with `graph` alone and read the instructions ' +
303
+ 'it returns. They are that graph’s own and they differ from graph to graph.',
304
+ '- Before the first call to a tool, call `get-tools` with its name in `names` and follow ' +
305
+ 'its description and input schema.',
306
+ '- Run it with `call-read-tool` or `call-write-tool`, whichever list the index put it in.',
307
+ 'SUBGRAPHS',
308
+ '- A subgraph is a graph with its own, smaller tool list. Create one with the parent’s ' +
309
+ '`create-subgraph` (a write tool); the id it returns works as `graph` on the next call. ' +
310
+ 'The parent’s `list-subgraphs` lists them, and `delete-subgraph` removes one.',
311
+ '- A result that says to add a connector for a `connector_url` is written for a connection ' +
312
+ 'to a single graph. Here, pass the subgraph id as `graph` instead.',
313
+ 'When several graphs are in play, say which graph a figure or a write belongs to.',
314
+ ].join('\n')
315
+ }
316
+
317
+ class UpstreamError extends Error {}
318
+
319
+ function textResult(text, isError = false) {
320
+ return { content: [{ type: 'text', text }], isError }
321
+ }
322
+
323
+ const jsonResult = (value) => textResult(JSON.stringify(value))
324
+
325
+ /**
326
+ * Create a catalog bound to one API base and key. Exposed separately from
327
+ * runCatalog so tests can drive individual messages without real stdio.
328
+ */
329
+ export function createCatalog({
330
+ baseUrl,
331
+ apiKey,
332
+ version,
333
+ graphSet = null,
334
+ readOnly = false,
335
+ output = process.stdout,
336
+ fetchImpl = fetch,
337
+ now = Date.now,
338
+ }) {
339
+ const apiBase = (baseUrl || 'https://api.robosystems.ai').replace(/\/$/, '')
340
+ const toolCache = new Map()
341
+ const instructionCache = new Map()
342
+ const inFlight = new Map()
343
+ let lookupId = 0
344
+
345
+ const tools = readOnly
346
+ ? CATALOG_TOOLS.filter((tool) => tool.name !== 'call-write-tool')
347
+ : CATALOG_TOOLS
348
+ const writesWithheld = (graphId) => readOnly || isGraphReadOnly(graphId, graphSet)
349
+
350
+ const deliver = (message) => output.write(JSON.stringify(message) + '\n')
351
+
352
+ const headers = () => ({
353
+ 'Content-Type': 'application/json',
354
+ Accept: 'application/json, text/event-stream',
355
+ 'User-Agent': `robosystems-mcp/${version}`,
356
+ 'X-MCP-Client': version,
357
+ 'X-API-Key': apiKey,
358
+ })
359
+
360
+ const httpFailure = async (response) => {
361
+ const body = await response.text().catch(() => '')
362
+ let detail = body.slice(0, ERROR_BODY_PREVIEW_CHARS)
363
+ try {
364
+ const parsed = JSON.parse(body)
365
+ const message = parsed?.error?.message ?? parsed?.detail
366
+ if (message) detail = typeof message === 'string' ? message : JSON.stringify(message)
367
+ } catch {
368
+ // Not JSON: keep the preview.
369
+ }
370
+ return new UpstreamError(`HTTP ${response.status}${detail ? `: ${detail}` : ''}`)
371
+ }
372
+
373
+ const withTimeout = (signal) => {
374
+ const timeout = AbortSignal.timeout(LOOKUP_TIMEOUT_MS)
375
+ return signal ? AbortSignal.any([signal, timeout]) : timeout
376
+ }
377
+
378
+ /** POST one JSON-RPC message to a graph and hand each reply to onMessage. */
379
+ const post = async (graphId, message, onMessage, signal) => {
380
+ const response = await fetchImpl(`${apiBase}/v1/graphs/${graphId}/mcp`, {
381
+ method: 'POST',
382
+ headers: headers(),
383
+ body: JSON.stringify(message),
384
+ ...(signal ? { signal } : {}),
385
+ })
386
+ if (!response.ok) throw await httpFailure(response)
387
+ const contentType = response.headers.get('content-type') || ''
388
+ if (contentType.includes('text/event-stream')) {
389
+ await relaySSE(response.body, onMessage)
390
+ } else {
391
+ const text = await response.text()
392
+ if (text.trim()) onMessage(JSON.parse(text))
393
+ }
394
+ }
395
+
396
+ /** A request the bridge makes on its own account; returns the result. */
397
+ const lookup = async (graphId, method, params, signal) => {
398
+ const id = `catalog-${++lookupId}`
399
+ let reply = null
400
+ await post(
401
+ graphId,
402
+ { jsonrpc: '2.0', id, method, ...(params ? { params } : {}) },
403
+ (message) => {
404
+ if (message?.id === id) reply = message
405
+ },
406
+ withTimeout(signal)
407
+ )
408
+ if (!reply) throw new UpstreamError(`No reply to ${method}`)
409
+ if (reply.error) throw new UpstreamError(reply.error.message || `${method} failed`)
410
+ return reply.result
411
+ }
412
+
413
+ const cached = async (cache, graphId, load) => {
414
+ const hit = cache.get(graphId)
415
+ if (hit && now() - hit.at < CACHE_TTL_MS) return hit.value
416
+ const value = await load()
417
+ cache.set(graphId, { at: now(), value })
418
+ return value
419
+ }
420
+
421
+ const toolsOf = (graphId, signal) =>
422
+ cached(
423
+ toolCache,
424
+ graphId,
425
+ async () => (await lookup(graphId, 'tools/list', undefined, signal)).tools || []
426
+ )
427
+
428
+ const instructionsOf = (graphId, signal) =>
429
+ cached(instructionCache, graphId, async () => {
430
+ try {
431
+ const result = await lookup(
432
+ graphId,
433
+ 'initialize',
434
+ {
435
+ protocolVersion: PROTOCOL_VERSION,
436
+ capabilities: {},
437
+ clientInfo: { name: 'robosystems-mcp', version },
438
+ },
439
+ signal
440
+ )
441
+ return result?.instructions || null
442
+ } catch {
443
+ // Instructions are guidance; a graph without them is still usable.
444
+ return null
445
+ }
446
+ })
447
+
448
+ const listGraphs = async (signal) => {
449
+ let listed = null
450
+ let listingError = null
451
+ try {
452
+ const response = await fetchImpl(`${apiBase}/v1/graphs`, {
453
+ headers: headers(),
454
+ signal: withTimeout(signal),
455
+ })
456
+ if (!response.ok) throw await httpFailure(response)
457
+ listed = (await response.json()).graphs || []
458
+ } catch (error) {
459
+ listingError = error.message
460
+ }
461
+
462
+ if (!listed && !graphSet) {
463
+ return textResult(
464
+ `Could not list graphs (${listingError}). A key scoped to one graph cannot list the ` +
465
+ 'account: set ROBOSYSTEMS_GRAPH_IDS to the graphs this connection should reach.',
466
+ true
467
+ )
468
+ }
469
+
470
+ const aliasOf = new Map((graphSet?.entries || []).map((e) => [e.id, e.alias]))
471
+ const inScope = (graph) =>
472
+ !graphSet || graphSet.ids.has(graph.graphId) || graphSet.ids.has(graph.parentGraphId)
473
+
474
+ const subgraphCount = new Map()
475
+ for (const graph of listed || []) {
476
+ if (!graph.parentGraphId) continue
477
+ subgraphCount.set(graph.parentGraphId, (subgraphCount.get(graph.parentGraphId) || 0) + 1)
478
+ }
479
+
480
+ const graphs = (listed || []).filter(inScope).map((graph) => {
481
+ const row = { graph: graph.graphId }
482
+ if (aliasOf.get(graph.graphId)) row.alias = aliasOf.get(graph.graphId)
483
+ if (graph.graphName) row.name = graph.graphName
484
+ if (graph.description && graph.description !== graph.graphName) {
485
+ row.description = graph.description
486
+ }
487
+ if (graph.graphType) row.type = graph.graphType
488
+ if (graph.schemaExtensions?.length) row.extensions = graph.schemaExtensions
489
+ if (graph.repositoryType) row.repository = graph.repositoryType
490
+ if (graph.parentGraphId) row.parent = graph.parentGraphId
491
+ if (subgraphCount.get(graph.graphId)) row.subgraphs = subgraphCount.get(graph.graphId)
492
+ if (graph.role) row.role = graph.role
493
+ if (graph.status) row.status = graph.status
494
+ if (writesWithheld(graph.graphId)) row.read_only = true
495
+ return row
496
+ })
497
+
498
+ const seen = new Set(graphs.map((row) => row.graph))
499
+ for (const entry of graphSet?.entries || []) {
500
+ if (seen.has(entry.id)) continue
501
+ const row = { graph: entry.id }
502
+ if (entry.alias) row.alias = entry.alias
503
+ if (writesWithheld(entry.id)) row.read_only = true
504
+ row.note = listed
505
+ ? 'Configured for this connection; not in the account listing'
506
+ : 'Configured for this connection'
507
+ graphs.push(row)
508
+ }
509
+
510
+ return jsonResult({
511
+ graphs,
512
+ scope: graphSet ? 'the configured graphs and their subgraphs' : 'every graph the key reaches',
513
+ next: 'Pass `graph` (the alias when there is one) to `get-tools`.',
514
+ })
515
+ }
516
+
517
+ const getTools = async (graphId, args, signal) => {
518
+ const served = await toolsOf(graphId, signal)
519
+ const withheld = writesWithheld(graphId)
520
+ const tools = withheld ? served.filter(isReadTool) : served
521
+
522
+ if (Array.isArray(args.names) && args.names.length > 0) {
523
+ const names = args.names.slice(0, MAX_DEFINITIONS)
524
+ const byName = new Map(tools.map((tool) => [tool.name, tool]))
525
+ const servedNames = new Set(served.map((tool) => tool.name))
526
+ const found = names.filter((name) => byName.has(name)).map((name) => byName.get(name))
527
+ const unknown = names.filter((name) => !servedNames.has(name))
528
+ const writes = names.filter((name) => servedNames.has(name) && !byName.has(name))
529
+ const payload = {
530
+ graph: graphId,
531
+ tools: found.map((tool) => ({
532
+ name: tool.name,
533
+ call_with: isReadTool(tool) ? 'call-read-tool' : 'call-write-tool',
534
+ description: tool.description,
535
+ inputSchema: tool.inputSchema,
536
+ })),
537
+ }
538
+ if (unknown.length) payload.not_on_this_graph = unknown
539
+ if (writes.length) payload.withheld_read_only = writes
540
+ if (args.names.length > MAX_DEFINITIONS) {
541
+ payload.omitted = args.names.slice(MAX_DEFINITIONS)
542
+ }
543
+ return jsonResult(payload)
544
+ }
545
+
546
+ const query = typeof args.query === 'string' ? args.query.trim() : ''
547
+ const listed = query ? searchTools(tools, query) : tools
548
+ const row = (tool) => ({ name: tool.name, summary: summarize(tool.description) })
549
+ const payload = {
550
+ graph: graphId,
551
+ tool_count: tools.length,
552
+ read_tools: listed.filter(isReadTool).map(row),
553
+ write_tools: listed.filter((tool) => !isReadTool(tool)).map(row),
554
+ next: 'Call `get-tools` with `names` for the full definition before calling a tool.',
555
+ }
556
+ if (withheld) {
557
+ delete payload.write_tools
558
+ payload.read_only = true
559
+ payload.write_tools_withheld = served.length - tools.length
560
+ }
561
+ if (query) {
562
+ payload.query = query
563
+ } else {
564
+ const instructions = await instructionsOf(graphId, signal)
565
+ if (instructions) payload.instructions = instructions
566
+ }
567
+ return jsonResult(payload)
568
+ }
569
+
570
+ /** Forward one tool call to its graph and relay everything it sends back. */
571
+ const callTool = async (message, graphId, args, wantRead, signal) => {
572
+ if (typeof args.name !== 'string' || !args.name) {
573
+ return textResult('`name` is required: the tool to run, from `get-tools`', true)
574
+ }
575
+ if (!wantRead && writesWithheld(graphId)) {
576
+ return textResult(`Graph ${graphId} is read-only on this connection.`, true)
577
+ }
578
+ const tool = (await toolsOf(graphId, signal)).find((t) => t.name === args.name)
579
+ if (!tool) {
580
+ return textResult(
581
+ `Graph ${graphId} has no tool named "${args.name}". ` +
582
+ 'Call `get-tools` with this graph for the tools it serves.',
583
+ true
584
+ )
585
+ }
586
+ if (isReadTool(tool) !== wantRead) {
587
+ if (wantRead && writesWithheld(graphId)) {
588
+ return textResult(
589
+ `"${args.name}" is a write tool, and graph ${graphId} is read-only on this connection.`,
590
+ true
591
+ )
592
+ }
593
+ return textResult(
594
+ wantRead
595
+ ? `"${args.name}" is a write tool: call it with \`call-write-tool\`.`
596
+ : `"${args.name}" is a read tool: call it with \`call-read-tool\`.`,
597
+ true
598
+ )
599
+ }
600
+
601
+ const params = { name: args.name, arguments: args.arguments ?? {} }
602
+ if (message.params._meta) params._meta = message.params._meta
603
+
604
+ // The host's own request id travels upstream, so the reply and any
605
+ // progress notifications relay back without rewriting.
606
+ let answered = false
607
+ try {
608
+ await post(
609
+ graphId,
610
+ { jsonrpc: '2.0', id: message.id, method: 'tools/call', params },
611
+ (reply) => {
612
+ if (reply && reply.id === message.id && reply.method === undefined) answered = true
613
+ deliver(reply)
614
+ },
615
+ signal
616
+ )
617
+ } catch (error) {
618
+ // A stream that broke after the result arrived has nothing left to say.
619
+ if (!answered) throw error
620
+ }
621
+ if (!answered) throw new UpstreamError('The graph sent no result for this call')
622
+ return null
623
+ }
624
+
625
+ const handleToolCall = async (message, signal) => {
626
+ const { name, arguments: rawArgs } = message.params
627
+ const args = rawArgs && typeof rawArgs === 'object' ? rawArgs : {}
628
+ if (readOnly && name === 'call-write-tool') {
629
+ return textResult('This connection is read-only: no write tool can be called.', true)
630
+ }
631
+ if (!tools.some((tool) => tool.name === name)) {
632
+ return textResult(
633
+ `Unknown tool: ${name}. A graph’s own tools run through \`call-read-tool\` or ` +
634
+ '`call-write-tool`.',
635
+ true
636
+ )
637
+ }
638
+ try {
639
+ if (name === 'list-graphs') return await listGraphs(signal)
640
+ const graphId = resolveGraph(args.graph, graphSet)
641
+ if (name === 'get-tools') return await getTools(graphId, args, signal)
642
+ return await callTool(message, graphId, args, name === 'call-read-tool', signal)
643
+ } catch (error) {
644
+ return textResult(error.message, true)
645
+ }
646
+ }
647
+
648
+ const handleLine = async (line) => {
649
+ const raw = line.trim()
650
+ if (!raw) return
651
+
652
+ let message
653
+ try {
654
+ message = JSON.parse(raw)
655
+ } catch {
656
+ deliver({
657
+ jsonrpc: '2.0',
658
+ id: null,
659
+ error: { code: JSONRPC_PARSE_ERROR, message: 'Parse error' },
660
+ })
661
+ return
662
+ }
663
+
664
+ // A cancelled call stops its upstream request and is never answered.
665
+ if (message?.method === 'notifications/cancelled') {
666
+ inFlight.get(message.params?.requestId)?.abort()
667
+ return
668
+ }
669
+
670
+ // Other notifications and client responses need no answer and have nowhere to go.
671
+ if (!message || typeof message.method !== 'string' || message.id === undefined) return
672
+
673
+ const respond = (result) => deliver({ jsonrpc: '2.0', id: message.id, result })
674
+ const fail = (code, text) =>
675
+ deliver({ jsonrpc: '2.0', id: message.id, error: { code, message: text } })
676
+
677
+ if (message.method === 'initialize') {
678
+ respond({
679
+ protocolVersion: PROTOCOL_VERSION,
680
+ capabilities: { tools: { listChanged: false } },
681
+ serverInfo: { name: 'robosystems', title: 'RoboSystems', version },
682
+ instructions: buildInstructions(graphSet, readOnly),
683
+ })
684
+ } else if (message.method === 'ping') {
685
+ respond({})
686
+ } else if (message.method === 'tools/list') {
687
+ respond({ tools })
688
+ } else if (message.method === 'tools/call') {
689
+ if (!message.params || typeof message.params.name !== 'string') {
690
+ fail(JSONRPC_INVALID_PARAMS, 'Invalid params: expected a tool name')
691
+ return
692
+ }
693
+ const controller = new AbortController()
694
+ inFlight.set(message.id, controller)
695
+ try {
696
+ const result = await handleToolCall(message, controller.signal)
697
+ if (result && !controller.signal.aborted) respond(result)
698
+ } finally {
699
+ inFlight.delete(message.id)
700
+ }
701
+ } else {
702
+ fail(JSONRPC_METHOD_NOT_FOUND, `Method not found: ${message.method}`)
703
+ }
704
+ }
705
+
706
+ return { handleLine }
707
+ }
708
+
709
+ /**
710
+ * Run the catalog over real stdio until the host closes stdin.
711
+ */
712
+ export async function runCatalog({
713
+ baseUrl,
714
+ apiKey,
715
+ version,
716
+ graphSet = null,
717
+ readOnly = false,
718
+ input = process.stdin,
719
+ output = process.stdout,
720
+ fetchImpl = fetch,
721
+ }) {
722
+ const catalog = createCatalog({
723
+ baseUrl,
724
+ apiKey,
725
+ version,
726
+ graphSet,
727
+ readOnly,
728
+ output,
729
+ fetchImpl,
730
+ })
731
+
732
+ console.error(`RoboSystems MCP catalog v${version}`)
733
+ console.error(
734
+ graphSet
735
+ ? `Graphs: ${graphSet.entries
736
+ .map((e) => `${e.alias || e.id}${e.readOnly ? ' (read-only)' : ''}`)
737
+ .join(', ')} (and their subgraphs)`
738
+ : 'Graphs: every graph the API key reaches'
739
+ )
740
+ if (readOnly) console.error('Read-only: write tools are withheld')
741
+
742
+ const pending = new Set()
743
+ const rl = createInterface({ input, terminal: false })
744
+
745
+ rl.on('line', (line) => {
746
+ const task = catalog
747
+ .handleLine(line)
748
+ .catch((error) => console.error(`Catalog error: ${error.message}`))
749
+ .finally(() => pending.delete(task))
750
+ pending.add(task)
751
+ })
752
+
753
+ await new Promise((resolve) => rl.on('close', resolve))
754
+ await Promise.allSettled([...pending])
755
+ }
package/index.js CHANGED
@@ -1,24 +1,25 @@
1
1
  #!/usr/bin/env node
2
2
 
3
3
  /**
4
- * RoboSystems MCP stdio proxy.
4
+ * RoboSystems MCP stdio bridge.
5
5
  *
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.
6
+ * Two modes, chosen by the environment:
12
7
  *
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.
8
+ * - Proxy (ROBOSYSTEMS_GRAPH_ID or ROBOSYSTEMS_MCP_URL set): a transparent
9
+ * pipe between a stdio MCP client and one graph's MCP endpoint (Streamable
10
+ * HTTP). Every JSON-RPC message is forwarded verbatim with the API-key
11
+ * header attached; the bridge adds nothing of its own.
12
+ * - Catalog (neither set): one connection for every graph the API key
13
+ * reaches. Four fixed tools take the graph as an argument and forward to
14
+ * that graph's endpoint, so a subgraph is usable the moment it exists.
15
+ * ROBOSYSTEMS_READ_ONLY withholds the write tool.
16
16
  */
17
17
 
18
18
  import { readFileSync } from 'fs'
19
19
  import { fileURLToPath } from 'url'
20
20
  import { dirname, join } from 'path'
21
21
  import { runProxy } from './proxy.js'
22
+ import { parseGraphSet, runCatalog } from './catalog.js'
22
23
 
23
24
  // Get package version dynamically
24
25
  const __filename = fileURLToPath(import.meta.url)
@@ -85,23 +86,56 @@ export function resolveEndpoint({ baseUrl, graphId, mcpUrl }) {
85
86
  return `${(baseUrl || 'https://api.robosystems.ai').replace(/\/$/, '')}/v1/graphs/${graphId}/mcp`
86
87
  }
87
88
 
89
+ /** A flag is on for `true`, `1` or `yes`, in any case. */
90
+ export function isEnabled(value) {
91
+ return ['true', '1', 'yes'].includes(
92
+ String(value ?? '')
93
+ .trim()
94
+ .toLowerCase()
95
+ )
96
+ }
97
+
88
98
  async function main() {
99
+ const apiKey = process.env.ROBOSYSTEMS_API_KEY
89
100
  const url = resolveEndpoint({
90
101
  baseUrl: process.env.ROBOSYSTEMS_API_URL,
91
102
  graphId: process.env.ROBOSYSTEMS_GRAPH_ID,
92
103
  mcpUrl: process.env.ROBOSYSTEMS_MCP_URL,
93
104
  })
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')
105
+
106
+ if (url) {
107
+ if (process.env.ROBOSYSTEMS_GRAPH_IDS) {
108
+ console.error(
109
+ 'ROBOSYSTEMS_GRAPH_IDS is ignored: ROBOSYSTEMS_GRAPH_ID or ROBOSYSTEMS_MCP_URL ' +
110
+ 'selects the single-graph proxy'
111
+ )
112
+ }
113
+ void checkForUpdate() // fire-and-forget stale-version warning (stderr only)
114
+ await runProxy({ url, apiKey, version: PACKAGE_VERSION })
115
+ return
116
+ }
117
+
118
+ if (!apiKey) {
119
+ console.error('ROBOSYSTEMS_API_KEY is required')
120
+ console.error(
121
+ 'Set it alone to reach every graph the key covers, or with ROBOSYSTEMS_GRAPH_ID ' +
122
+ 'to connect one graph'
123
+ )
97
124
  process.exit(1)
98
125
  }
99
126
 
100
- void checkForUpdate() // fire-and-forget stale-version warning (stderr only)
101
- await runProxy({ url, apiKey: process.env.ROBOSYSTEMS_API_KEY, version: PACKAGE_VERSION })
127
+ const graphSet = parseGraphSet(process.env.ROBOSYSTEMS_GRAPH_IDS)
128
+ void checkForUpdate()
129
+ await runCatalog({
130
+ baseUrl: process.env.ROBOSYSTEMS_API_URL,
131
+ apiKey,
132
+ version: PACKAGE_VERSION,
133
+ graphSet,
134
+ readOnly: isEnabled(process.env.ROBOSYSTEMS_READ_ONLY),
135
+ })
102
136
  }
103
137
 
104
- // Only run as the proxy if this is the main module (works for `node index.js`
138
+ // Only run as the bridge if this is the main module (works for `node index.js`
105
139
  // and the npx binary names); never under the test runner.
106
140
  const isMainModule =
107
141
  import.meta.url === `file://${process.argv[1]}` ||
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "@robosystems/mcp",
3
- "version": "0.5.5",
4
- "description": "MCP stdio bridge for RoboSystems, the open-source knowledge graph for finance; proxies to the hosted endpoint by default",
3
+ "version": "1.0.0",
4
+ "description": "MCP stdio bridge for RoboSystems, the open-source knowledge graph for finance; one connection for every graph an API key reaches",
5
5
  "type": "module",
6
6
  "main": "index.js",
7
7
  "bin": {
8
- "@robosystems/mcp": "./index.js",
9
- "create-feature": "./bin/create-feature.sh"
8
+ "@robosystems/mcp": "./index.js"
10
9
  },
11
10
  "files": [
12
11
  "index.js",
13
12
  "proxy.js",
13
+ "catalog.js",
14
14
  "README.md",
15
15
  "LICENSE"
16
16
  ],
@@ -49,7 +49,7 @@
49
49
  "vitest": "^4.0.3"
50
50
  },
51
51
  "engines": {
52
- "node": ">=18.0.0"
52
+ "node": ">=22.0.0"
53
53
  },
54
54
  "publishConfig": {
55
55
  "access": "public"
package/proxy.js CHANGED
@@ -24,7 +24,7 @@ const ERROR_BODY_PREVIEW_CHARS = 300
24
24
  * (keepalive) lines. `event:`/`id:`/`retry:` fields carry no JSON-RPC content
25
25
  * on this endpoint and are skipped.
26
26
  */
27
- async function relaySSE(body, deliver) {
27
+ export async function relaySSE(body, deliver) {
28
28
  const reader = body.getReader()
29
29
  const decoder = new TextDecoder()
30
30
  let buffer = ''
@@ -1,106 +0,0 @@
1
- #!/bin/bash
2
- set -e
3
-
4
- # Create feature branch script - local Git operations
5
- # Creates a new feature/bugfix/hotfix branch locally and pushes to remote
6
- # Usage: ./bin/create-feature.sh [feature|bugfix|hotfix|chore|refactor] [branch-name] [base-branch] [update-deps]
7
-
8
- # Default values
9
- BRANCH_TYPE=${1:-feature}
10
- BRANCH_NAME=${2:-}
11
- BASE_BRANCH=${3:-main}
12
- UPDATE_DEPS=${4:-no}
13
-
14
- # Validate branch type
15
- if [[ "$BRANCH_TYPE" != "feature" && "$BRANCH_TYPE" != "bugfix" && "$BRANCH_TYPE" != "hotfix" && "$BRANCH_TYPE" != "chore" && "$BRANCH_TYPE" != "refactor" ]]; then
16
- echo "❌ Invalid branch type: $BRANCH_TYPE"
17
- echo "Valid types: feature, bugfix, hotfix, chore, refactor"
18
- exit 1
19
- fi
20
-
21
- # Check if branch name was provided
22
- if [ -z "$BRANCH_NAME" ]; then
23
- echo "❌ Branch name is required"
24
- echo "Usage: $0 [type] [name] [base_branch]"
25
- echo "Example: $0 feature add-user-auth main"
26
- exit 1
27
- fi
28
-
29
- # Sanitize branch name
30
- SANITIZED_NAME=$(echo "$BRANCH_NAME" | sed 's/[^a-zA-Z0-9._-]/-/g' | sed 's/--*/-/g' | sed 's/^-//;s/-$//')
31
- FULL_BRANCH="${BRANCH_TYPE}/${SANITIZED_NAME}"
32
-
33
- echo "🚀 Creating feature branch locally..."
34
- echo "📋 Details:"
35
- echo " Type: $BRANCH_TYPE"
36
- echo " Name: $SANITIZED_NAME"
37
- echo " Full Branch: $FULL_BRANCH"
38
- echo " Base Branch: $BASE_BRANCH"
39
- echo ""
40
-
41
- # Check for uncommitted changes
42
- if ! git diff --quiet || ! git diff --cached --quiet; then
43
- echo "⚠️ You have uncommitted changes. Auto-stashing..."
44
- git stash push -m "Auto-stash before creating branch $FULL_BRANCH"
45
- echo "✅ Changes stashed"
46
- fi
47
-
48
- # Fetch latest changes from remote
49
- echo "📥 Fetching latest changes from remote..."
50
- git fetch origin
51
-
52
- # Check if branch already exists (local or remote)
53
- if git show-ref --verify --quiet refs/heads/$FULL_BRANCH; then
54
- echo "❌ Branch $FULL_BRANCH already exists locally"
55
- exit 1
56
- fi
57
-
58
- if git show-ref --verify --quiet refs/remotes/origin/$FULL_BRANCH; then
59
- echo "❌ Branch $FULL_BRANCH already exists on remote"
60
- echo "💡 To check it out: git checkout -b $FULL_BRANCH origin/$FULL_BRANCH"
61
- exit 1
62
- fi
63
-
64
- # Check if base branch exists on remote
65
- if ! git show-ref --verify --quiet refs/remotes/origin/$BASE_BRANCH; then
66
- echo "❌ Base branch $BASE_BRANCH does not exist on remote"
67
- echo "💡 Available branches:"
68
- git branch -r | grep -v HEAD | sed 's/origin\///' | head -10
69
- exit 1
70
- fi
71
-
72
- # Create and checkout the new branch from the base branch
73
- echo "🔨 Creating branch $FULL_BRANCH from origin/$BASE_BRANCH..."
74
- git checkout -b $FULL_BRANCH origin/$BASE_BRANCH
75
-
76
- # Push the new branch to remote with upstream tracking
77
- echo "📤 Pushing branch to remote..."
78
- git push -u origin $FULL_BRANCH
79
-
80
- echo ""
81
- echo "🎉 Successfully created and checked out $FULL_BRANCH"
82
-
83
- # Update dependencies only when explicitly requested (default: no).
84
- # Pass "yes" as the 4th arg to refresh deps on the new branch; otherwise
85
- # branch creation leaves the lockfile untouched.
86
- if [[ "$UPDATE_DEPS" == "yes" ]]; then
87
- echo ""
88
- echo "📦 Updating dependencies..."
89
- npm update
90
- echo "✅ Dependencies updated"
91
- fi
92
-
93
- echo ""
94
- echo "📝 Next steps:"
95
- echo " 1. Make your changes and commit them"
96
- echo " 2. Push your changes: git push"
97
- echo " 3. Create a PR: gh pr create --base $BASE_BRANCH --title \"Your PR title\" --body \"Your PR description\""
98
- echo " or in a Claude Code session: /create-pr"
99
-
100
- # Check if we had stashed changes and auto-apply them
101
- if git stash list | grep -q "Auto-stash before creating branch $FULL_BRANCH"; then
102
- echo ""
103
- echo "Auto-applying stashed changes..."
104
- git stash pop
105
- echo "✅ Stashed changes applied"
106
- fi