netbox-rack-design-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.
- netbox_rack_design_mcp-0.1.0/LICENSE +201 -0
- netbox_rack_design_mcp-0.1.0/PKG-INFO +22 -0
- netbox_rack_design_mcp-0.1.0/README.md +5 -0
- netbox_rack_design_mcp-0.1.0/pyproject.toml +33 -0
- netbox_rack_design_mcp-0.1.0/setup.cfg +4 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp/__init__.py +3 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp/client.py +58 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp/server.py +293 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp.egg-info/PKG-INFO +22 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp.egg-info/SOURCES.txt +13 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp.egg-info/dependency_links.txt +1 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp.egg-info/entry_points.txt +2 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp.egg-info/requires.txt +5 -0
- netbox_rack_design_mcp-0.1.0/src/netbox_rack_design_mcp.egg-info/top_level.txt +1 -0
- netbox_rack_design_mcp-0.1.0/tests/test_tools.py +241 -0
|
@@ -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 Derivative
|
|
95
|
+
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 Petr Voronov
|
|
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,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: netbox-rack-design-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read-only MCP server for the netbox-rack-design plugin: execution plan, simulation and smart-hands work orders for Claude.
|
|
5
|
+
Author-email: Petr Voronov <ravenrs@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Source, https://github.com/ravenrs/netbox-rack-design
|
|
8
|
+
Keywords: netbox,netbox-plugin,mcp,claude
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: mcp[cli]<2,>=1.2
|
|
13
|
+
Requires-Dist: httpx>=0.27
|
|
14
|
+
Provides-Extra: test
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# netbox-rack-design-mcp
|
|
19
|
+
|
|
20
|
+
Read-only MCP server (stdio) for the [netbox-rack-design](https://github.com/ravenrs/netbox-rack-design)
|
|
21
|
+
NetBox plugin. Set `NETBOX_URL` and `NETBOX_TOKEN`, then run `netbox-rack-design-mcp`.
|
|
22
|
+
Setup for Claude Desktop and Claude Code: see `docs/mcp.md` in the plugin repository.
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
# netbox-rack-design-mcp
|
|
2
|
+
|
|
3
|
+
Read-only MCP server (stdio) for the [netbox-rack-design](https://github.com/ravenrs/netbox-rack-design)
|
|
4
|
+
NetBox plugin. Set `NETBOX_URL` and `NETBOX_TOKEN`, then run `netbox-rack-design-mcp`.
|
|
5
|
+
Setup for Claude Desktop and Claude Code: see `docs/mcp.md` in the plugin repository.
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77.0.3"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "netbox-rack-design-mcp"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Read-only MCP server for the netbox-rack-design plugin: execution plan, simulation and smart-hands work orders for Claude."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "Apache-2.0"
|
|
11
|
+
authors = [{name = "Petr Voronov", email = "ravenrs@gmail.com"}]
|
|
12
|
+
keywords = ["netbox", "netbox-plugin", "mcp", "claude"]
|
|
13
|
+
requires-python = ">=3.10"
|
|
14
|
+
dependencies = [
|
|
15
|
+
"mcp[cli]>=1.2,<2",
|
|
16
|
+
"httpx>=0.27",
|
|
17
|
+
]
|
|
18
|
+
|
|
19
|
+
[project.optional-dependencies]
|
|
20
|
+
test = ["pytest>=8"]
|
|
21
|
+
|
|
22
|
+
[project.urls]
|
|
23
|
+
Source = "https://github.com/ravenrs/netbox-rack-design"
|
|
24
|
+
|
|
25
|
+
[project.scripts]
|
|
26
|
+
netbox-rack-design-mcp = "netbox_rack_design_mcp.server:main"
|
|
27
|
+
|
|
28
|
+
[tool.setuptools.packages.find]
|
|
29
|
+
where = ["src"]
|
|
30
|
+
|
|
31
|
+
[tool.pytest.ini_options]
|
|
32
|
+
testpaths = ["tests"]
|
|
33
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Thin NetBox REST client. The token is only ever put in the Authorization header."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
API_ROOT = "/api/plugins/rack-design"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class NetBoxError(RuntimeError):
|
|
13
|
+
"""A NetBox call failed. The message never contains the token."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def auth_header(token: str) -> str:
|
|
17
|
+
# NetBox 4.5+ v2 tokens look like "nbt_<key>.<secret>" and use Bearer;
|
|
18
|
+
# older (v1) tokens use the "Token" scheme.
|
|
19
|
+
return f"Bearer {token}" if token.startswith("nbt_") else f"Token {token}"
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class NetBoxClient:
|
|
23
|
+
def __init__(self, url: str, token: str, *, transport: httpx.BaseTransport | None = None,
|
|
24
|
+
verify: bool = True, timeout: float = 60.0):
|
|
25
|
+
self._http = httpx.Client(
|
|
26
|
+
base_url=url.rstrip("/"),
|
|
27
|
+
headers={"Authorization": auth_header(token), "Accept": "application/json"},
|
|
28
|
+
transport=transport,
|
|
29
|
+
verify=verify,
|
|
30
|
+
timeout=timeout,
|
|
31
|
+
)
|
|
32
|
+
|
|
33
|
+
@classmethod
|
|
34
|
+
def from_env(cls) -> NetBoxClient:
|
|
35
|
+
url = os.environ.get("NETBOX_URL", "").strip()
|
|
36
|
+
token = os.environ.get("NETBOX_TOKEN", "").strip()
|
|
37
|
+
if not url or not token:
|
|
38
|
+
raise NetBoxError("Set NETBOX_URL and NETBOX_TOKEN in the MCP server environment.")
|
|
39
|
+
verify = os.environ.get("NETBOX_VERIFY_SSL", "true").strip().lower() not in ("0", "false", "no")
|
|
40
|
+
return cls(url, token, verify=verify)
|
|
41
|
+
|
|
42
|
+
def request(self, method: str, path: str, *, params=None, json=None):
|
|
43
|
+
clean = {k: v for k, v in (params or {}).items() if v is not None}
|
|
44
|
+
try:
|
|
45
|
+
resp = self._http.request(method, f"{API_ROOT}/{path}", params=clean, json=json)
|
|
46
|
+
except httpx.HTTPError as exc:
|
|
47
|
+
raise NetBoxError(f"NetBox request failed: {type(exc).__name__}") from None
|
|
48
|
+
if resp.status_code >= 400:
|
|
49
|
+
raise NetBoxError(f"NetBox answered {resp.status_code} for {method} {path}: {resp.text[:500]}")
|
|
50
|
+
if "json" in resp.headers.get("content-type", ""):
|
|
51
|
+
return resp.json()
|
|
52
|
+
return resp.text
|
|
53
|
+
|
|
54
|
+
def get(self, path: str, **params):
|
|
55
|
+
return self.request("GET", path, params=params)
|
|
56
|
+
|
|
57
|
+
def post(self, path: str, body):
|
|
58
|
+
return self.request("POST", path, json=body)
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
"""FastMCP stdio server. Read-only: nothing here changes a design in NetBox."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import logging
|
|
7
|
+
import sys
|
|
8
|
+
|
|
9
|
+
from mcp.server.fastmcp import FastMCP
|
|
10
|
+
|
|
11
|
+
from .client import NetBoxClient
|
|
12
|
+
|
|
13
|
+
# stdout carries the MCP protocol; every log line goes to stderr.
|
|
14
|
+
logging.basicConfig(stream=sys.stderr, level=logging.INFO, format="%(levelname)s %(name)s: %(message)s")
|
|
15
|
+
logging.getLogger("httpx").setLevel(logging.WARNING) # its request lines would show URLs
|
|
16
|
+
log = logging.getLogger("netbox_rack_design_mcp")
|
|
17
|
+
|
|
18
|
+
DEFAULT_TICKET_FORMAT = """\
|
|
19
|
+
DEFAULT SMART-HANDS TICKET FORMAT (use it only when the user gave no format of their own):
|
|
20
|
+
1. Header: design, step (number and title), site, rack(s), maintenance window.
|
|
21
|
+
2. Safety notes: power headroom per rack from the simulation ("R12 peaks at 6.7/8 kW"),
|
|
22
|
+
devices that stay live, the PDU and bank touched, any problems the plan reports.
|
|
23
|
+
3. Numbered actions in the order given, each with device, from/to rack and U, serial and
|
|
24
|
+
asset tag, power: for a move or add, "Unplug from" power_from (the current PDU outlets) and
|
|
25
|
+
"Plug into" power_to (the target rack's PDU and bank; the outlet is "any free outlet"
|
|
26
|
+
when no cable is planned).
|
|
27
|
+
4. A photo or check per action (for example "photo of R12 front after U20 is installed").
|
|
28
|
+
5. A rollback line: how to undo the step if something goes wrong.
|
|
29
|
+
6. What to report back: serials, photos, any deviation from the plan."""
|
|
30
|
+
|
|
31
|
+
mcp = FastMCP("rack-design")
|
|
32
|
+
|
|
33
|
+
_client: NetBoxClient | None = None
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def get_client() -> NetBoxClient:
|
|
37
|
+
global _client
|
|
38
|
+
if _client is None:
|
|
39
|
+
_client = NetBoxClient.from_env()
|
|
40
|
+
return _client
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def set_client(client: NetBoxClient | None) -> None:
|
|
44
|
+
"""Install a ready client (tests)."""
|
|
45
|
+
global _client
|
|
46
|
+
_client = client
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@mcp.tool()
|
|
50
|
+
def list_designs(site: str | None = None, status: str | None = None) -> dict:
|
|
51
|
+
"""List rack designs. Read-only.
|
|
52
|
+
|
|
53
|
+
site: site slug to filter by (for example "ams1"). status: design status
|
|
54
|
+
(for example "draft", "approved", "implemented")."""
|
|
55
|
+
data = get_client().get("designs/", site=site, status=status, limit=100)
|
|
56
|
+
return {
|
|
57
|
+
"count": data["count"],
|
|
58
|
+
"designs": [
|
|
59
|
+
{k: d.get(k) for k in ("id", "title", "status", "sites", "version", "url", "description")}
|
|
60
|
+
for d in data["results"]
|
|
61
|
+
],
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
@mcp.tool()
|
|
66
|
+
def get_design(design_id: int) -> dict:
|
|
67
|
+
"""Get one design with all its fields. Read-only."""
|
|
68
|
+
return get_client().get(f"designs/{design_id}/")
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _saved_order(placements: list[dict]) -> dict[int, list[tuple[int, int]]]:
|
|
72
|
+
"""Placement ids per step, in saved order. Blades follow their chassis and are not listed."""
|
|
73
|
+
by_step: dict[int, list[tuple[int, int]]] = {}
|
|
74
|
+
for p in placements:
|
|
75
|
+
step = p.get("step")
|
|
76
|
+
if not step or p.get("parent_placement") or p.get("base_parent_placement"):
|
|
77
|
+
continue
|
|
78
|
+
by_step.setdefault(step["index"], []).append((p.get("step_order") or 0, p["id"]))
|
|
79
|
+
return by_step
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _prune(value):
|
|
83
|
+
"""Drop null / empty values (False and 0 stay): they carry no information for a ticket."""
|
|
84
|
+
if isinstance(value, dict):
|
|
85
|
+
out = {k: _prune(v) for k, v in value.items()}
|
|
86
|
+
return {k: v for k, v in out.items() if v is not None and v != [] and v != {} and v != ""}
|
|
87
|
+
if isinstance(value, list):
|
|
88
|
+
return [_prune(v) for v in value]
|
|
89
|
+
return value
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
_BAD_BANK_STATES = ("warn", "critical", "overload")
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _where(loc: dict | None) -> dict | None:
|
|
96
|
+
"""A from/to location reduced to rack, U, face (and chassis/bay for a blade)."""
|
|
97
|
+
if not loc:
|
|
98
|
+
return None
|
|
99
|
+
out = {k: loc.get(k) for k in ("rack", "position", "face", "chassis", "bay") if loc.get(k)}
|
|
100
|
+
if "position" in out:
|
|
101
|
+
out["u"] = out.pop("position")
|
|
102
|
+
return out or None
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def _action_summary(act: dict) -> dict:
|
|
106
|
+
out = {
|
|
107
|
+
"placement_id": act.get("placement_id"),
|
|
108
|
+
"kind": act.get("kind"),
|
|
109
|
+
"device": (act.get("device") or {}).get("name"),
|
|
110
|
+
"from": _where(act.get("from")),
|
|
111
|
+
"to": _where(act.get("to")),
|
|
112
|
+
}
|
|
113
|
+
if act.get("children"):
|
|
114
|
+
out["blades"] = [(c.get("device") or {}).get("name") for c in act["children"]]
|
|
115
|
+
return out
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _lookup(client: NetBoxClient, design_id: int) -> tuple[dict, dict, list]:
|
|
119
|
+
"""(rack key -> name, placement id -> compact action, unscheduled compact actions),
|
|
120
|
+
from the saved work order."""
|
|
121
|
+
order = client.get(f"designs/{design_id}/work-order/", output="json")
|
|
122
|
+
names: dict[str, str] = {}
|
|
123
|
+
actions: dict[int, dict] = {}
|
|
124
|
+
for s in order.get("steps", []):
|
|
125
|
+
for row in s.get("power", []):
|
|
126
|
+
names[row["key"]] = row["rack"]
|
|
127
|
+
for act in s.get("actions", []):
|
|
128
|
+
actions[act["placement_id"]] = _action_summary(act)
|
|
129
|
+
unscheduled = [_action_summary(a) for a in order.get("unscheduled", [])]
|
|
130
|
+
for a in unscheduled:
|
|
131
|
+
actions[a["placement_id"]] = a
|
|
132
|
+
return names, actions, unscheduled
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def _compact_sim(entry: dict, names: dict[str, str]) -> dict:
|
|
136
|
+
"""One simulated step: per rack draw/capacity/util/state, only the hot banks, problems."""
|
|
137
|
+
racks, problems = [], []
|
|
138
|
+
for key, data in sorted((entry.get("racks") or {}).items(), key=lambda kv: names.get(kv[0], kv[0])):
|
|
139
|
+
name = names.get(key, key)
|
|
140
|
+
power = data.get("power") or {}
|
|
141
|
+
banks = []
|
|
142
|
+
for pdu_name, pdu in ((data.get("distribution") or {}).get("pdus") or {}).items():
|
|
143
|
+
for bank_id, bank in (pdu.get("banks") or {}).items():
|
|
144
|
+
if bank.get("state") in _BAD_BANK_STATES:
|
|
145
|
+
banks.append({
|
|
146
|
+
"pdu": pdu_name, "bank": bank_id, "state": bank["state"],
|
|
147
|
+
"load_w": round((bank.get("allocated_power") or 0) + (bank.get("planned_power") or 0)),
|
|
148
|
+
"limit_w": round(bank.get("max_power") or 0),
|
|
149
|
+
"pct": round(bank.get("util_pct") or 0),
|
|
150
|
+
})
|
|
151
|
+
racks.append({
|
|
152
|
+
"rack": name,
|
|
153
|
+
"draw_w": round(power.get("draw_w") or 0),
|
|
154
|
+
"capacity_w": round(power.get("capacity_w") or 0),
|
|
155
|
+
"util_pct": round(power.get("util_pct") or 0),
|
|
156
|
+
"state": power.get("state") or "",
|
|
157
|
+
"hot_banks": banks,
|
|
158
|
+
})
|
|
159
|
+
# keep EVERY problem (bank_over / bank_near too); hot_banks is extra detail.
|
|
160
|
+
problems += [
|
|
161
|
+
{"rack": name, "code": p.get("code"), "severity": p.get("severity"), "detail": p.get("detail")}
|
|
162
|
+
for p in data.get("problems") or []
|
|
163
|
+
]
|
|
164
|
+
return {"racks": racks, "problems": problems}
|
|
165
|
+
|
|
166
|
+
|
|
167
|
+
@mcp.tool(
|
|
168
|
+
description=(
|
|
169
|
+
"Get a design's execution plan as a COMPACT SUMMARY: per step its index, title and "
|
|
170
|
+
"actions (kind, device, from/to rack and U), plus the simulated power of each touched "
|
|
171
|
+
"rack (draw_w, capacity_w, util_pct, state), only the PDU banks that are warn/critical/"
|
|
172
|
+
"overload (hot_banks), and the problems found (code, severity, detail). Raw "
|
|
173
|
+
"distribution and per-outlet data are left out. Call it with detail=true ONLY when you "
|
|
174
|
+
"need the full simulation payload (every bank and outlet); that answer is very large "
|
|
175
|
+
"(>100k characters). For a technician ticket use get_work_order instead. Read-only. "
|
|
176
|
+
"This tool makes one POST (simulate-steps) with the SAVED order; that POST only "
|
|
177
|
+
"computes the simulation and changes nothing in NetBox."
|
|
178
|
+
)
|
|
179
|
+
)
|
|
180
|
+
def get_execution_plan(design_id: int, detail: bool = False) -> dict:
|
|
181
|
+
client = get_client()
|
|
182
|
+
steps = sorted(client.get("design-steps/", design_id=design_id, limit=0)["results"],
|
|
183
|
+
key=lambda s: s["index"])
|
|
184
|
+
placements = client.get("placements/", design_id=design_id, limit=0)["results"]
|
|
185
|
+
by_step = _saved_order(placements)
|
|
186
|
+
ordered = [[pid for _, pid in sorted(by_step.get(s["index"], []))] for s in steps]
|
|
187
|
+
simulation = (client.post(f"designs/{design_id}/simulate-steps/", {"steps": ordered}).get("steps", [])
|
|
188
|
+
if ordered else [])
|
|
189
|
+
if detail:
|
|
190
|
+
names = {p["id"]: p.get("display") for p in placements}
|
|
191
|
+
return {
|
|
192
|
+
"design_id": design_id,
|
|
193
|
+
"steps": [
|
|
194
|
+
{
|
|
195
|
+
"index": s["index"],
|
|
196
|
+
"title": s.get("title", ""),
|
|
197
|
+
"actions": [{"placement_id": pid, "display": names.get(pid)} for pid in ordered[i]],
|
|
198
|
+
}
|
|
199
|
+
for i, s in enumerate(steps)
|
|
200
|
+
],
|
|
201
|
+
"unscheduled": [
|
|
202
|
+
{"placement_id": p["id"], "display": p.get("display")}
|
|
203
|
+
for p in placements
|
|
204
|
+
if not p.get("step") and not p.get("parent_placement") and not p.get("base_parent_placement")
|
|
205
|
+
],
|
|
206
|
+
"simulation": simulation,
|
|
207
|
+
}
|
|
208
|
+
rack_names, actions, unscheduled = _lookup(client, design_id)
|
|
209
|
+
by_index = {e["index"]: e for e in simulation}
|
|
210
|
+
out_steps = []
|
|
211
|
+
for i, s in enumerate(steps, start=1):
|
|
212
|
+
row = {
|
|
213
|
+
"index": s["index"],
|
|
214
|
+
"title": s.get("title", ""),
|
|
215
|
+
"actions": [actions.get(pid, {"placement_id": pid}) for pid in ordered[i - 1]],
|
|
216
|
+
}
|
|
217
|
+
row.update(_compact_sim(by_index.get(i, {}), rack_names))
|
|
218
|
+
out_steps.append(row)
|
|
219
|
+
return {"design_id": design_id, "total_steps": len(steps), "steps": out_steps,
|
|
220
|
+
"unscheduled": unscheduled}
|
|
221
|
+
|
|
222
|
+
|
|
223
|
+
@mcp.tool(
|
|
224
|
+
description=(
|
|
225
|
+
"Get the work order of a design: every step (or only `step`) with its actions in the "
|
|
226
|
+
"safe order. Per action: kind (add/move/remove), device name, type, U height, "
|
|
227
|
+
"full-depth flag, serial, asset tag, from and to (site, location, rack, U, face), "
|
|
228
|
+
"power cabling (power_from: the PDU outlets the device leaves; power_to: the PDU and bank it "
|
|
229
|
+
"plugs into on the target rack, outlet \"any free outlet\" unless cabled), the target status afterwards and a NetBox "
|
|
230
|
+
"link; per step: its index, total_steps (say \"Step 1 of 7\", never \"1 of 1\", even "
|
|
231
|
+
"when you ask for one step), the power headroom per rack and the problems the "
|
|
232
|
+
"simulation found. Unscheduled actions come in a separate list. This is already the "
|
|
233
|
+
"compact, technician-ready payload. Read-only.\n\n"
|
|
234
|
+
"The user's own instructions about the ticket (format, language, destination, fields) "
|
|
235
|
+
"ALWAYS win. Only when the user gave none, write a smart-hands ticket like this:\n"
|
|
236
|
+
+ DEFAULT_TICKET_FORMAT
|
|
237
|
+
)
|
|
238
|
+
)
|
|
239
|
+
def get_work_order(design_id: int, step: int | None = None) -> dict:
|
|
240
|
+
return _prune(get_client().get(f"designs/{design_id}/work-order/", step=step, output="json"))
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@mcp.tool(
|
|
244
|
+
description=(
|
|
245
|
+
"What-if: simulate a PROPOSED order of placements without saving it. steps is a list "
|
|
246
|
+
"of steps, each a list of placement ids (blades are not listed, they follow their "
|
|
247
|
+
"chassis). Returns a COMPACT SUMMARY per step: actions, per touched rack draw_w/"
|
|
248
|
+
"capacity_w/util_pct/state, only the warn/critical/overload banks (hot_banks) and "
|
|
249
|
+
"problems (rack_over, bank_over, u_conflict, unpowered ...). Pass detail=true ONLY "
|
|
250
|
+
"when you need the raw simulation (every bank and outlet; >100k characters). This is "
|
|
251
|
+
"a POST, but it only computes a result: it changes nothing in NetBox."
|
|
252
|
+
)
|
|
253
|
+
)
|
|
254
|
+
def simulate_order(design_id: int, steps: list[list[int]], detail: bool = False) -> dict:
|
|
255
|
+
client = get_client()
|
|
256
|
+
raw = client.post(f"designs/{design_id}/simulate-steps/", {"steps": steps})
|
|
257
|
+
if detail:
|
|
258
|
+
return raw
|
|
259
|
+
rack_names, actions, _ = _lookup(client, design_id)
|
|
260
|
+
out_steps = []
|
|
261
|
+
for entry in raw.get("steps", []):
|
|
262
|
+
i = entry["index"]
|
|
263
|
+
row = {
|
|
264
|
+
"index": i,
|
|
265
|
+
"actions": [actions.get(pid, {"placement_id": pid}) for pid in (steps[i - 1] if i <= len(steps) else [])],
|
|
266
|
+
}
|
|
267
|
+
row.update(_compact_sim(entry, rack_names))
|
|
268
|
+
out_steps.append(row)
|
|
269
|
+
return {"design_id": design_id, "total_steps": len(steps), "steps": out_steps}
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
@mcp.prompt()
|
|
273
|
+
def smart_hands_ticket(design_id: int, step: int, instructions: str = "") -> str:
|
|
274
|
+
"""Write a smart-hands ticket for one step of a design's plan (Claude Code)."""
|
|
275
|
+
order = _prune(get_client().get(f"designs/{design_id}/work-order/", step=step, output="json"))
|
|
276
|
+
if instructions.strip():
|
|
277
|
+
rules = ("Follow these instructions from the user for the ticket; they replace any "
|
|
278
|
+
"default format:\n" + instructions.strip())
|
|
279
|
+
else:
|
|
280
|
+
rules = "The user gave no format. " + DEFAULT_TICKET_FORMAT
|
|
281
|
+
return (
|
|
282
|
+
f"Write a smart-hands ticket for step {step} of design {design_id}.\n\n{rules}\n\n"
|
|
283
|
+
f"Work order (JSON):\n{json.dumps(order, indent=2)}"
|
|
284
|
+
)
|
|
285
|
+
|
|
286
|
+
|
|
287
|
+
def main() -> None:
|
|
288
|
+
log.info("starting netbox-rack-design-mcp (stdio)")
|
|
289
|
+
mcp.run(transport="stdio")
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
if __name__ == "__main__":
|
|
293
|
+
main()
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: netbox-rack-design-mcp
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Read-only MCP server for the netbox-rack-design plugin: execution plan, simulation and smart-hands work orders for Claude.
|
|
5
|
+
Author-email: Petr Voronov <ravenrs@gmail.com>
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Source, https://github.com/ravenrs/netbox-rack-design
|
|
8
|
+
Keywords: netbox,netbox-plugin,mcp,claude
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Requires-Dist: mcp[cli]<2,>=1.2
|
|
13
|
+
Requires-Dist: httpx>=0.27
|
|
14
|
+
Provides-Extra: test
|
|
15
|
+
Requires-Dist: pytest>=8; extra == "test"
|
|
16
|
+
Dynamic: license-file
|
|
17
|
+
|
|
18
|
+
# netbox-rack-design-mcp
|
|
19
|
+
|
|
20
|
+
Read-only MCP server (stdio) for the [netbox-rack-design](https://github.com/ravenrs/netbox-rack-design)
|
|
21
|
+
NetBox plugin. Set `NETBOX_URL` and `NETBOX_TOKEN`, then run `netbox-rack-design-mcp`.
|
|
22
|
+
Setup for Claude Desktop and Claude Code: see `docs/mcp.md` in the plugin repository.
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/netbox_rack_design_mcp/__init__.py
|
|
5
|
+
src/netbox_rack_design_mcp/client.py
|
|
6
|
+
src/netbox_rack_design_mcp/server.py
|
|
7
|
+
src/netbox_rack_design_mcp.egg-info/PKG-INFO
|
|
8
|
+
src/netbox_rack_design_mcp.egg-info/SOURCES.txt
|
|
9
|
+
src/netbox_rack_design_mcp.egg-info/dependency_links.txt
|
|
10
|
+
src/netbox_rack_design_mcp.egg-info/entry_points.txt
|
|
11
|
+
src/netbox_rack_design_mcp.egg-info/requires.txt
|
|
12
|
+
src/netbox_rack_design_mcp.egg-info/top_level.txt
|
|
13
|
+
tests/test_tools.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
netbox_rack_design_mcp
|
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
import httpx
|
|
4
|
+
import pytest
|
|
5
|
+
|
|
6
|
+
from netbox_rack_design_mcp import server
|
|
7
|
+
from netbox_rack_design_mcp.client import NetBoxClient, NetBoxError, auth_header
|
|
8
|
+
|
|
9
|
+
TOKEN = "s3cret-token-value"
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Recorder:
|
|
13
|
+
def __init__(self, routes):
|
|
14
|
+
self.routes = routes # {(method, path): json-able or callable}
|
|
15
|
+
self.calls = []
|
|
16
|
+
|
|
17
|
+
def __call__(self, request: httpx.Request) -> httpx.Response:
|
|
18
|
+
self.calls.append(request)
|
|
19
|
+
key = (request.method, request.url.path)
|
|
20
|
+
if key not in self.routes:
|
|
21
|
+
return httpx.Response(404, json={"detail": "not found"})
|
|
22
|
+
body = self.routes[key]
|
|
23
|
+
return httpx.Response(200, json=body(request) if callable(body) else body)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def install(routes):
|
|
27
|
+
rec = Recorder(routes)
|
|
28
|
+
server.set_client(NetBoxClient("https://nb.example", TOKEN, transport=httpx.MockTransport(rec)))
|
|
29
|
+
return rec
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
@pytest.fixture(autouse=True)
|
|
33
|
+
def _reset():
|
|
34
|
+
yield
|
|
35
|
+
server.set_client(None)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
API = "/api/plugins/rack-design/"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def test_list_designs_passes_filters_and_trims():
|
|
42
|
+
rec = install({("GET", API + "designs/"): {
|
|
43
|
+
"count": 1, "results": [{"id": 3, "title": "Q3", "status": "draft", "sites": [], "extra": 1}]}})
|
|
44
|
+
out = server.list_designs(site="ams1", status="draft")
|
|
45
|
+
assert out["count"] == 1 and out["designs"][0]["title"] == "Q3"
|
|
46
|
+
assert "extra" not in out["designs"][0]
|
|
47
|
+
req = rec.calls[0]
|
|
48
|
+
assert req.url.params["site"] == "ams1" and req.url.params["status"] == "draft"
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def test_list_designs_omits_unset_filters():
|
|
52
|
+
rec = install({("GET", API + "designs/"): {"count": 0, "results": []}})
|
|
53
|
+
server.list_designs()
|
|
54
|
+
assert "site" not in rec.calls[0].url.params and "status" not in rec.calls[0].url.params
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def test_get_design():
|
|
58
|
+
install({("GET", API + "designs/7/"): {"id": 7, "title": "X"}})
|
|
59
|
+
assert server.get_design(7)["title"] == "X"
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def test_get_work_order_sends_step_and_json_format():
|
|
63
|
+
rec = install({("GET", API + "designs/7/work-order/"): {"steps": []}})
|
|
64
|
+
assert server.get_work_order(7, step=2) == {}
|
|
65
|
+
params = rec.calls[0].url.params
|
|
66
|
+
assert params["step"] == "2" and params["output"] == "json"
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def test_get_work_order_without_step_omits_it():
|
|
70
|
+
rec = install({("GET", API + "designs/7/work-order/"): {"steps": []}})
|
|
71
|
+
server.get_work_order(7)
|
|
72
|
+
assert "step" not in rec.calls[0].url.params
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _plan_routes(n_steps=2):
|
|
76
|
+
"""A realistic Rebalance-sized plan: n steps, 2 racks, 2 PDUs x 12 banks with outlets."""
|
|
77
|
+
steps = {"results": [{"index": i, "title": f"Window {i}"} for i in range(n_steps, 0, -1)]}
|
|
78
|
+
placements, wo_steps, sim_steps = [], [], []
|
|
79
|
+
for i in range(1, n_steps + 1):
|
|
80
|
+
pid = 100 + i
|
|
81
|
+
placements.append({"id": pid, "display": f"Move: srv-{i}", "step": {"index": i}, "step_order": 1})
|
|
82
|
+
wo_steps.append({
|
|
83
|
+
"index": i, "total_steps": n_steps,
|
|
84
|
+
"power": [{"rack": "A1", "key": "r:1"}, {"rack": "A2", "key": "r:2"}],
|
|
85
|
+
"actions": [{"placement_id": pid, "kind": "move", "device": {"name": f"srv-{i}", "serial": "S" * 40},
|
|
86
|
+
"from": {"rack": "A1", "position": "10", "face": "front", "site": "FRA"},
|
|
87
|
+
"to": {"rack": "A2", "position": "20", "face": "front", "site": "FRA"},
|
|
88
|
+
"children": [], "power": {"cabling": [{"outlet": "o"}] * 4}}],
|
|
89
|
+
})
|
|
90
|
+
racks = {}
|
|
91
|
+
for key, name in (("r:1", "A1"), ("r:2", "A2")):
|
|
92
|
+
pdus = {}
|
|
93
|
+
for pdu in ("pdu-a", "pdu-b"):
|
|
94
|
+
banks = {}
|
|
95
|
+
for b in range(1, 13):
|
|
96
|
+
banks[str(b)] = {
|
|
97
|
+
"allocated_power": 100.0 * b, "planned_power": 0.0, "max_power": 1500.0,
|
|
98
|
+
"util_pct": 100.0 * b / 1500 * 100, "state": "warn" if b == 12 else "ok",
|
|
99
|
+
"outlets": {str(o): {"name": f"o{o}", "device": "x" * 30, "power": 12.5}
|
|
100
|
+
for o in range(1, 25)},
|
|
101
|
+
}
|
|
102
|
+
pdus[pdu] = {"banks": banks}
|
|
103
|
+
racks[key] = {
|
|
104
|
+
"power": {"draw_w": 5000.4, "capacity_w": 8000, "util_pct": 62.5, "state": "ok"},
|
|
105
|
+
"distribution": {"pdus": pdus}, "distribution_status": {"state": "ok"},
|
|
106
|
+
"problems": [{"code": "rack_near", "severity": "warning", "detail": f"{name}: 5000 W of 8000 W"},
|
|
107
|
+
{"code": "bank_near", "severity": "warning", "detail": "dup of hot_banks"}],
|
|
108
|
+
}
|
|
109
|
+
sim_steps.append({"index": i, "racks": racks})
|
|
110
|
+
placements.append({"id": 14, "display": "loose", "step": None})
|
|
111
|
+
routes = {
|
|
112
|
+
("GET", API + "design-steps/"): steps,
|
|
113
|
+
("GET", API + "placements/"): {"results": placements},
|
|
114
|
+
("GET", API + "designs/5/work-order/"): {"steps": wo_steps, "unscheduled": [
|
|
115
|
+
{"placement_id": 14, "kind": "add", "device": {"name": "loose"}, "from": None,
|
|
116
|
+
"to": {"rack": "A1", "position": "5"}, "children": []}]},
|
|
117
|
+
("POST", API + "designs/5/simulate-steps/"): {"steps": sim_steps},
|
|
118
|
+
}
|
|
119
|
+
return routes, sim_steps
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def test_get_execution_plan_posts_the_saved_order_and_is_compact():
|
|
123
|
+
routes, _ = _plan_routes(2)
|
|
124
|
+
rec = install(routes)
|
|
125
|
+
out = server.get_execution_plan(5)
|
|
126
|
+
post = [c for c in rec.calls if c.method == "POST"][0]
|
|
127
|
+
assert json.loads(post.content) == {"steps": [[101], [102]]}
|
|
128
|
+
assert [s["index"] for s in out["steps"]] == [1, 2] and out["total_steps"] == 2
|
|
129
|
+
step = out["steps"][0]
|
|
130
|
+
assert step["title"] == "Window 1"
|
|
131
|
+
assert step["actions"] == [{
|
|
132
|
+
"placement_id": 101, "kind": "move", "device": "srv-1",
|
|
133
|
+
"from": {"rack": "A1", "face": "front", "u": "10"},
|
|
134
|
+
"to": {"rack": "A2", "face": "front", "u": "20"}}]
|
|
135
|
+
a1 = step["racks"][0]
|
|
136
|
+
assert (a1["rack"], a1["draw_w"], a1["capacity_w"], a1["util_pct"], a1["state"]) == ("A1", 5000, 8000, 62, "ok")
|
|
137
|
+
assert len(a1["hot_banks"]) == 2 and a1["hot_banks"][0]["bank"] == "12"
|
|
138
|
+
assert set(a1["hot_banks"][0]) == {"pdu", "bank", "state", "load_w", "limit_w", "pct"}
|
|
139
|
+
assert step["problems"][0] == {"rack": "A1", "code": "rack_near", "severity": "warning",
|
|
140
|
+
"detail": "A1: 5000 W of 8000 W"}
|
|
141
|
+
# every problem is kept, bank_near included; hot_banks is extra detail
|
|
142
|
+
assert [p["code"] for p in step["problems"]] == ["rack_near", "bank_near", "rack_near", "bank_near"]
|
|
143
|
+
assert [u["placement_id"] for u in out["unscheduled"]] == [14]
|
|
144
|
+
assert "distribution" not in json.dumps(out) and "outlets" not in json.dumps(out)
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def test_get_execution_plan_detail_returns_the_full_simulation():
|
|
148
|
+
routes, sim = _plan_routes(2)
|
|
149
|
+
install(routes)
|
|
150
|
+
out = server.get_execution_plan(5, detail=True)
|
|
151
|
+
assert out["simulation"] == sim
|
|
152
|
+
assert [a["placement_id"] for a in out["steps"][0]["actions"]] == [101]
|
|
153
|
+
assert [u["placement_id"] for u in out["unscheduled"]] == [14]
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def test_compact_plan_of_a_rebalance_sized_design_stays_small():
|
|
157
|
+
routes, _ = _plan_routes(7)
|
|
158
|
+
install(routes)
|
|
159
|
+
compact = len(json.dumps(server.get_execution_plan(5)))
|
|
160
|
+
full = len(json.dumps(server.get_execution_plan(5, detail=True)))
|
|
161
|
+
assert compact < 9000, compact
|
|
162
|
+
assert full > 10 * compact
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def test_simulate_order_is_compact_by_default_and_detail_gives_raw():
|
|
166
|
+
routes, sim = _plan_routes(7)
|
|
167
|
+
rec = install(routes)
|
|
168
|
+
out = server.simulate_order(5, [[101], [102]])
|
|
169
|
+
assert json.loads([c for c in rec.calls if c.method == "POST"][0].content) == {"steps": [[101], [102]]}
|
|
170
|
+
assert len(json.dumps(out)) < 9000
|
|
171
|
+
assert out["steps"][0]["racks"][1]["rack"] == "A2"
|
|
172
|
+
assert out["steps"][0]["actions"][0]["device"] == "srv-1"
|
|
173
|
+
assert server.simulate_order(5, [[101]], detail=True) == {"steps": sim}
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def test_http_error_is_reported_without_the_token():
|
|
177
|
+
install({})
|
|
178
|
+
with pytest.raises(NetBoxError) as exc:
|
|
179
|
+
server.get_design(1)
|
|
180
|
+
assert "404" in str(exc.value)
|
|
181
|
+
assert TOKEN not in str(exc.value)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def test_token_only_in_authorization_header():
|
|
185
|
+
rec = install({("GET", API + "designs/1/"): {}})
|
|
186
|
+
server.get_design(1)
|
|
187
|
+
req = rec.calls[0]
|
|
188
|
+
assert req.headers["authorization"] == f"Token {TOKEN}"
|
|
189
|
+
assert TOKEN not in str(req.url)
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def test_v2_token_uses_bearer():
|
|
193
|
+
assert auth_header("nbt_abc.def") == "Bearer nbt_abc.def"
|
|
194
|
+
assert auth_header("plain") == "Token plain"
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def test_missing_env_is_a_clear_error(monkeypatch):
|
|
198
|
+
monkeypatch.delenv("NETBOX_URL", raising=False)
|
|
199
|
+
monkeypatch.delenv("NETBOX_TOKEN", raising=False)
|
|
200
|
+
with pytest.raises(NetBoxError, match="NETBOX_URL"):
|
|
201
|
+
NetBoxClient.from_env()
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def test_tools_are_registered_and_work_order_description_has_the_default_format():
|
|
205
|
+
import asyncio
|
|
206
|
+
|
|
207
|
+
tools = {t.name: t for t in asyncio.run(server.mcp.list_tools())}
|
|
208
|
+
assert set(tools) == {
|
|
209
|
+
"list_designs", "get_design", "get_execution_plan", "get_work_order", "simulate_order"}
|
|
210
|
+
desc = tools["get_work_order"].description
|
|
211
|
+
assert "ALWAYS win" in desc
|
|
212
|
+
for word in ("Header", "Safety notes", "photo", "rollback", "report back"):
|
|
213
|
+
assert word.lower() in desc.lower()
|
|
214
|
+
assert "changes nothing" in tools["simulate_order"].description
|
|
215
|
+
assert "changes nothing" in tools["get_execution_plan"].description
|
|
216
|
+
for name in ("get_execution_plan", "simulate_order"):
|
|
217
|
+
assert "COMPACT" in tools[name].description and "detail=true" in tools[name].description
|
|
218
|
+
assert "total_steps" in desc
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def test_prompt_uses_user_instructions_over_default():
|
|
222
|
+
install({("GET", API + "designs/5/work-order/"): {"steps": [{"index": 1}]}})
|
|
223
|
+
text = server.smart_hands_ticket(5, 1, instructions="Write it in Jira wiki markup.")
|
|
224
|
+
assert "Jira wiki markup" in text and "DEFAULT SMART-HANDS" not in text
|
|
225
|
+
assert '"index": 1' in text
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
def test_prompt_falls_back_to_default_format():
|
|
229
|
+
install({("GET", API + "designs/5/work-order/"): {"steps": []}})
|
|
230
|
+
assert "DEFAULT SMART-HANDS" in server.smart_hands_ticket(5, 1)
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def test_work_order_drops_empty_values_but_keeps_false_and_zero():
|
|
234
|
+
install({("GET", API + "designs/7/work-order/"): {
|
|
235
|
+
"total_steps": 3, "steps": [{"index": 1, "total_steps": 3, "problems": [], "actions": [
|
|
236
|
+
{"placement_id": 1, "stale": False, "bay": None, "children": [], "to": {"u": 0, "face": ""}}]}]}})
|
|
237
|
+
out = server.get_work_order(7)
|
|
238
|
+
assert out["total_steps"] == 3 and out["steps"][0]["total_steps"] == 3
|
|
239
|
+
act = out["steps"][0]["actions"][0]
|
|
240
|
+
assert act == {"placement_id": 1, "stale": False, "to": {"u": 0}}
|
|
241
|
+
assert "problems" not in out["steps"][0]
|