@kartha-energy/feederline-mcp 0.0.0-stage → 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md CHANGED
@@ -1,3 +1,173 @@
1
- # Temporary Holding Version
1
+ # feederline-mcp
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Model Context Protocol (MCP) server for distribution power grid simulation, DER hosting capacity, and power flow analysis (powered by OpenDSS)
4
+
5
+ A CIM (IEC 61970-301) operational data store on PostgreSQL + PostGIS + pgRouting, plus a Model Context Protocol
6
+ server that compiles any distribution feeder from it into an in-process OpenDSS circuit, so AI agents such as Claude
7
+ can run power-flow, hosting-capacity, voltage, fault and time-series studies on a utility network model.
8
+
9
+ > **Public data only.** The local stack is for public datasets (IEEE test feeders, NREL SMART-DS, HIFLD-schema
10
+ > mirrors). Real utility network models and loading are CEII (Critical Energy/Electric Infrastructure Information)
11
+ > and must not be loaded into it.
12
+
13
+ ## Quick start
14
+
15
+ You need **Docker** (Docker Desktop or Docker Engine with Compose v2) and **Node.js 18+**. Nothing else is installed on
16
+ the host: Postgres, PostGIS, pgRouting, OpenDSS and Python all run in containers.
17
+
18
+ ```bash
19
+ npx -y @kartha-energy/feederline-mcp up # pull images, start Postgres + server, migrate, load IEEE 13/34/123, seed demo telemetry
20
+ npx -y @kartha-energy/feederline-mcp config # print the Claude Desktop and Claude Code connection settings
21
+ ```
22
+
23
+ The server listens on `127.0.0.1` only, with a random bearer token generated on first run and kept in
24
+ `~/.feederline-mcp/config.json`.
25
+
26
+ ### Connect Claude Desktop
27
+
28
+ Add this to `claude_desktop_config.json` (macOS: `~/Library/Application Support/Claude/`, Windows: `%APPDATA%\Claude\`),
29
+ or run `npx -y @kartha-energy/feederline-mcp config --write-desktop`, which merges it in after writing a backup:
30
+
31
+ ```json
32
+ {
33
+ "mcpServers": {
34
+ "feederline-mcp": {
35
+ "command": "npx",
36
+ "args": ["-y", "@kartha-energy/feederline-mcp", "connect"]
37
+ }
38
+ }
39
+ }
40
+ ```
41
+
42
+ Restart Claude Desktop; the 34 tools appear in the tools menu. `connect` is a stdio bridge to the local server: it
43
+ reads the token from `~/.feederline-mcp/config.json` and starts the stack if it isn't running.
44
+
45
+ ### Connect Claude Code
46
+
47
+ ```bash
48
+ claude mcp add --transport http feederline-mcp http://127.0.0.1:8000/mcp \
49
+ --header "Authorization: Bearer <token from: npx -y @kartha-energy/feederline-mcp config>"
50
+ ```
51
+
52
+ Notes:
53
+
54
+ - The "custom connector" screen in Claude apps is for servers reachable over public HTTPS. For this local server, use
55
+ the config file above.
56
+ - One Claude chat is one MCP session. A new chat starts with no feeder loaded, so call `load_feeder` again.
57
+ - Without the bridge, the community `mcp-remote` package works too; `config` prints that variant with your token.
58
+
59
+ ## What you can ask
60
+
61
+ The [Claude playbook](https://github.com/Kartha-AI/feederline-mcp/blob/main/docs/playbook.md) is a 13-lesson learning path for Claude Desktop: concepts, prompts to type,
62
+ what to look for in each answer, a prompt cheat sheet and a self-check quiz. A few prompts from it:
63
+
64
+ - "List the feeders available, with region, substation and nominal voltage."
65
+ - "Load the IEEE 123 feeder and run a power flow. What are the losses and the lowest voltage?"
66
+ - "Which buses on IEEE 123 are outside 0.95–1.05 pu? Show the worst ten."
67
+ - "What is the PV hosting capacity at bus 76 on IEEE 123, and which constraint binds first?"
68
+ - "What was the peak load at the IEEE 123 feeder head over the last 7 days, and when did it occur?"
69
+
70
+ ## Tools
71
+
72
+ 34 MCP tools in two families, every result in the same envelope (`success`, `data`, `model`, `warnings`, `errors`, `meta`):
73
+
74
+ - **Engine** (need `load_feeder` first): `load_feeder`, `run_power_flow`, `check_voltages`, `analyze_capacity`,
75
+ `optimize_der`, `run_timeseries`, `create_visualization`, `set_control`, `compare_cases`, `fault_study`,
76
+ `phase_balance`, `losses_by_segment`, `line_loading`, `regulator_status`.
77
+ - **SQL** (straight from Postgres, no session): lookup (`search_equipment`, `describe_equipment`), topology
78
+ (`trace_downstream`, `trace_upstream`, `find_path`, `isolate`, `tie_options`, `connectivity_report`), spatial
79
+ (`equipment_near`, `nearest_substation`, `affected_by_area`, `feeder_geometry`), telemetry (`latest_readings`,
80
+ `measurement_history`, `load_profile`, `peak_load`, `limit_exceedances`, `telemetry_quality`), governance
81
+ (`model_changes`, `validate_feeder`).
82
+
83
+ Results name their shape in `data.viz` (`map`, `tree`, `path`, `timeseries`, `table`, `profile`) so a client can draw
84
+ them directly. Large results are capped and point at a `grid://` resource holding the rest. Each tool's MCP
85
+ description (its docstring) states its inputs, outputs and units.
86
+
87
+ No tool writes to the network model, switch states or telemetry. `set_control` changes only the in-memory circuit of
88
+ your session.
89
+
90
+ ## CLI
91
+
92
+ | Command | Does |
93
+ | --- | --- |
94
+ | `up [--ha] [--no-demo] [--smartds]` | Start the stack, migrate, load the IEEE feeders and 30 days of demo telemetry. Safe to rerun. |
95
+ | `down` / `reset` | Stop (keep data) / remove containers and data after confirmation |
96
+ | `status` | Containers, URL, feeders with root IDs, telemetry date range |
97
+ | `logs [service]` | Follow logs |
98
+ | `load ieee\|smartds\|hifld [...]` | Load a public dataset |
99
+ | `config [--write-desktop] [--claude-code]` | Connection settings |
100
+ | `connect` | stdio bridge for Claude Desktop |
101
+ | `inspect` | MCP Inspector against the local server |
102
+ | `doctor` | Check Node, Docker, Compose, ports, disk and registry access |
103
+
104
+ The IEEE root IDs are the same on every install (deterministic `uuid5` mRIDs):
105
+
106
+ | Feeder | Root ID |
107
+ | --- | --- |
108
+ | IEEE 13 | `c990acfa-4c84-5788-be92-53b20464fbd8` |
109
+ | IEEE 34 | `378451c2-afdb-524f-a587-9808c081df60` |
110
+ | IEEE 123 | `1dfeb41b-bf91-52f3-b6af-7b400b93c5b8` |
111
+
112
+ ## Data
113
+
114
+ | Command | Loads |
115
+ | --- | --- |
116
+ | `load ieee` (run by `up`) | IEEE 13/34/123 test feeders (vendored under `tests/fixtures/feeders`) |
117
+ | `load smartds --region P1R --substation p1rhs0_1247 [--date YYYY-MM-DD]` | An NREL SMART-DS substation downloaded from OEDI at run time (~7 MB, 17k nodes); `--date` also ingests that day's load profiles |
118
+ | `load hifld --state CA` | HIFLD-schema substations and transmission lines (transmission tier, 500 m snapping) |
119
+ | `make load-pecan FILE=... REGION=IEEE123` (from source) | Your own Pecan Street Dataport 15-minute export, scaled onto a region's consumers. No Pecan Street data is distributed. |
120
+
121
+ Demo telemetry is simulated (deterministic, seed 42) for the 30 days before install.
122
+
123
+ ## From source
124
+
125
+ Requires Docker, [uv](https://docs.astral.sh/uv/) and Python 3.12.
126
+
127
+ ```bash
128
+ make up # build images; postgres (127.0.0.1:5433), migrations, two MCP replicas behind nginx on :8000
129
+ make load-ieee # IEEE 13/34/123 -> CIM, SCADA registry, latest values, network_edges
130
+ make demo # 30 days of deterministic demo telemetry
131
+ make test # unit, contract, golden (0.1%), loaders, writer, auth/RLS, tools, rehydration, spatial, SQL tools
132
+ make inspect # MCP Inspector -> http://localhost:8000/mcp (Authorization: Bearer dev-token)
133
+ make ha-check # stop the replica holding a session; the other must serve it
134
+ make lint # ruff + import-linter (tools/ and compiler/ depend only on adapters/base.py)
135
+ ```
136
+
137
+ `PG_PORT=` and `MCP_PORT=` move the host ports. The from-source stack uses the static token `dev-token`; the npm
138
+ path never does.
139
+
140
+
141
+
142
+ ### Adapters
143
+
144
+ The server reads a `DataSource`, writes a `StudySink` and trusts an `Auth` (protocols in
145
+ `feederline_mcp/adapters/base.py`). Implementations are discovered through the Python entry-point group
146
+ `feederline_mcp.adapters` and selected with `FEEDERLINE_MCP_ADAPTER` (default `local`: one Postgres, the `studies`
147
+ schema, a static bearer token). Another backend ships as a separate package that registers its own entry point:
148
+
149
+ ```toml
150
+ [project.entry-points."feederline_mcp.adapters"]
151
+ mybackend = "my_package.adapter:build" # build(settings) -> (DataSource, StudySink, Auth)
152
+ ```
153
+
154
+ Any Postgres 16+ with PostGIS 3.4+ and pgRouting 3.4+ runs the schema. Sessions rehydrate on any replica from a
155
+ shared snapshot directory (`SNAPSHOT_DIR`).
156
+
157
+ ## Docs
158
+
159
+ | Document | What it covers |
160
+ | --- | --- |
161
+ | [docs/playbook.md](https://github.com/Kartha-AI/feederline-mcp/blob/main/docs/playbook.md) | Learning the grid with Claude Desktop: concepts, 13 lessons, cheat sheet, quiz |
162
+ | [tests/inspector.md](https://github.com/Kartha-AI/feederline-mcp/blob/main/tests/inspector.md) | Exploring every tool with the MCP Inspector, field by field |
163
+
164
+ ## Contributing, security, license
165
+
166
+ - [CONTRIBUTING.md](https://github.com/Kartha-AI/feederline-mcp/blob/main/CONTRIBUTING.md): DCO sign-off (`git commit -s`), running the tests, code rules.
167
+ - [SECURITY.md](https://github.com/Kartha-AI/feederline-mcp/blob/main/SECURITY.md): report vulnerabilities privately.
168
+ - [CODE_OF_CONDUCT.md](https://github.com/Kartha-AI/feederline-mcp/blob/main/CODE_OF_CONDUCT.md).
169
+ - Licensed under the [Apache License 2.0](https://github.com/Kartha-AI/feederline-mcp/blob/main/LICENSE). Third-party components and data: [NOTICE](https://github.com/Kartha-AI/feederline-mcp/blob/main/NOTICE).
170
+
171
+ ## Production and commercial support
172
+
173
+ For production deployments, other data platforms and support, see [kartha.energy](https://kartha.energy).
@@ -0,0 +1,18 @@
1
+ # Optional failover demo: `npx -y @kartha-energy/feederline-mcp up --ha`.
2
+ # A second replica and nginx hashing on Mcp-Session-Id; either replica rehydrates a session from the shared
3
+ # snapshot volume when the other stops.
4
+ services:
5
+ mcp:
6
+ ports: !reset []
7
+
8
+ mcp-b:
9
+ extends: { file: docker-compose.yml, service: mcp }
10
+ hostname: mcp-b
11
+ ports: !reset []
12
+
13
+ proxy:
14
+ image: nginx:1.27-alpine
15
+ volumes: ["./nginx.conf:/etc/nginx/conf.d/default.conf:ro"]
16
+ ports: ["127.0.0.1:${FEEDERLINE_MCP_PORT:-8000}:8000"]
17
+ depends_on: { mcp: { condition: service_healthy }, mcp-b: { condition: service_healthy } }
18
+ restart: unless-stopped
@@ -0,0 +1,52 @@
1
+ # feederline-mcp stack used by `npx -y @kartha-energy/feederline-mcp up`.
2
+ # Published images pinned to the npm package version; every port binds to 127.0.0.1 only.
3
+ # FEEDERLINE_IMAGE / FEEDERLINE_PG_IMAGE override the images (for testing locally built ones).
4
+ name: ${FEEDERLINE_PROJECT:-feederline-mcp}
5
+
6
+ services:
7
+ postgres:
8
+ image: ${FEEDERLINE_PG_IMAGE:-ghcr.io/kartha-ai/feederline-postgis:${FEEDERLINE_VERSION:?set by the CLI}}
9
+ environment: { POSTGRES_DB: grid, POSTGRES_USER: grid, POSTGRES_PASSWORD: grid }
10
+ ports: ["127.0.0.1:${FEEDERLINE_PG_PORT:-5433}:5432"]
11
+ volumes: ["feederline_pgdata:/var/lib/postgresql/data"]
12
+ healthcheck: { test: ["CMD-SHELL", "pg_isready -U grid -d grid"], interval: 3s, retries: 40 }
13
+ restart: unless-stopped
14
+
15
+ # One-shot administration: migrate, load, simulate, status. Run with `docker compose run --rm admin <args>`.
16
+ admin:
17
+ profiles: [admin]
18
+ image: ${FEEDERLINE_IMAGE:-ghcr.io/kartha-ai/feederline-mcp:${FEEDERLINE_VERSION:?set by the CLI}}
19
+ entrypoint: ["feederline-mcp-admin"]
20
+ environment:
21
+ ADMIN_DATABASE_URL: postgresql://grid:grid@postgres/grid
22
+ LOADER_DATABASE_URL: postgresql://grid_load:grid_load@postgres/grid
23
+ WRITER_DATABASE_URL: postgresql://grid_write:grid_write@postgres/grid
24
+ SMARTDS_DIR: /data/smartds
25
+ HISTORY_DIR: /data/parquet
26
+ volumes: ["feederline_data:/data"]
27
+ depends_on: { postgres: { condition: service_healthy } }
28
+
29
+ mcp:
30
+ image: ${FEEDERLINE_IMAGE:-ghcr.io/kartha-ai/feederline-mcp:${FEEDERLINE_VERSION:?set by the CLI}}
31
+ hostname: mcp
32
+ environment:
33
+ FEEDERLINE_MCP_ADAPTER: local
34
+ DATABASE_URL: postgresql://mcp:mcp@postgres/grid
35
+ MCP_BEARER_TOKEN: ${FEEDERLINE_MCP_TOKEN:?set by the CLI}
36
+ MCP_AUTH: "on"
37
+ MAX_CONTEXTS: "8"
38
+ HISTORY_DIR: /data/parquet
39
+ SNAPSHOT_DIR: /snapshots
40
+ ports: ["127.0.0.1:${FEEDERLINE_MCP_PORT:-8000}:8000"]
41
+ volumes: ["feederline_snapshots:/snapshots", "feederline_data:/data"]
42
+ healthcheck:
43
+ test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://localhost:8000/healthz')"]
44
+ interval: 3s
45
+ retries: 40
46
+ depends_on: { postgres: { condition: service_healthy } }
47
+ restart: unless-stopped
48
+
49
+ volumes:
50
+ feederline_pgdata: {}
51
+ feederline_snapshots: {}
52
+ feederline_data: {}
@@ -0,0 +1,26 @@
1
+ # SPDX-License-Identifier: Apache-2.0
2
+ # Two MCP replicas behind one endpoint. Requests hash on Mcp-Session-Id so a session normally stays on one
3
+ # replica; when that replica is down the request moves to the other, which rehydrates the session from the shared
4
+ # snapshot store. initialize carries no session id yet and may land on either replica.
5
+ upstream mcp {
6
+ hash $http_mcp_session_id consistent;
7
+ server mcp:8000 max_fails=1 fail_timeout=5s;
8
+ server mcp-b:8000 max_fails=1 fail_timeout=5s;
9
+ }
10
+
11
+ server {
12
+ listen 8000;
13
+
14
+ location / {
15
+ proxy_pass http://mcp;
16
+ proxy_http_version 1.1;
17
+ proxy_set_header Connection "";
18
+ proxy_set_header Host $host;
19
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
20
+ proxy_buffering off; # SSE responses stream through
21
+ proxy_read_timeout 300s;
22
+ proxy_next_upstream error timeout http_502 http_503 non_idempotent;
23
+ proxy_next_upstream_tries 2;
24
+ add_header X-Upstream $upstream_addr always;
25
+ }
26
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,64 @@
1
+ #!/usr/bin/env node
2
+ // SPDX-License-Identifier: Apache-2.0
3
+ import { Command } from "commander";
4
+ import { config, inspect } from "./commands/config.js";
5
+ import { connect } from "./commands/connect.js";
6
+ import { doctor } from "./commands/doctor.js";
7
+ import { down, load, logs, reset, status } from "./commands/stack.js";
8
+ import { up } from "./commands/up.js";
9
+ import { CliError } from "./log.js";
10
+ import { VERSION } from "./version.js";
11
+ const program = new Command();
12
+ program
13
+ .name("feederline-mcp")
14
+ .description("Run the feederline-mcp server (CIM grid model + OpenDSS studies over MCP) locally and connect Claude to it.")
15
+ .version(VERSION);
16
+ program
17
+ .command("up")
18
+ .description("start Postgres and the MCP server, migrate, load the IEEE feeders and seed 30 days of demo telemetry")
19
+ .option("--ha", "two server replicas behind nginx (failover demo)")
20
+ .option("--no-demo", "skip loading the IEEE feeders and demo telemetry")
21
+ .option("--smartds", "also load NREL SMART-DS P1R (about 7 MB download)")
22
+ .option("--no-pull", "use images already present locally")
23
+ .action(async (o) => void (await up(o)));
24
+ program.command("down").description("stop the containers (data volumes are kept)").action(down);
25
+ program
26
+ .command("reset")
27
+ .description("remove the containers and all data volumes (asks for confirmation)")
28
+ .option("-y, --yes", "skip the confirmation prompt")
29
+ .action(async (o) => reset(Boolean(o.yes)));
30
+ program
31
+ .command("status")
32
+ .description("container state, server URL, loaded feeders with root IDs, telemetry date range")
33
+ .option("--json", "machine-readable output")
34
+ .action(async (o) => status(Boolean(o.json)));
35
+ program.command("logs [service]").description("follow container logs (postgres, mcp)").action(logs);
36
+ program
37
+ .command("load <dataset> [args...]")
38
+ .description("load a public dataset: ieee | smartds [--region --substation --date] | hifld [--state]")
39
+ .allowUnknownOption(true)
40
+ .action(async (dataset, args) => load(dataset, args ?? []));
41
+ program
42
+ .command("config")
43
+ .description("print the Claude Desktop and Claude Code connection settings")
44
+ .option("--write-desktop", "merge the server into the Claude Desktop config (writes a backup first)")
45
+ .option("--claude-code", "print only the Claude Code command")
46
+ .action((o) => config(o));
47
+ program.command("connect").description("stdio bridge for Claude Desktop (used in claude_desktop_config.json)").action(connect);
48
+ program.command("inspect").description("open the MCP Inspector against the local server").action(inspect);
49
+ program
50
+ .command("doctor")
51
+ .description("check Node.js, Docker, Compose, ports, disk space and registry access")
52
+ .action(async () => {
53
+ if (!(await doctor()))
54
+ process.exitCode = 1;
55
+ });
56
+ program.parseAsync(process.argv).catch((e) => {
57
+ const err = e;
58
+ process.stderr.write(`error: ${err.message}\n`);
59
+ if (e instanceof CliError && e.fix)
60
+ process.stderr.write(`fix: ${e.fix}\n`);
61
+ else if (!(e instanceof CliError))
62
+ process.stderr.write(`${err.stack ?? ""}\n`);
63
+ process.exit(1);
64
+ });
@@ -0,0 +1,50 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { spawn } from "node:child_process";
3
+ import { bridgeEntry, claudeCodeCommand, desktopConfigPath, desktopSnippet, mcpRemoteEntry, writeDesktopConfig } from "../desktop.js";
4
+ import { CliError, out } from "../log.js";
5
+ import { endpoint } from "../state.js";
6
+ import { NPM_PACKAGE } from "../version.js";
7
+ import { requireState } from "./stack.js";
8
+ export function config(opts = {}) {
9
+ const state = requireState();
10
+ const { url, token } = endpoint(state);
11
+ if (opts.claudeCode) {
12
+ out(claudeCodeCommand(url, token));
13
+ return;
14
+ }
15
+ if (opts.writeDesktop) {
16
+ const { path, backup } = writeDesktopConfig(bridgeEntry());
17
+ out(`Added "feederline-mcp" to ${path}`);
18
+ if (backup)
19
+ out(`Backup of the previous file: ${backup}`);
20
+ out("Restart Claude Desktop; the feederline-mcp tools appear in the tools menu.");
21
+ return;
22
+ }
23
+ out(`Claude Desktop: add this to ${desktopConfigPath()}`);
24
+ out("(or run `npx -y " + NPM_PACKAGE + " config --write-desktop`), then restart Claude Desktop.");
25
+ out("");
26
+ out(desktopSnippet(bridgeEntry()));
27
+ out("");
28
+ out("Claude Code:");
29
+ out("");
30
+ out(` ${claudeCodeCommand(url, token)}`);
31
+ out("");
32
+ out("Without the bridge (community mcp-remote package):");
33
+ out("");
34
+ out(desktopSnippet(mcpRemoteEntry(url, token)));
35
+ out("");
36
+ out("One Claude chat is one MCP session: a new chat starts with no feeder loaded, so call load_feeder again.");
37
+ }
38
+ export async function inspect() {
39
+ const state = requireState();
40
+ const { url, token } = endpoint(state);
41
+ const args = ["-y", "@modelcontextprotocol/inspector", "--transport", "http", "--server-url", url, "--header", `Authorization: Bearer ${token}`];
42
+ const win = process.platform === "win32";
43
+ // On Windows npx is a .cmd shim that needs a shell; quote arguments containing spaces for it.
44
+ const argv = win ? args.map((a) => (/\s/.test(a) ? `"${a}"` : a)) : args;
45
+ await new Promise((resolve, reject) => {
46
+ const child = spawn(win ? "npx.cmd" : "npx", argv, { stdio: "inherit", shell: win });
47
+ child.on("error", (e) => reject(new CliError(`Could not start the MCP Inspector: ${e.message}`, "Check that npx works: npx --version")));
48
+ child.on("close", () => resolve());
49
+ });
50
+ }
@@ -0,0 +1,85 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // stdio <-> Streamable HTTP bridge for Claude Desktop. stdout carries only MCP protocol messages; every log line goes
3
+ // to stderr. One HTTP MCP session per bridge process, so one Claude chat keeps its loaded feeder.
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { StreamableHTTPClientTransport } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
6
+ import { getHealth, isHealthy, waitHealthy } from "../health.js";
7
+ import { CliError, enableProtocolMode, info } from "../log.js";
8
+ import { endpoint, readState } from "../state.js";
9
+ import { NPM_PACKAGE } from "../version.js";
10
+ import { up } from "./up.js";
11
+ const START_TIMEOUT_MS = 90_000;
12
+ function isRequest(m) {
13
+ return "method" in m && "id" in m && m.id !== undefined;
14
+ }
15
+ async function ensureServer() {
16
+ const state = readState();
17
+ const ep = endpoint(state);
18
+ if (ep.overridden)
19
+ return ep; // non-default setup: the user manages the server
20
+ if (isHealthy(await getHealth(ep.url)))
21
+ return ep;
22
+ info("feederline-mcp: server not running; starting it (up --no-demo)...");
23
+ const deadline = Date.now() + START_TIMEOUT_MS;
24
+ try {
25
+ const started = await Promise.race([
26
+ up({ demo: state ? false : true, pull: !state, quietNextSteps: true }),
27
+ new Promise((_, rej) => setTimeout(() => rej(new Error("timeout")), START_TIMEOUT_MS)),
28
+ ]);
29
+ const fresh = endpoint(started);
30
+ if (await waitHealthy(fresh.url, Math.max(1000, deadline - Date.now())))
31
+ return fresh;
32
+ }
33
+ catch (e) {
34
+ info(`feederline-mcp: ${e.message}`);
35
+ }
36
+ throw new CliError("feederline-mcp server is not running and could not be started.", `npx -y ${NPM_PACKAGE} up`);
37
+ }
38
+ export async function connect() {
39
+ enableProtocolMode();
40
+ const { url, token } = await ensureServer();
41
+ if (!token)
42
+ throw new CliError(`A server is running at ${url} but no access token was found (~/.feederline-mcp/config.json is created by \`up\`).`, `For the from-source stack (make up) set FEEDERLINE_MCP_TOKEN=dev-token in the client config; otherwise run: npx -y ${NPM_PACKAGE} up`);
43
+ const http = new StreamableHTTPClientTransport(new URL(url), {
44
+ requestInit: { headers: { Authorization: `Bearer ${token}` } },
45
+ });
46
+ const stdio = new StdioServerTransport();
47
+ let closing = false;
48
+ const shutdown = async (code = 0) => {
49
+ if (closing)
50
+ return;
51
+ closing = true;
52
+ await Promise.allSettled([http.close(), stdio.close()]);
53
+ process.exit(code);
54
+ };
55
+ http.onmessage = (msg) => {
56
+ // Record the negotiated protocol version so later HTTP requests carry MCP-Protocol-Version.
57
+ const result = msg.result;
58
+ if (result && typeof result.protocolVersion === "string")
59
+ http.setProtocolVersion(result.protocolVersion);
60
+ stdio.send(msg).catch((e) => info(`feederline-mcp: stdout write failed: ${e.message}`));
61
+ };
62
+ http.onerror = (e) => info(`feederline-mcp: ${e.message}`);
63
+ http.onclose = () => void shutdown(0);
64
+ stdio.onmessage = (msg) => {
65
+ http.send(msg).catch((e) => {
66
+ info(`feederline-mcp: request to ${url} failed: ${e.message}`);
67
+ if (isRequest(msg)) {
68
+ const reply = {
69
+ jsonrpc: "2.0",
70
+ id: msg.id,
71
+ error: { code: -32603, message: `feederline-mcp server unreachable at ${url}. Run: npx -y ${NPM_PACKAGE} up` },
72
+ };
73
+ stdio.send(reply).catch(() => undefined);
74
+ }
75
+ });
76
+ };
77
+ stdio.onerror = (e) => info(`feederline-mcp: ${e.message}`);
78
+ stdio.onclose = () => void shutdown(0);
79
+ process.stdin.on("end", () => void shutdown(0));
80
+ process.on("SIGINT", () => void shutdown(0));
81
+ process.on("SIGTERM", () => void shutdown(0));
82
+ await http.start();
83
+ await stdio.start();
84
+ info(`feederline-mcp: bridging stdio to ${url}`);
85
+ }
@@ -0,0 +1,81 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { statfsSync } from "node:fs";
3
+ import { createServer } from "node:net";
4
+ import { homedir } from "node:os";
5
+ import { detectCompose, dockerInstalled, dockerRunning } from "../docker.js";
6
+ import { getHealth } from "../health.js";
7
+ import { out } from "../log.js";
8
+ import { endpoint, readState, DEFAULT_MCP_PORT, DEFAULT_PG_PORT } from "../state.js";
9
+ function portFree(port) {
10
+ return new Promise((resolve) => {
11
+ const srv = createServer();
12
+ srv.once("error", () => resolve(false));
13
+ srv.once("listening", () => srv.close(() => resolve(true)));
14
+ srv.listen(port, "127.0.0.1");
15
+ });
16
+ }
17
+ async function registryReachable() {
18
+ const ctl = new AbortController();
19
+ const t = setTimeout(() => ctl.abort(), 5000);
20
+ try {
21
+ const res = await fetch("https://ghcr.io/v2/", { signal: ctl.signal });
22
+ return res.status === 401 || res.ok; // 401 = reachable, anonymous
23
+ }
24
+ catch {
25
+ return false;
26
+ }
27
+ finally {
28
+ clearTimeout(t);
29
+ }
30
+ }
31
+ export async function runChecks() {
32
+ const checks = [];
33
+ const major = Number.parseInt(process.versions.node.split(".")[0], 10);
34
+ checks.push({ name: "Node.js", ok: major >= 18, detail: `v${process.versions.node}`, fix: "Install Node.js 18 or newer from https://nodejs.org", critical: true });
35
+ const installed = dockerInstalled();
36
+ const running = installed && dockerRunning();
37
+ checks.push({
38
+ name: "Docker",
39
+ ok: running,
40
+ detail: !installed ? "not installed" : running ? "running" : "installed but not running",
41
+ fix: !installed ? "Install Docker Desktop (https://docs.docker.com/get-docker/)" : "Start Docker Desktop (or `sudo systemctl start docker`)",
42
+ critical: true,
43
+ });
44
+ const compose = running ? detectCompose() : null;
45
+ checks.push({ name: "Docker Compose (v2+)", ok: Boolean(compose), detail: compose ? compose.join(" ") : "not found", fix: "Update Docker Desktop, or install the compose plugin (https://docs.docker.com/compose/install/)", critical: true });
46
+ const state = readState();
47
+ const ours = await getHealth(endpoint(state).url, 1500); // our own server already holding the port is fine
48
+ for (const [label, port] of [["MCP port", state?.mcpPort ?? DEFAULT_MCP_PORT], ["Postgres port", state?.pgPort ?? DEFAULT_PG_PORT]]) {
49
+ const free = ours ? true : await portFree(port);
50
+ checks.push({
51
+ name: `${label} ${port}`,
52
+ ok: free,
53
+ detail: ours ? "in use by feederline-mcp" : free ? "free" : "in use by another program",
54
+ fix: label === "MCP port" ? "Free the port, or set FEEDERLINE_MCP_PORT=<port> and rerun `up`" : "Free the port, or set FEEDERLINE_PG_PORT=<port> and rerun `up`",
55
+ critical: true,
56
+ });
57
+ }
58
+ try {
59
+ const s = statfsSync(homedir());
60
+ const freeGb = (s.bavail * s.bsize) / 1e9;
61
+ checks.push({ name: "Disk space", ok: freeGb >= 3, detail: `${freeGb.toFixed(1)} GB free`, fix: "Free at least 3 GB (images ~1.5 GB plus data)", critical: false });
62
+ }
63
+ catch {
64
+ checks.push({ name: "Disk space", ok: true, detail: "not checked", critical: false });
65
+ }
66
+ const reach = await registryReachable();
67
+ checks.push({ name: "Image registry (ghcr.io)", ok: reach, detail: reach ? "reachable" : "unreachable", fix: "Check your network or proxy settings; images are pulled from ghcr.io", critical: false });
68
+ return checks;
69
+ }
70
+ export function printChecks(checks) {
71
+ for (const c of checks) {
72
+ out(`${c.ok ? "ok " : "FAIL"} ${c.name}: ${c.detail}`);
73
+ if (!c.ok && c.fix)
74
+ out(` fix: ${c.fix}`);
75
+ }
76
+ }
77
+ export async function doctor() {
78
+ const checks = await runChecks();
79
+ printChecks(checks);
80
+ return checks.every((c) => c.ok || !c.critical);
81
+ }
@@ -0,0 +1,72 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // down, reset, status, logs, load: thin wrappers over docker compose and the admin CLI.
3
+ import { createInterface } from "node:readline/promises";
4
+ import { admin, compose, services } from "../docker.js";
5
+ import { getHealth } from "../health.js";
6
+ import { CliError, out } from "../log.js";
7
+ import { endpoint, readState } from "../state.js";
8
+ import { NPM_PACKAGE } from "../version.js";
9
+ import { adminStatus } from "./up.js";
10
+ export function requireState() {
11
+ const state = readState();
12
+ if (!state)
13
+ throw new CliError("feederline-mcp has not been set up on this machine yet.", `npx -y ${NPM_PACKAGE} up`);
14
+ return state;
15
+ }
16
+ export async function down() {
17
+ const state = requireState();
18
+ await compose(state, ["--profile", "admin", "down", "--remove-orphans"], { ha: true, quiet: true });
19
+ out("Stopped. Data volumes are kept; `up` starts again in seconds.");
20
+ }
21
+ export async function reset(yes = false) {
22
+ const state = requireState();
23
+ if (!yes) {
24
+ if (!process.stdin.isTTY)
25
+ throw new CliError("reset needs confirmation.", `npx -y ${NPM_PACKAGE} reset --yes`);
26
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
27
+ const answer = await rl.question("This deletes the feederline-mcp containers and ALL loaded data (volumes). Type 'reset' to continue: ");
28
+ rl.close();
29
+ if (answer.trim() !== "reset") {
30
+ out("Cancelled.");
31
+ return;
32
+ }
33
+ }
34
+ await compose(state, ["--profile", "admin", "down", "--volumes", "--remove-orphans"], { ha: true, quiet: true });
35
+ out("Removed containers and volumes. Your access token in ~/.feederline-mcp/config.json is kept.");
36
+ }
37
+ export async function status(json = false) {
38
+ const state = requireState();
39
+ const { url } = endpoint(state, {});
40
+ const svc = await services(state, true);
41
+ const health = await getHealth(url);
42
+ const st = health ? await adminStatus(state).catch(() => null) : null;
43
+ if (json) {
44
+ out(JSON.stringify({ url, services: svc, health, status: st }, null, 2));
45
+ return;
46
+ }
47
+ out(`URL: ${url}`);
48
+ out(`Server: ${health ? `${health.status} (version ${health.version}, migration ${health.migration ?? "none"})` : "not reachable"}`);
49
+ for (const s of svc)
50
+ out(` ${s.Service.padEnd(10)} ${s.State}${s.Health ? ` (${s.Health})` : ""}`);
51
+ if (!svc.length)
52
+ out(` no containers; run: npx -y ${NPM_PACKAGE} up`);
53
+ if (st) {
54
+ out("");
55
+ out("Feeders:");
56
+ out(` ${"Region".padEnd(10)} ${"Name".padEnd(22)} ${"kV".padEnd(8)} Root ID`);
57
+ for (const f of st.feeders)
58
+ out(` ${f.region_code.padEnd(10)} ${f.name.padEnd(22)} ${String(f.kv ?? "").padEnd(8)} ${f.root_mrid}`);
59
+ out("");
60
+ out(st.telemetry ? `Telemetry: ${st.telemetry.first.slice(0, 10)} to ${st.telemetry.last.slice(0, 10)}` : "Telemetry: none");
61
+ }
62
+ }
63
+ export async function logs(service) {
64
+ const state = requireState();
65
+ await compose(state, ["logs", "-f", "--tail", "200", ...(service ? [service] : [])], { ha: true, input: "inherit" });
66
+ }
67
+ export async function load(dataset, rest) {
68
+ if (!["ieee", "smartds", "hifld"].includes(dataset))
69
+ throw new CliError(`Unknown dataset '${dataset}'.`, `npx -y ${NPM_PACKAGE} load ieee|smartds|hifld --help`);
70
+ const state = requireState();
71
+ await admin(state, ["load", dataset, ...rest]);
72
+ }
@@ -0,0 +1,72 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { admin, compose } from "../docker.js";
3
+ import { waitHealthy } from "../health.js";
4
+ import { CliError, out } from "../log.js";
5
+ import { endpoint, ensureState } from "../state.js";
6
+ import { NPM_PACKAGE, VERSION } from "../version.js";
7
+ import { printChecks, runChecks } from "./doctor.js";
8
+ export async function adminStatus(state) {
9
+ const raw = await admin(state, ["status", "--json"], { capture: true });
10
+ return JSON.parse(raw.trim().split("\n").pop() || "{}");
11
+ }
12
+ /** Days of demo telemetry still missing between the last rollup bucket and yesterday (UTC), capped at 30. */
13
+ export function missingDemoDays(telemetry, now = new Date(), window = 30) {
14
+ if (!telemetry)
15
+ return window;
16
+ const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
17
+ const last = new Date(telemetry.last);
18
+ const lastDay = Date.UTC(last.getUTCFullYear(), last.getUTCMonth(), last.getUTCDate());
19
+ const gap = Math.floor((today - lastDay) / 86_400_000) - 1; // yesterday is the last day the demo fills
20
+ return Math.max(0, Math.min(window, gap));
21
+ }
22
+ export async function up(opts = {}) {
23
+ const checks = await runChecks();
24
+ const failed = checks.filter((c) => !c.ok && c.critical);
25
+ if (failed.length) {
26
+ printChecks(checks);
27
+ throw new CliError("Prerequisites are missing (see above).", `Fix the failed checks, then run: npx -y ${NPM_PACKAGE} up`);
28
+ }
29
+ const { state, created } = ensureState(VERSION);
30
+ if (created)
31
+ out("Created ~/.feederline-mcp/config.json with a new random access token.");
32
+ if (opts.pull !== false) {
33
+ out("Pulling images...");
34
+ await compose(state, ["pull", "--quiet", ...(opts.ha ? ["postgres", "mcp", "proxy"] : ["postgres", "mcp"])], { ha: opts.ha });
35
+ }
36
+ out("Starting Postgres...");
37
+ await compose(state, ["up", "-d", "--wait", "postgres"], { ha: opts.ha, quiet: true });
38
+ out("Applying migrations...");
39
+ await admin(state, ["migrate"], { quiet: true });
40
+ out("Starting the MCP server...");
41
+ await compose(state, ["up", "-d", "--wait", ...(opts.ha ? ["mcp", "mcp-b", "proxy"] : ["mcp"])], { ha: opts.ha, quiet: true });
42
+ if (opts.demo !== false) {
43
+ const st = await adminStatus(state);
44
+ const regions = new Set(st.feeders.map((f) => f.region_code));
45
+ if (!["IEEE13", "IEEE34", "IEEE123"].every((r) => regions.has(r))) {
46
+ out("Loading the IEEE 13/34/123 test feeders...");
47
+ await admin(state, ["load", "ieee"], { quiet: true });
48
+ }
49
+ const days = missingDemoDays(st.telemetry);
50
+ if (days > 0) {
51
+ out(`Generating ${days} day(s) of demo telemetry (deterministic, seed 42)...`);
52
+ await admin(state, ["simulate", "--backfill-days", String(days), "--seed", "42"], { quiet: true });
53
+ }
54
+ }
55
+ if (opts.smartds) {
56
+ out("Loading NREL SMART-DS P1R (downloads about 7 MB)...");
57
+ await admin(state, ["load", "smartds", "--region", "P1R", "--substation", "p1rhs0_1247"], { quiet: true });
58
+ }
59
+ const { url } = endpoint(state, {});
60
+ const health = await waitHealthy(url, 90_000);
61
+ if (!health)
62
+ throw new CliError(`The server did not become healthy at ${url}.`, `npx -y ${NPM_PACKAGE} logs mcp`);
63
+ out(`feederline-mcp ${health.version ?? VERSION} is running at ${url} (${health.feeders ?? 0} feeders loaded).`);
64
+ if (!opts.quietNextSteps) {
65
+ out("");
66
+ out("Next: connect Claude.");
67
+ out(` npx -y ${NPM_PACKAGE} config # print the Claude Desktop / Claude Code settings`);
68
+ out(` npx -y ${NPM_PACKAGE} config --write-desktop # or add it to Claude Desktop for you (backup first)`);
69
+ out("Then restart Claude Desktop and ask: \"List the feeders available, with region, substation and nominal voltage.\"");
70
+ }
71
+ return state;
72
+ }
@@ -0,0 +1,72 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Claude Desktop and Claude Code connection settings, and a safe merge into claude_desktop_config.json.
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { dirname, join } from "node:path";
6
+ import { CliError } from "./log.js";
7
+ import { NPM_PACKAGE, SERVER_NAME } from "./version.js";
8
+ export function bridgeEntry() {
9
+ return { command: "npx", args: ["-y", NPM_PACKAGE, "connect"] };
10
+ }
11
+ export function mcpRemoteEntry(url, token) {
12
+ return {
13
+ command: "npx",
14
+ args: ["-y", "mcp-remote", url, "--header", "Authorization:${FEEDERLINE_AUTH}"],
15
+ env: { FEEDERLINE_AUTH: `Bearer ${token}` },
16
+ };
17
+ }
18
+ export function desktopSnippet(entry) {
19
+ return JSON.stringify({ mcpServers: { [SERVER_NAME]: entry } }, null, 2);
20
+ }
21
+ export function claudeCodeCommand(url, token) {
22
+ return `claude mcp add --transport http ${SERVER_NAME} ${url} --header "Authorization: Bearer ${token}"`;
23
+ }
24
+ export function desktopConfigPath(platform = process.platform, env = process.env) {
25
+ if (platform === "darwin")
26
+ return join(homedir(), "Library", "Application Support", "Claude", "claude_desktop_config.json");
27
+ if (platform === "win32") {
28
+ const appData = env.APPDATA || join(homedir(), "AppData", "Roaming");
29
+ return join(appData, "Claude", "claude_desktop_config.json");
30
+ }
31
+ return join(env.XDG_CONFIG_HOME || join(homedir(), ".config"), "Claude", "claude_desktop_config.json");
32
+ }
33
+ /** Pure merge: returns a new config with only mcpServers[SERVER_NAME] set; every other key is preserved. */
34
+ export function mergeDesktopConfig(existing, entry) {
35
+ if (existing !== undefined && (typeof existing !== "object" || existing === null || Array.isArray(existing))) {
36
+ throw new CliError("The Claude Desktop config is not a JSON object; refusing to modify it.", "Fix the file by hand, or paste the JSON printed by `config`.");
37
+ }
38
+ const base = { ...(existing ?? {}) };
39
+ const servers = base.mcpServers;
40
+ if (servers !== undefined && (typeof servers !== "object" || servers === null || Array.isArray(servers))) {
41
+ throw new CliError("`mcpServers` in the Claude Desktop config is not an object; refusing to modify it.", "Fix the file by hand, or paste the JSON printed by `config`.");
42
+ }
43
+ base.mcpServers = { ...(servers ?? {}), [SERVER_NAME]: entry };
44
+ return base;
45
+ }
46
+ function timestamp(d = new Date()) {
47
+ return d.toISOString().replace(/[:.]/g, "-");
48
+ }
49
+ /** Merge the entry into the Claude Desktop config file, writing a timestamped backup first. Returns paths. */
50
+ export function writeDesktopConfig(entry, path = desktopConfigPath()) {
51
+ let existing = undefined;
52
+ let backup = null;
53
+ if (existsSync(path)) {
54
+ const text = readFileSync(path, "utf8");
55
+ if (text.trim()) {
56
+ try {
57
+ existing = JSON.parse(text);
58
+ }
59
+ catch {
60
+ throw new CliError(`${path} is not valid JSON; refusing to modify it.`, "Fix the file by hand, or paste the JSON printed by `config`.");
61
+ }
62
+ }
63
+ backup = `${path}.${timestamp()}.bak`;
64
+ copyFileSync(path, backup);
65
+ }
66
+ else {
67
+ mkdirSync(dirname(path), { recursive: true });
68
+ }
69
+ const merged = mergeDesktopConfig(existing, entry);
70
+ writeFileSync(path, JSON.stringify(merged, null, 2) + "\n");
71
+ return { path, backup };
72
+ }
package/dist/docker.js ADDED
@@ -0,0 +1,93 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Docker and docker compose detection and calls. Compose files ship in the package's compose/ directory.
3
+ import { spawn, spawnSync } from "node:child_process";
4
+ import { join } from "node:path";
5
+ import { CliError, isProtocolMode } from "./log.js";
6
+ import { COMPOSE_DIR, NPM_PACKAGE, VERSION } from "./version.js";
7
+ let composeCmd = null;
8
+ export function dockerRunning() {
9
+ const r = spawnSync("docker", ["info", "--format", "{{.ServerVersion}}"], { encoding: "utf8" });
10
+ return r.status === 0;
11
+ }
12
+ export function dockerInstalled() {
13
+ const r = spawnSync("docker", ["--version"], { encoding: "utf8" });
14
+ return r.status === 0;
15
+ }
16
+ /** Major version from `compose version --short` output such as "2.34.0", "v2.29.1" or "5.0.1"; null if unparseable. */
17
+ export function composeMajor(version) {
18
+ const m = /^v?(\d+)\./.exec(version.trim());
19
+ return m ? Number(m[1]) : null;
20
+ }
21
+ const supported = (version) => (composeMajor(version) ?? 0) >= 2;
22
+ /** `docker compose` (plugin) or the standalone `docker-compose` binary, version 2 or later (v1 lacks the syntax we use). */
23
+ export function detectCompose() {
24
+ if (composeCmd)
25
+ return composeCmd;
26
+ const plugin = spawnSync("docker", ["compose", "version", "--short"], { encoding: "utf8" });
27
+ if (plugin.status === 0 && supported(plugin.stdout))
28
+ return (composeCmd = ["docker", "compose"]);
29
+ const standalone = spawnSync("docker-compose", ["version", "--short"], { encoding: "utf8" });
30
+ if (standalone.status === 0 && supported(standalone.stdout))
31
+ return (composeCmd = ["docker-compose"]);
32
+ return null;
33
+ }
34
+ export function composeEnv(state) {
35
+ return {
36
+ ...process.env,
37
+ FEEDERLINE_VERSION: process.env.FEEDERLINE_VERSION || VERSION,
38
+ FEEDERLINE_MCP_TOKEN: state.token,
39
+ FEEDERLINE_MCP_PORT: String(state.mcpPort),
40
+ FEEDERLINE_PG_PORT: String(state.pgPort),
41
+ FEEDERLINE_PROJECT: state.project,
42
+ COMPOSE_IGNORE_ORPHANS: "true", // one-shot admin runs use the base file while --ha replicas may be up
43
+ };
44
+ }
45
+ export function composeFiles(ha = false) {
46
+ const files = ["-f", join(COMPOSE_DIR, "docker-compose.yml")];
47
+ if (ha)
48
+ files.push("-f", join(COMPOSE_DIR, "compose.ha.yml"));
49
+ return files;
50
+ }
51
+ /** Run `docker compose -p <project> -f ... <args>`. Resolves with captured stdout (when capture) or "". */
52
+ export function compose(state, args, opts = {}) {
53
+ const cmd = detectCompose();
54
+ if (!cmd)
55
+ throw new CliError("Docker Compose v2 was not found.", `Install Docker Desktop, or Docker Engine with the compose plugin, then run: npx -y ${NPM_PACKAGE} doctor`);
56
+ const [bin, ...pre] = cmd;
57
+ const full = [...pre, "-p", state.project, ...composeFiles(opts.ha), ...args];
58
+ // In protocol mode (connect) the child's stdout must not reach ours: send it to stderr.
59
+ const stdoutTarget = opts.capture || opts.quiet ? "pipe" : isProtocolMode() ? 2 : "inherit";
60
+ const stderrTarget = opts.quiet ? "pipe" : "inherit";
61
+ const stdio = [opts.input ?? "ignore", stdoutTarget, stderrTarget];
62
+ return new Promise((resolve, reject) => {
63
+ const child = spawn(bin, full, { env: composeEnv(state), stdio });
64
+ let stdout = "";
65
+ let stderr = "";
66
+ child.stdout?.on("data", (d) => (stdout += d.toString()));
67
+ child.stderr?.on("data", (d) => (stderr += d.toString()));
68
+ child.on("error", (e) => reject(new CliError(`Could not run ${bin}: ${e.message}`, `npx -y ${NPM_PACKAGE} doctor`)));
69
+ child.on("close", (code) => {
70
+ if (code === 0)
71
+ resolve(stdout);
72
+ else {
73
+ if (opts.quiet && (stdout || stderr))
74
+ process.stderr.write(stdout + stderr);
75
+ reject(new CliError(`docker compose ${args.join(" ")} failed (exit ${code}).`, `npx -y ${NPM_PACKAGE} logs`));
76
+ }
77
+ });
78
+ });
79
+ }
80
+ /** Run the admin CLI inside the server image: `docker compose run --rm admin <args>`. */
81
+ export function admin(state, args, opts = {}) {
82
+ return compose(state, ["--profile", "admin", "run", "--rm", "--no-deps", "admin", ...args], opts);
83
+ }
84
+ export async function services(state, ha = false) {
85
+ const raw = await compose(state, ["ps", "--all", "--format", "json"], { capture: true, ha });
86
+ const text = raw.trim();
87
+ if (!text)
88
+ return [];
89
+ // compose v2 prints either a JSON array or one JSON object per line depending on version
90
+ if (text.startsWith("["))
91
+ return JSON.parse(text);
92
+ return text.split("\n").filter(Boolean).map((l) => JSON.parse(l));
93
+ }
package/dist/health.js ADDED
@@ -0,0 +1,36 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ export function healthUrl(mcpUrl) {
3
+ const u = new URL(mcpUrl);
4
+ u.pathname = "/healthz";
5
+ u.search = "";
6
+ return u.toString();
7
+ }
8
+ export async function getHealth(mcpUrl, timeoutMs = 3000) {
9
+ const ctl = new AbortController();
10
+ const timer = setTimeout(() => ctl.abort(), timeoutMs);
11
+ try {
12
+ const res = await fetch(healthUrl(mcpUrl), { signal: ctl.signal });
13
+ const body = (await res.json());
14
+ return body;
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ finally {
20
+ clearTimeout(timer);
21
+ }
22
+ }
23
+ export function isHealthy(h) {
24
+ return Boolean(h && h.status === "ok" && h.db === "ok");
25
+ }
26
+ export async function waitHealthy(mcpUrl, timeoutMs, wantMigration = true) {
27
+ const deadline = Date.now() + timeoutMs;
28
+ let last = null;
29
+ while (Date.now() < deadline) {
30
+ last = await getHealth(mcpUrl);
31
+ if (isHealthy(last) && (!wantMigration || last?.migration))
32
+ return last;
33
+ await new Promise((r) => setTimeout(r, 1000));
34
+ }
35
+ return null;
36
+ }
package/dist/log.js ADDED
@@ -0,0 +1,30 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Output helpers. In `connect` mode stdout belongs to the MCP protocol, so everything human-readable goes to stderr
3
+ // and child processes have their stdout redirected to stderr as well.
4
+ let protocolMode = false;
5
+ export function enableProtocolMode() {
6
+ protocolMode = true;
7
+ // Any stray console.log in a dependency would corrupt the protocol stream.
8
+ console.log = (...args) => console.error(...args);
9
+ console.info = (...args) => console.error(...args);
10
+ }
11
+ export function isProtocolMode() {
12
+ return protocolMode;
13
+ }
14
+ /** Human-facing output: stdout normally, stderr in protocol mode. */
15
+ export function out(line = "") {
16
+ if (protocolMode)
17
+ process.stderr.write(line + "\n");
18
+ else
19
+ process.stdout.write(line + "\n");
20
+ }
21
+ export function info(line) {
22
+ process.stderr.write(line + "\n");
23
+ }
24
+ export class CliError extends Error {
25
+ fix;
26
+ constructor(message, fix) {
27
+ super(message);
28
+ this.fix = fix;
29
+ }
30
+ }
package/dist/state.js ADDED
@@ -0,0 +1,76 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Per-user state: ~/.feederline-mcp/config.json holds the bearer token, ports, version and compose project name.
3
+ import { randomBytes } from "node:crypto";
4
+ import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
5
+ import { homedir } from "node:os";
6
+ import { join } from "node:path";
7
+ export const DEFAULT_MCP_PORT = 8000;
8
+ export const DEFAULT_PG_PORT = 5433;
9
+ export const DEFAULT_PROJECT = "feederline-mcp";
10
+ export function stateDir(env = process.env) {
11
+ return env.FEEDERLINE_HOME || join(homedir(), ".feederline-mcp");
12
+ }
13
+ export function statePath(env = process.env) {
14
+ return join(stateDir(env), "config.json");
15
+ }
16
+ export function newToken() {
17
+ return randomBytes(32).toString("hex");
18
+ }
19
+ function envPort(value, fallback) {
20
+ const n = value ? Number.parseInt(value, 10) : NaN;
21
+ return Number.isInteger(n) && n > 0 && n < 65536 ? n : fallback;
22
+ }
23
+ export function readState(env = process.env) {
24
+ const path = statePath(env);
25
+ if (!existsSync(path))
26
+ return null;
27
+ const raw = JSON.parse(readFileSync(path, "utf8"));
28
+ if (!raw.token || typeof raw.token !== "string")
29
+ return null;
30
+ return {
31
+ token: raw.token,
32
+ mcpPort: envPort(String(raw.mcpPort ?? ""), DEFAULT_MCP_PORT),
33
+ pgPort: envPort(String(raw.pgPort ?? ""), DEFAULT_PG_PORT),
34
+ version: raw.version ?? "",
35
+ project: raw.project || DEFAULT_PROJECT,
36
+ };
37
+ }
38
+ export function writeState(state, env = process.env) {
39
+ const dir = stateDir(env);
40
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
41
+ const path = statePath(env);
42
+ writeFileSync(path, JSON.stringify(state, null, 2) + "\n", { mode: 0o600 });
43
+ try {
44
+ chmodSync(path, 0o600); // the token is a credential; no-op on Windows
45
+ }
46
+ catch {
47
+ /* ignore */
48
+ }
49
+ }
50
+ /** Read the state file, creating it with a random 32-byte token on first run. Env ports override saved ones. */
51
+ export function ensureState(version, env = process.env) {
52
+ const existing = readState(env);
53
+ const state = existing ?? {
54
+ token: newToken(),
55
+ mcpPort: DEFAULT_MCP_PORT,
56
+ pgPort: DEFAULT_PG_PORT,
57
+ version,
58
+ project: DEFAULT_PROJECT,
59
+ };
60
+ state.mcpPort = envPort(env.FEEDERLINE_MCP_PORT, state.mcpPort);
61
+ state.pgPort = envPort(env.FEEDERLINE_PG_PORT, state.pgPort);
62
+ if (env.FEEDERLINE_PROJECT)
63
+ state.project = env.FEEDERLINE_PROJECT;
64
+ const changed = !existing || existing.version !== version || existing.mcpPort !== state.mcpPort || existing.pgPort !== state.pgPort || existing.project !== state.project;
65
+ state.version = version;
66
+ if (changed)
67
+ writeState(state, env);
68
+ return { state, created: !existing };
69
+ }
70
+ /** Where the MCP endpoint is and how to authenticate, honouring FEEDERLINE_MCP_URL / FEEDERLINE_MCP_TOKEN. */
71
+ export function endpoint(state, env = process.env) {
72
+ const overridden = Boolean(env.FEEDERLINE_MCP_URL);
73
+ const url = env.FEEDERLINE_MCP_URL || `http://127.0.0.1:${state?.mcpPort ?? DEFAULT_MCP_PORT}/mcp`;
74
+ const token = env.FEEDERLINE_MCP_TOKEN || state?.token || "";
75
+ return { url, token, overridden };
76
+ }
@@ -0,0 +1,9 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ export const PACKAGE_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
6
+ export const COMPOSE_DIR = join(PACKAGE_ROOT, "compose");
7
+ export const VERSION = JSON.parse(readFileSync(join(PACKAGE_ROOT, "package.json"), "utf8")).version;
8
+ export const SERVER_NAME = "feederline-mcp";
9
+ export const NPM_PACKAGE = "@kartha-energy/feederline-mcp";
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@kartha-energy/feederline-mcp",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Run the feederline-mcp server (CIM grid model on Postgres + OpenDSS power-flow studies over MCP) locally with Docker, and connect Claude to it.",
5
+ "license": "Apache-2.0",
6
+ "author": "Kartha Energy",
7
+ "type": "module",
8
+ "bin": {
9
+ "feederline-mcp": "dist/cli.js"
10
+ },
11
+ "files": [
12
+ "dist",
13
+ "compose",
14
+ "README.md",
15
+ "LICENSE"
16
+ ],
17
+ "engines": {
18
+ "node": ">=18"
19
+ },
20
+ "scripts": {
21
+ "build": "tsc -p tsconfig.json",
22
+ "lint": "tsc -p tsconfig.json --noEmit",
23
+ "test": "npm run build && vitest run",
24
+ "prepack": "node scripts/copy-license.mjs && npm run build"
25
+ },
26
+ "dependencies": {
27
+ "@modelcontextprotocol/sdk": "^1.32.2",
28
+ "commander": "^12.1.0"
29
+ },
30
+ "devDependencies": {
31
+ "@types/node": "^20.19.0",
32
+ "typescript": "^5.9.3",
33
+ "vitest": "^3.2.7"
34
+ },
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/Kartha-AI/feederline-mcp.git",
38
+ "directory": "npm"
39
+ },
40
+ "homepage": "https://github.com/Kartha-AI/feederline-mcp#readme",
41
+ "bugs": "https://github.com/Kartha-AI/feederline-mcp/issues",
42
+ "keywords": [
43
+ "mcp",
44
+ "model-context-protocol",
45
+ "opendss",
46
+ "power-flow",
47
+ "cim",
48
+ "distribution-grid",
49
+ "claude"
50
+ ],
51
+ "publishConfig": {
52
+ "access": "public",
53
+ "provenance": true
54
+ }
55
+ }