aivy-mcp 0.1.0__tar.gz

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.
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .env
aivy_mcp-0.1.0/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 2026 Ivy Energy
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.
@@ -0,0 +1,124 @@
1
+ Metadata-Version: 2.5
2
+ Name: aivy-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for the Aivy Developer API: let your AI assistant read and control your own solar + battery system.
5
+ Project-URL: Homepage, https://github.com/IVYEnergy/aivy-mcp
6
+ Project-URL: Documentation, https://bridge.ivyenergy.com.au/v1/docs
7
+ Project-URL: API guide, https://bridge.ivyenergy.com.au/v1/llms.txt
8
+ Author: Ivy Energy
9
+ License-Expression: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: amber,battery,energy,home-energy,mcp,sigenergy,solar,sungrow
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: License :: OSI Approved :: Apache Software License
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Topic :: Home Automation
18
+ Requires-Python: >=3.10
19
+ Requires-Dist: httpx>=0.27
20
+ Requires-Dist: mcp>=1.2
21
+ Description-Content-Type: text/markdown
22
+
23
+ # aivy-mcp
24
+
25
+ An [MCP](https://modelcontextprotocol.io) server that lets your own AI assistant
26
+ (Claude Code, Claude Desktop, ChatGPT, Codex, Cursor, ...) read and control
27
+ **your own** solar + battery system through the
28
+ [Aivy Developer API](https://bridge.ivyenergy.com.au/v1/docs) by Ivy Energy.
29
+
30
+ Works with every brand Aivy runs: Sungrow, Sigenergy, FoxESS, AlphaESS, SolaX
31
+ and more. The same tools, whatever the inverter.
32
+
33
+ ## 1. Get a key
34
+
35
+ In the Aivy app (web or mobile) open the user menu, **API keys**, and create a
36
+ key. Pick **Read only** to let an assistant look, or **Read and control** to
37
+ let it change the energy mode and Ai+ settings. The key sees exactly what your
38
+ account sees, nothing more.
39
+
40
+ ## 2. Add the server
41
+
42
+ Claude Code:
43
+
44
+ ```bash
45
+ claude mcp add aivy -e AIVY_API_KEY=aivy_sk_... -- uvx aivy-mcp
46
+ ```
47
+
48
+ Claude Desktop / Cursor / any MCP client (`mcpServers` block):
49
+
50
+ ```json
51
+ {
52
+ "mcpServers": {
53
+ "aivy": {
54
+ "command": "uvx",
55
+ "args": ["aivy-mcp"],
56
+ "env": { "AIVY_API_KEY": "aivy_sk_..." }
57
+ }
58
+ }
59
+ }
60
+ ```
61
+
62
+ No `uv`? `pipx run aivy-mcp` or `pip install aivy-mcp && aivy-mcp` work too.
63
+
64
+ Assistants that cannot run local tools (ChatGPT in the browser) can use the
65
+ HTTP API directly. Paste this into the chat:
66
+
67
+ > Use the Aivy Developer API at https://bridge.ivyenergy.com.au/v1 with the
68
+ > header `Authorization: Bearer aivy_sk_...`. Read
69
+ > https://bridge.ivyenergy.com.au/v1/llms.txt first, then GET /sites.
70
+
71
+ ## 3. Ask
72
+
73
+ - "How's my battery doing?"
74
+ - "Why did it charge at 3am?"
75
+ - "What are prices doing tonight? Should I sell?"
76
+ - "Plan the best time to sell tonight, keep 20%, then apply it."
77
+ - "Charge at 5 kW to 90% for the next two hours." (control key)
78
+ - "Make Ai+ a bit more aggressive on exports." (control key)
79
+
80
+ ## Tools
81
+
82
+ | Tool | Changes anything? | What it does |
83
+ |---|---|---|
84
+ | `whoami` | no | Who the key is, read or control |
85
+ | `list_sites` | no | Your sites; ids look like `sungrow:1445844` |
86
+ | `get_site` | no | Capacity, limits, timezone, mode, live SOC |
87
+ | `get_status` | no | Live SOC and power flows |
88
+ | `get_curve` | no | 5-minute or daily history |
89
+ | `get_earnings` | no | A day's energy, priced at Amber's actual prices |
90
+ | `get_operations` | no | What the platform did and why |
91
+ | `get_prices` | no | Amber prices now and forecast |
92
+ | `get_energy_mode` | no | Mode, windows, pending hand-back |
93
+ | `set_energy_mode` | **yes** | selfConsumption / amber_smart (Ai+) / forced (time-boxed) |
94
+ | `get_ai_plus` | no | Ai+ variant, settings and tunable ranges |
95
+ | `update_ai_plus` | **yes** | Change Ai+ levers or variant |
96
+ | `plan_best_price_discharge` | no | Propose a sell schedule from the forecast |
97
+ | `plan_discharge_to_target` | no | Propose a discharge that lands on a SOC at a time |
98
+
99
+ ## What the server enforces, whatever the assistant does
100
+
101
+ - A key sees only its owner's sites; writes need the control scope.
102
+ - A forced (manual) mode set through the API **always reverts** to the previous
103
+ mode after `duration_minutes` (default 4 h, max 24 h).
104
+ - The SOC floor and grid export limits cannot be overridden.
105
+ - Every call is recorded with the key id and client; keys can be revoked in
106
+ the app at any time and stop working immediately.
107
+ - Per-key rate limit (default 120/min). Readings refresh about once a minute.
108
+
109
+ ## Development
110
+
111
+ ```bash
112
+ git clone https://github.com/IVYEnergy/aivy-mcp && cd aivy-mcp
113
+ uv run --with pytest pytest
114
+ uv run aivy-mcp # needs AIVY_API_KEY
115
+ ```
116
+
117
+ The package also lives in Ivy Energy's main repository under `sdk/aivy-mcp`;
118
+ this public repository is where it is released from.
119
+
120
+ Point at another deployment with `AIVY_API_URL=https://host/v1`.
121
+
122
+ ## License
123
+
124
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,102 @@
1
+ # aivy-mcp
2
+
3
+ An [MCP](https://modelcontextprotocol.io) server that lets your own AI assistant
4
+ (Claude Code, Claude Desktop, ChatGPT, Codex, Cursor, ...) read and control
5
+ **your own** solar + battery system through the
6
+ [Aivy Developer API](https://bridge.ivyenergy.com.au/v1/docs) by Ivy Energy.
7
+
8
+ Works with every brand Aivy runs: Sungrow, Sigenergy, FoxESS, AlphaESS, SolaX
9
+ and more. The same tools, whatever the inverter.
10
+
11
+ ## 1. Get a key
12
+
13
+ In the Aivy app (web or mobile) open the user menu, **API keys**, and create a
14
+ key. Pick **Read only** to let an assistant look, or **Read and control** to
15
+ let it change the energy mode and Ai+ settings. The key sees exactly what your
16
+ account sees, nothing more.
17
+
18
+ ## 2. Add the server
19
+
20
+ Claude Code:
21
+
22
+ ```bash
23
+ claude mcp add aivy -e AIVY_API_KEY=aivy_sk_... -- uvx aivy-mcp
24
+ ```
25
+
26
+ Claude Desktop / Cursor / any MCP client (`mcpServers` block):
27
+
28
+ ```json
29
+ {
30
+ "mcpServers": {
31
+ "aivy": {
32
+ "command": "uvx",
33
+ "args": ["aivy-mcp"],
34
+ "env": { "AIVY_API_KEY": "aivy_sk_..." }
35
+ }
36
+ }
37
+ }
38
+ ```
39
+
40
+ No `uv`? `pipx run aivy-mcp` or `pip install aivy-mcp && aivy-mcp` work too.
41
+
42
+ Assistants that cannot run local tools (ChatGPT in the browser) can use the
43
+ HTTP API directly. Paste this into the chat:
44
+
45
+ > Use the Aivy Developer API at https://bridge.ivyenergy.com.au/v1 with the
46
+ > header `Authorization: Bearer aivy_sk_...`. Read
47
+ > https://bridge.ivyenergy.com.au/v1/llms.txt first, then GET /sites.
48
+
49
+ ## 3. Ask
50
+
51
+ - "How's my battery doing?"
52
+ - "Why did it charge at 3am?"
53
+ - "What are prices doing tonight? Should I sell?"
54
+ - "Plan the best time to sell tonight, keep 20%, then apply it."
55
+ - "Charge at 5 kW to 90% for the next two hours." (control key)
56
+ - "Make Ai+ a bit more aggressive on exports." (control key)
57
+
58
+ ## Tools
59
+
60
+ | Tool | Changes anything? | What it does |
61
+ |---|---|---|
62
+ | `whoami` | no | Who the key is, read or control |
63
+ | `list_sites` | no | Your sites; ids look like `sungrow:1445844` |
64
+ | `get_site` | no | Capacity, limits, timezone, mode, live SOC |
65
+ | `get_status` | no | Live SOC and power flows |
66
+ | `get_curve` | no | 5-minute or daily history |
67
+ | `get_earnings` | no | A day's energy, priced at Amber's actual prices |
68
+ | `get_operations` | no | What the platform did and why |
69
+ | `get_prices` | no | Amber prices now and forecast |
70
+ | `get_energy_mode` | no | Mode, windows, pending hand-back |
71
+ | `set_energy_mode` | **yes** | selfConsumption / amber_smart (Ai+) / forced (time-boxed) |
72
+ | `get_ai_plus` | no | Ai+ variant, settings and tunable ranges |
73
+ | `update_ai_plus` | **yes** | Change Ai+ levers or variant |
74
+ | `plan_best_price_discharge` | no | Propose a sell schedule from the forecast |
75
+ | `plan_discharge_to_target` | no | Propose a discharge that lands on a SOC at a time |
76
+
77
+ ## What the server enforces, whatever the assistant does
78
+
79
+ - A key sees only its owner's sites; writes need the control scope.
80
+ - A forced (manual) mode set through the API **always reverts** to the previous
81
+ mode after `duration_minutes` (default 4 h, max 24 h).
82
+ - The SOC floor and grid export limits cannot be overridden.
83
+ - Every call is recorded with the key id and client; keys can be revoked in
84
+ the app at any time and stop working immediately.
85
+ - Per-key rate limit (default 120/min). Readings refresh about once a minute.
86
+
87
+ ## Development
88
+
89
+ ```bash
90
+ git clone https://github.com/IVYEnergy/aivy-mcp && cd aivy-mcp
91
+ uv run --with pytest pytest
92
+ uv run aivy-mcp # needs AIVY_API_KEY
93
+ ```
94
+
95
+ The package also lives in Ivy Energy's main repository under `sdk/aivy-mcp`;
96
+ this public repository is where it is released from.
97
+
98
+ Point at another deployment with `AIVY_API_URL=https://host/v1`.
99
+
100
+ ## License
101
+
102
+ Apache License 2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,36 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "aivy-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for the Aivy Developer API: let your AI assistant read and control your own solar + battery system."
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ requires-python = ">=3.10"
12
+ authors = [{ name = "Ivy Energy" }]
13
+ keywords = ["mcp", "solar", "battery", "energy", "amber", "sungrow", "sigenergy", "home-energy"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: End Users/Desktop",
17
+ "Intended Audience :: Developers",
18
+ "License :: OSI Approved :: Apache Software License",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Home Automation",
21
+ ]
22
+ dependencies = [
23
+ "mcp>=1.2",
24
+ "httpx>=0.27",
25
+ ]
26
+
27
+ [project.urls]
28
+ Homepage = "https://github.com/IVYEnergy/aivy-mcp"
29
+ Documentation = "https://bridge.ivyenergy.com.au/v1/docs"
30
+ "API guide" = "https://bridge.ivyenergy.com.au/v1/llms.txt"
31
+
32
+ [project.scripts]
33
+ aivy-mcp = "aivy_mcp.server:main"
34
+
35
+ [tool.hatch.build.targets.wheel]
36
+ packages = ["src/aivy_mcp"]
@@ -0,0 +1,3 @@
1
+ """aivy-mcp: an MCP server over the Aivy Developer API."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,103 @@
1
+ """Thin HTTP client for the Aivy Developer API.
2
+
3
+ Everything the MCP tools do is one HTTP call here. Kept separate so the same
4
+ client can back a CLI or a notebook without the MCP machinery.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ from typing import Any
11
+
12
+ import httpx
13
+
14
+ DEFAULT_API_URL = "https://bridge.ivyenergy.com.au/v1"
15
+
16
+
17
+ class AivyError(RuntimeError):
18
+ """The API refused or could not complete a request. The message carries
19
+ the server's `detail`, which is written to be read by a person or model."""
20
+
21
+
22
+ class AivyClient:
23
+ def __init__(self, api_key: str | None = None, api_url: str | None = None, timeout: float = 30.0):
24
+ self.api_key = api_key or os.environ.get("AIVY_API_KEY", "")
25
+ self.api_url = (api_url or os.environ.get("AIVY_API_URL") or DEFAULT_API_URL).rstrip("/")
26
+ if not self.api_key:
27
+ raise AivyError("AIVY_API_KEY is not set. Create a key in the Aivy app (menu, API keys) and "
28
+ "export AIVY_API_KEY=aivy_sk_...")
29
+ self._http = httpx.AsyncClient(
30
+ base_url=self.api_url, timeout=timeout,
31
+ headers={"Authorization": f"Bearer {self.api_key}", "User-Agent": f"aivy-mcp/{_version()}"},
32
+ )
33
+
34
+ async def aclose(self) -> None:
35
+ await self._http.aclose()
36
+
37
+ async def _call(self, method: str, path: str, **kwargs: Any) -> Any:
38
+ try:
39
+ response = await self._http.request(method, path, **kwargs)
40
+ except httpx.HTTPError as e:
41
+ raise AivyError(f"could not reach the Aivy API at {self.api_url}: {e}") from e
42
+ if response.status_code >= 400:
43
+ try:
44
+ detail = response.json().get("detail")
45
+ except ValueError:
46
+ detail = response.text
47
+ raise AivyError(f"{response.status_code}: {detail}")
48
+ return response.json()
49
+
50
+ # ── account / sites ──
51
+ async def me(self) -> dict:
52
+ return await self._call("GET", "/me")
53
+
54
+ async def sites(self) -> dict:
55
+ return await self._call("GET", "/sites")
56
+
57
+ async def site(self, site_id: str) -> dict:
58
+ return await self._call("GET", f"/sites/{site_id}")
59
+
60
+ async def status(self, site_id: str) -> dict:
61
+ return await self._call("GET", f"/sites/{site_id}/status")
62
+
63
+ async def curve(self, site_id: str, range_: str = "1d", day: str | None = None) -> dict:
64
+ params = {"range": range_}
65
+ if day:
66
+ params["day"] = day
67
+ return await self._call("GET", f"/sites/{site_id}/curve", params=params)
68
+
69
+ async def earnings(self, site_id: str, date: str | None = None, window_start: str | None = None,
70
+ window_end: str | None = None) -> dict:
71
+ params = {k: v for k, v in {"date": date, "window_start": window_start, "window_end": window_end}.items() if v}
72
+ return await self._call("GET", f"/sites/{site_id}/earnings", params=params)
73
+
74
+ async def operations(self, site_id: str, limit: int = 20) -> dict:
75
+ return await self._call("GET", f"/sites/{site_id}/operations", params={"limit": limit})
76
+
77
+ async def prices(self, site_id: str, hours: int = 8, resolution: int = 30) -> dict:
78
+ return await self._call("GET", f"/sites/{site_id}/prices", params={"hours": hours, "resolution": resolution})
79
+
80
+ # ── control ──
81
+ async def energy_mode(self, site_id: str) -> dict:
82
+ return await self._call("GET", f"/sites/{site_id}/energy-mode")
83
+
84
+ async def set_energy_mode(self, site_id: str, body: dict) -> dict:
85
+ return await self._call("PUT", f"/sites/{site_id}/energy-mode", json=body)
86
+
87
+ async def ai_plus(self, site_id: str) -> dict:
88
+ return await self._call("GET", f"/sites/{site_id}/ai-plus")
89
+
90
+ async def patch_ai_plus(self, site_id: str, variant: str | None, settings: dict) -> dict:
91
+ return await self._call("PATCH", f"/sites/{site_id}/ai-plus", json={"variant": variant, "settings": settings})
92
+
93
+ # ── planning ──
94
+ async def plan_best_price_discharge(self, site_id: str, body: dict) -> dict:
95
+ return await self._call("POST", f"/sites/{site_id}/plans/best-price-discharge", json=body)
96
+
97
+ async def plan_discharge_to_target(self, site_id: str, body: dict) -> dict:
98
+ return await self._call("POST", f"/sites/{site_id}/plans/discharge-to-target", json=body)
99
+
100
+
101
+ def _version() -> str:
102
+ from aivy_mcp import __version__
103
+ return __version__
@@ -0,0 +1,210 @@
1
+ """MCP server exposing the Aivy Developer API as tools.
2
+
3
+ Run with `uvx aivy-mcp` (stdio). Configuration by environment:
4
+
5
+ AIVY_API_KEY personal key from the Aivy app (required)
6
+ AIVY_API_URL API base, default https://bridge.ivyenergy.com.au/v1
7
+
8
+ Tool descriptions are the contract the model reads, so they say what a
9
+ call changes, what it cannot change, and what the server will do on its
10
+ own (hand a forced mode back after its duration).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ from typing import Any
17
+
18
+ try: # mcp 2.x
19
+ from mcp.server.mcpserver import MCPServer as _Server
20
+ except ModuleNotFoundError: # mcp 1.x
21
+ from mcp.server.fastmcp import FastMCP as _Server
22
+
23
+ from aivy_mcp.client import AivyClient, AivyError
24
+
25
+ mcp = _Server(
26
+ "aivy",
27
+ instructions=(
28
+ "Tools for the user's own solar + battery system through the Aivy platform (Ivy Energy, Australia). "
29
+ "Call list_sites first; every other tool takes one of its site ids (vendor:station_id). "
30
+ "Power is in watts (battery_w > 0 charging, grid_w > 0 exporting), SOC in percent, prices in "
31
+ "Australian cents per kWh. Readings refresh about once a minute: do not poll faster. "
32
+ "Changing the mode or Ai+ settings needs a control-scope key; a forced (manual) mode set here is "
33
+ "time-boxed and the server returns the site to its previous mode when the time is up."
34
+ ),
35
+ )
36
+
37
+ _client: AivyClient | None = None
38
+
39
+
40
+ def _c() -> AivyClient:
41
+ global _client
42
+ if _client is None:
43
+ _client = AivyClient()
44
+ return _client
45
+
46
+
47
+ def _dump(value: Any) -> str:
48
+ return json.dumps(value, ensure_ascii=False, default=str)
49
+
50
+
51
+ async def _run(coro) -> str:
52
+ try:
53
+ return _dump(await coro)
54
+ except AivyError as e:
55
+ return _dump({"error": str(e)})
56
+
57
+
58
+ # ── account / sites ──
59
+
60
+ @mcp.tool()
61
+ async def whoami() -> str:
62
+ """Check the API key: who it belongs to and whether it may control (scope read or control)."""
63
+ return await _run(_c().me())
64
+
65
+
66
+ @mcp.tool()
67
+ async def list_sites() -> str:
68
+ """List the user's solar + battery sites across vendors. Returns id (vendor:station_id, used by every other
69
+ tool), vendor, name, online and the vendor's headline power in W. Start here."""
70
+ return await _run(_c().sites())
71
+
72
+
73
+ @mcp.tool()
74
+ async def get_site(site_id: str) -> str:
75
+ """Facts about one site: timezone, battery capacity (kWh) and where that figure came from, max charge/discharge
76
+ power (W), export limit (W), the SOC floor Ai+ keeps, live SOC and usable kWh, current energy mode and
77
+ forced windows, today's energy and income when the vendor reports them."""
78
+ return await _run(_c().site(site_id))
79
+
80
+
81
+ @mcp.tool()
82
+ async def get_status(site_id: str) -> str:
83
+ """Live reading: SOC (%), pv_w, load_w, grid_w (>0 exporting), battery_w (>0 charging). A null channel is one
84
+ the vendor does not report, not zero. `source` is vendor (fresh) or stored (last kept reading)."""
85
+ return await _run(_c().status(site_id))
86
+
87
+
88
+ @mcp.tool()
89
+ async def get_curve(site_id: str, range: str = "1d", day: str | None = None) -> str:
90
+ """Power and SOC history. range 1d = 5-minute points for one local day (day = YYYY-MM-DD, default today);
91
+ 7d / 30d = daily values. Returns times (UTC), local_times, and series per channel (pv, load, battery, grid,
92
+ soc). Large: summarise before quoting."""
93
+ return await _run(_c().curve(site_id, range, day))
94
+
95
+
96
+ @mcp.tool()
97
+ async def get_earnings(site_id: str, date: str | None = None, window_start: str | None = None,
98
+ window_end: str | None = None) -> str:
99
+ """Energy bought, sold and self-consumed for a day (YYYY-MM-DD, 'today' or 'yesterday'), priced at the actual
100
+ Amber half-hourly prices when Amber is linked. Optional HH:MM window for part of the day. An estimate from
101
+ vendor power samples, not the bill; read `coverage` and say so when it is partial."""
102
+ return await _run(_c().earnings(site_id, date, window_start, window_end))
103
+
104
+
105
+ @mcp.tool()
106
+ async def get_operations(site_id: str, limit: int = 20) -> str:
107
+ """What the platform did to the site and why, newest first: each automatic (Ai+) and manual command with its
108
+ reason and the prices at the time. Use it to explain 'why did it charge at 3am'."""
109
+ return await _run(_c().operations(site_id, limit))
110
+
111
+
112
+ @mcp.tool()
113
+ async def get_prices(site_id: str, hours: int = 8, resolution: int = 30) -> str:
114
+ """Amber Electric prices for the site: the current interval and the forecast as import price and feed-in earn
115
+ (c/kWh incl. GST), with a summary of cheapest/dearest periods. resolution 30 (up to 24 h) or 5 (up to 4 h).
116
+ Fails with 409 when no Amber account is linked to the site."""
117
+ return await _run(_c().prices(site_id, hours, resolution))
118
+
119
+
120
+ # ── control ──
121
+
122
+ @mcp.tool()
123
+ async def get_energy_mode(site_id: str) -> str:
124
+ """Current energy mode (selfConsumption | amber_smart = Ai+ | forced), its forced windows, the SOC floor, the
125
+ Ai+ variant and settings when on Ai+, and any pending timed hand-back (reverts_at / reverts_to)."""
126
+ return await _run(_c().energy_mode(site_id))
127
+
128
+
129
+ @mcp.tool()
130
+ async def set_energy_mode(
131
+ site_id: str,
132
+ mode: str,
133
+ duration_minutes: int | None = None,
134
+ action: str | None = None,
135
+ power_w: int | None = None,
136
+ target_soc: int | None = None,
137
+ stop_soc: int | None = None,
138
+ time_slots: list[dict] | None = None,
139
+ variant: str | None = None,
140
+ ) -> str:
141
+ """CHANGES THE SITE (control scope). Confirm with the user before calling.
142
+
143
+ mode: selfConsumption (inverter default), amber_smart (Ai+, price-driven trading) or forced (manual windows).
144
+ forced is always time-boxed: duration_minutes (default 240, max 1440); afterwards the server returns the site
145
+ to the mode it had before. Shorthand for forced: action=charge|discharge with power_w and target_soc (charge)
146
+ or stop_soc (discharge) builds one window starting now. Or pass explicit time_slots:
147
+ [{type, start 'HH:MM', end 'HH:MM', target_soc|stop_soc, power, pace}] in site local time.
148
+ variant picks the Ai+ engine when mode is amber_smart. The SOC floor and export limits cannot be overridden.
149
+ Takes effect on the engine's next tick (about a minute)."""
150
+ body: dict[str, Any] = {"mode": mode}
151
+ for key, value in (("duration_minutes", duration_minutes), ("action", action), ("power_w", power_w),
152
+ ("target_soc", target_soc), ("stop_soc", stop_soc), ("time_slots", time_slots),
153
+ ("variant", variant)):
154
+ if value is not None:
155
+ body[key] = value
156
+ return await _run(_c().set_energy_mode(site_id, body))
157
+
158
+
159
+ @mcp.tool()
160
+ async def get_ai_plus(site_id: str) -> str:
161
+ """Ai+ (amber_smart) configuration: active or not, engine variant and options, effective settings, and
162
+ `tunable`: every lever with type, min, max, unit and default. Read before update_ai_plus."""
163
+ return await _run(_c().ai_plus(site_id))
164
+
165
+
166
+ @mcp.tool()
167
+ async def update_ai_plus(site_id: str, settings: dict[str, Any] | None = None, variant: str | None = None) -> str:
168
+ """CHANGES THE SITE (control scope). Confirm with the user before calling.
169
+
170
+ Set Ai+ levers (names and ranges from get_ai_plus `tunable`) and/or switch engine variant. Validated against
171
+ the variant that will run; if any value is rejected nothing changes and `rejected` says why. Does not switch
172
+ the mode: use set_energy_mode(mode='amber_smart') for that."""
173
+ return await _run(_c().patch_ai_plus(site_id, variant, settings or {}))
174
+
175
+
176
+ # ── planning (nothing is applied) ──
177
+
178
+ @mcp.tool()
179
+ async def plan_best_price_discharge(site_id: str, window_start: str | None = None, window_end: str | None = None,
180
+ reserve_soc: int | None = None, min_sell_c: float | None = None,
181
+ battery_capacity_kwh: float | None = None) -> str:
182
+ """Propose when to sell: picks the best-paid Amber intervals in the window (HH:MM) for the battery's usable
183
+ energy above reserve_soc, optionally only above min_sell_c c/kWh. Returns intervals, expected revenue, the
184
+ average it beats and proposed time_slots. Nothing is applied; apply with set_energy_mode(mode='forced',
185
+ time_slots=...) after the user agrees."""
186
+ body = {k: v for k, v in {"window_start": window_start, "window_end": window_end, "reserve_soc": reserve_soc,
187
+ "min_sell_c": min_sell_c, "battery_capacity_kwh": battery_capacity_kwh}.items()
188
+ if v is not None}
189
+ return await _run(_c().plan_best_price_discharge(site_id, body))
190
+
191
+
192
+ @mcp.tool()
193
+ async def plan_discharge_to_target(site_id: str, end: str, target_soc: int, start: str | None = None,
194
+ battery_capacity_kwh: float | None = None) -> str:
195
+ """Propose a steady discharge that lands on target_soc at end (HH:MM, site local), from the real capacity, SOC
196
+ and power limits. Returns power_w and proposed time_slots. Nothing is applied."""
197
+ body: dict[str, Any] = {"end": end, "target_soc": target_soc}
198
+ if start:
199
+ body["start"] = start
200
+ if battery_capacity_kwh:
201
+ body["battery_capacity_kwh"] = battery_capacity_kwh
202
+ return await _run(_c().plan_discharge_to_target(site_id, body))
203
+
204
+
205
+ def main() -> None:
206
+ mcp.run()
207
+
208
+
209
+ if __name__ == "__main__":
210
+ main()
@@ -0,0 +1,63 @@
1
+ """The MCP tool set mirrors the Developer API, and errors come back as data."""
2
+ import asyncio
3
+ import json
4
+
5
+ import httpx
6
+ import pytest
7
+
8
+ from aivy_mcp import client as client_mod
9
+ from aivy_mcp import server
10
+
11
+
12
+ def _client_with(handler) -> client_mod.AivyClient:
13
+ c = client_mod.AivyClient(api_key="aivy_sk_test", api_url="https://example.test/v1")
14
+ c._http = httpx.AsyncClient(base_url="https://example.test/v1", transport=httpx.MockTransport(handler),
15
+ headers={"Authorization": "Bearer aivy_sk_test"})
16
+ return c
17
+
18
+
19
+ def test_every_tool_is_listed_and_writes_say_so():
20
+ tools = asyncio.run(server.mcp.list_tools())
21
+ names = {t.name for t in tools}
22
+ assert names == {"whoami", "list_sites", "get_site", "get_status", "get_curve", "get_earnings", "get_operations",
23
+ "get_prices", "get_energy_mode", "set_energy_mode", "get_ai_plus", "update_ai_plus",
24
+ "plan_best_price_discharge", "plan_discharge_to_target"}
25
+ for t in tools:
26
+ if t.name in ("set_energy_mode", "update_ai_plus"):
27
+ assert "CHANGES THE SITE" in t.description and "Confirm with the user" in t.description
28
+ else:
29
+ assert "CHANGES THE SITE" not in t.description
30
+
31
+
32
+ def test_set_energy_mode_sends_only_the_given_fields_and_bearer_auth(monkeypatch):
33
+ seen = {}
34
+
35
+ def handler(request: httpx.Request) -> httpx.Response:
36
+ seen["auth"] = request.headers["authorization"]
37
+ seen["body"] = json.loads(request.content)
38
+ seen["url"] = str(request.url)
39
+ return httpx.Response(200, json={"energy_mode": "forced", "reverts_to": "amber_smart"})
40
+
41
+ monkeypatch.setattr(server, "_client", _client_with(handler))
42
+ out = json.loads(asyncio.run(server.set_energy_mode("sungrow:1", "forced", duration_minutes=60,
43
+ action="charge", power_w=5000, target_soc=90)))
44
+ assert out["reverts_to"] == "amber_smart"
45
+ assert seen["auth"] == "Bearer aivy_sk_test"
46
+ assert seen["url"].endswith("/sites/sungrow:1/energy-mode")
47
+ assert seen["body"] == {"mode": "forced", "duration_minutes": 60, "action": "charge", "power_w": 5000,
48
+ "target_soc": 90}
49
+
50
+
51
+ def test_api_errors_are_returned_as_data_not_raised(monkeypatch):
52
+ def handler(request: httpx.Request) -> httpx.Response:
53
+ return httpx.Response(403, json={"detail": {"error": "this API key is read-only"}})
54
+
55
+ monkeypatch.setattr(server, "_client", _client_with(handler))
56
+ out = json.loads(asyncio.run(server.update_ai_plus("sungrow:1", {"hard_floor": 20})))
57
+ assert out["error"].startswith("403") and "read-only" in out["error"]
58
+
59
+
60
+ def test_missing_key_is_a_clear_message(monkeypatch):
61
+ monkeypatch.delenv("AIVY_API_KEY", raising=False)
62
+ with pytest.raises(client_mod.AivyError, match="AIVY_API_KEY"):
63
+ client_mod.AivyClient(api_key=None)