netbox-mcp-server 1.3.0__py3-none-any.whl

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
+ """NetBox MCP Server - Read-only MCP server for NetBox infrastructure data."""
2
+
3
+ __version__ = "1.3.0" # Auto-managed by semantic-release
4
+
5
+ __all__ = ["NETBOX_OBJECT_TYPES", "NetBoxRestClient", "Settings"]
6
+
7
+ from netbox_mcp_server.config import Settings
8
+ from netbox_mcp_server.netbox_client import NetBoxRestClient
9
+ from netbox_mcp_server.netbox_types import NETBOX_OBJECT_TYPES
@@ -0,0 +1,6 @@
1
+ """Entry point for python -m netbox_mcp_server execution."""
2
+
3
+ from netbox_mcp_server.server import main
4
+
5
+ if __name__ == "__main__":
6
+ main()
@@ -0,0 +1,225 @@
1
+ """Configuration management for NetBox MCP Server."""
2
+
3
+ import logging
4
+ import logging.config
5
+ from typing import Any, Literal
6
+ from urllib.parse import urlparse
7
+
8
+ from pydantic import AnyUrl, Field, SecretStr, field_validator, model_validator
9
+ from pydantic_settings import BaseSettings, SettingsConfigDict
10
+
11
+
12
+ class Settings(BaseSettings):
13
+ """
14
+ Centralized configuration for NetBox MCP Server.
15
+
16
+ Configuration precedence: CLI > Environment > .env file > Defaults
17
+
18
+ Environment variables should match field names (e.g., NETBOX_URL, TRANSPORT).
19
+ """
20
+
21
+ # ===== Core NetBox Settings =====
22
+ netbox_url: AnyUrl
23
+ """Base URL of the NetBox instance (e.g., https://netbox.example.com/)"""
24
+
25
+ netbox_token: SecretStr | None = None
26
+ """API token for NetBox authentication (treated as secret).
27
+
28
+ Required unless token_passthrough is enabled.
29
+ """
30
+
31
+ token_passthrough: bool = False
32
+ """Use each HTTP client's own NetBox token instead of a shared NETBOX_TOKEN.
33
+
34
+ Clients send 'Authorization: Bearer <netbox token>'. The server checks the token
35
+ against NetBox and makes every API call with it, so NetBox applies that user's
36
+ permissions. Only valid with transport='http'.
37
+ """
38
+
39
+ # ===== Transport Settings =====
40
+ transport: Literal["stdio", "http"] = "stdio"
41
+ """MCP transport protocol to use (stdio for Claude Desktop, http for web clients)"""
42
+
43
+ host: str = "127.0.0.1"
44
+ """Host address to bind HTTP server (only used when transport='http')"""
45
+
46
+ port: int = 8000
47
+ """Port to bind HTTP server (only used when transport='http')"""
48
+
49
+ cors_origins: list[str] = Field(
50
+ default_factory=list,
51
+ description="Browser origins allowed for HTTP CORS. Use * to allow any origin.",
52
+ )
53
+
54
+ mcp_auth_token: SecretStr | None = Field(
55
+ default=None,
56
+ description=(
57
+ "Optional bearer token required on the HTTP transport endpoint. "
58
+ "When set, requests to the MCP endpoint must send "
59
+ "'Authorization: Bearer <token>'. Only applied when transport='http'."
60
+ ),
61
+ )
62
+ """Optional bearer token protecting the HTTP transport endpoint (treated as secret)"""
63
+
64
+ # ===== Plugin Discovery Settings =====
65
+ enable_plugin_discovery: bool = False
66
+ """Whether to auto-discover plugin object types from NetBox at startup"""
67
+
68
+ # ===== Security Settings =====
69
+ verify_ssl: bool = True
70
+ """Whether to verify SSL certificates when connecting to NetBox"""
71
+
72
+ # ===== Observability Settings =====
73
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"] = "INFO"
74
+ """Logging verbosity level"""
75
+
76
+ # ===== Pydantic Configuration =====
77
+ model_config = SettingsConfigDict(
78
+ env_file=".env",
79
+ env_file_encoding="utf-8",
80
+ env_prefix="", # No prefix, use field names directly
81
+ extra="ignore", # Ignore unknown environment variables
82
+ case_sensitive=False, # Environment variables are case-insensitive
83
+ )
84
+
85
+ # ===== Validators =====
86
+
87
+ @field_validator("port")
88
+ @classmethod
89
+ def validate_port(cls, v: int) -> int:
90
+ """Ensure port is in valid range."""
91
+ if not (0 < v < 65536):
92
+ raise ValueError(f"Port must be between 1 and 65535, got {v}")
93
+ return v
94
+
95
+ @field_validator("mcp_auth_token", mode="after")
96
+ @classmethod
97
+ def normalize_auth_token(cls, v: SecretStr | None) -> SecretStr | None:
98
+ """Treat an empty or whitespace-only token as unset.
99
+
100
+ A present-but-empty value (e.g. an unpopulated container secret
101
+ rendering as MCP_AUTH_TOKEN=) would otherwise build a verifier that
102
+ accepts an empty bearer while the server logs that auth is enabled.
103
+ Normalizing to None here keeps every consumer in agreement.
104
+ """
105
+ if v is not None and not v.get_secret_value().strip():
106
+ return None
107
+ return v
108
+
109
+ @field_validator("netbox_url")
110
+ @classmethod
111
+ def validate_netbox_url(cls, v: AnyUrl) -> AnyUrl:
112
+ """Ensure NetBox URL has a scheme and host."""
113
+ if not v.scheme or not v.host:
114
+ raise ValueError(
115
+ "NETBOX_URL must include scheme and host (e.g., https://netbox.example.com/)"
116
+ )
117
+ return v
118
+
119
+ @model_validator(mode="after")
120
+ def validate_token_settings(self) -> "Settings":
121
+ """Ensure exactly one way of getting NetBox tokens is configured."""
122
+ if not self.token_passthrough:
123
+ if self.netbox_token is None:
124
+ raise ValueError("netbox_token is required unless TOKEN_PASSTHROUGH is enabled")
125
+ return self
126
+
127
+ if self.transport != "http":
128
+ raise ValueError("TOKEN_PASSTHROUGH requires TRANSPORT=http")
129
+ # A shared token next to per-user tokens would be an easy way to leak
130
+ # one user's access to everyone, so refuse it outright.
131
+ if self.netbox_token is not None:
132
+ raise ValueError("NETBOX_TOKEN must not be set when TOKEN_PASSTHROUGH is enabled")
133
+ # Both use the Authorization header, so they cannot be combined.
134
+ if self.mcp_auth_token is not None:
135
+ raise ValueError("MCP_AUTH_TOKEN cannot be used with TOKEN_PASSTHROUGH")
136
+ if self.enable_plugin_discovery:
137
+ raise ValueError(
138
+ "ENABLE_PLUGIN_DISCOVERY needs a shared NETBOX_TOKEN and cannot be used "
139
+ "with TOKEN_PASSTHROUGH"
140
+ )
141
+ return self
142
+
143
+ @field_validator("cors_origins", mode="before")
144
+ @classmethod
145
+ def validate_cors_origins(cls, v: object) -> list[str]:
146
+ """Ensure each CORS origin is a valid URL."""
147
+ for origin in v:
148
+ if origin == "*":
149
+ continue
150
+ parsed = urlparse(origin)
151
+ if not parsed.scheme or not parsed.netloc:
152
+ raise ValueError(
153
+ f"Invalid CORS_ORIGIN: {origin!r} (expected format: http://host:port)"
154
+ )
155
+ return v
156
+
157
+ def get_effective_config_summary(self) -> dict:
158
+ """
159
+ Return a non-secret summary of effective configuration for logging.
160
+
161
+ Returns:
162
+ Dictionary with configuration values (secrets masked)
163
+ """
164
+ summary: dict[str, Any] = {
165
+ "netbox_url": str(self.netbox_url),
166
+ "netbox_token": "***REDACTED***" if self.netbox_token else None,
167
+ "token_passthrough": self.token_passthrough,
168
+ "transport": self.transport,
169
+ "verify_ssl": self.verify_ssl,
170
+ "enable_plugin_discovery": self.enable_plugin_discovery,
171
+ "log_level": self.log_level,
172
+ }
173
+ if self.transport == "http":
174
+ summary.update(
175
+ {
176
+ "host": self.host,
177
+ "port": self.port,
178
+ "cors_origins": self.cors_origins,
179
+ "mcp_auth_token": "***REDACTED***" if self.mcp_auth_token else None,
180
+ }
181
+ )
182
+ return summary
183
+
184
+
185
+ def configure_logging(
186
+ log_level: Literal["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"],
187
+ ) -> None:
188
+ """
189
+ Configure structured logging using dictConfig.
190
+
191
+ Args:
192
+ log_level: Logging level (DEBUG, INFO, WARNING, ERROR, CRITICAL)
193
+ """
194
+ config: dict[str, Any] = {
195
+ "version": 1,
196
+ "disable_existing_loggers": False,
197
+ "formatters": {
198
+ "console": {
199
+ "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
200
+ "datefmt": "%Y-%m-%d %H:%M:%S",
201
+ },
202
+ },
203
+ "handlers": {
204
+ "console": {
205
+ "class": "logging.StreamHandler",
206
+ "formatter": "console",
207
+ "stream": "ext://sys.stderr",
208
+ },
209
+ },
210
+ "loggers": {
211
+ # Suppress noisy HTTP client logs unless DEBUG
212
+ "urllib3": {
213
+ "level": "WARNING" if log_level != "DEBUG" else "DEBUG",
214
+ },
215
+ "httpx": {
216
+ "level": "WARNING" if log_level != "DEBUG" else "DEBUG",
217
+ },
218
+ },
219
+ "root": {
220
+ "level": log_level,
221
+ "handlers": ["console"],
222
+ },
223
+ }
224
+
225
+ logging.config.dictConfig(config)
@@ -0,0 +1,375 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ NetBox Client Library
4
+
5
+ This module provides a base class for NetBox client implementations and a REST API implementation.
6
+ """
7
+
8
+ import abc
9
+ from typing import Any
10
+
11
+ import httpx
12
+
13
+
14
+ class NetBoxClientBase(abc.ABC):
15
+ """
16
+ Abstract base class for NetBox client implementations.
17
+
18
+ This class defines the interface for CRUD operations that can be implemented
19
+ either via the REST API or directly via the ORM in a NetBox plugin.
20
+ """
21
+
22
+ @abc.abstractmethod
23
+ def get(
24
+ self,
25
+ endpoint: str,
26
+ id: int | None = None,
27
+ params: dict[str, Any] | None = None,
28
+ fallback_endpoint: str | None = None,
29
+ ) -> dict[str, Any] | list[dict[str, Any]]:
30
+ """
31
+ Retrieve one or more objects from NetBox.
32
+
33
+ Args:
34
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
35
+ id: Optional ID to retrieve a specific object
36
+ params: Optional query parameters for filtering
37
+ fallback_endpoint: Optional alternative endpoint to try if primary returns 404
38
+ (used for NetBox version compatibility)
39
+
40
+ Returns:
41
+ For single object queries (with id): Returns the object dict
42
+ For list queries (without id): Returns the full paginated response dict with:
43
+ - count: Total number of objects matching the query
44
+ - next: URL to next page (or null if no more pages)
45
+ - previous: URL to previous page (or null if on first page)
46
+ - results: Array of objects for this page
47
+ """
48
+ pass
49
+
50
+ @abc.abstractmethod
51
+ def create(self, endpoint: str, data: dict[str, Any]) -> dict[str, Any]:
52
+ """
53
+ Create a new object in NetBox.
54
+
55
+ Args:
56
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
57
+ data: Object data to create
58
+
59
+ Returns:
60
+ The created object as a dict
61
+ """
62
+ pass
63
+
64
+ @abc.abstractmethod
65
+ def update(self, endpoint: str, id: int, data: dict[str, Any]) -> dict[str, Any]:
66
+ """
67
+ Update an existing object in NetBox.
68
+
69
+ Args:
70
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
71
+ id: ID of the object to update
72
+ data: Object data to update
73
+
74
+ Returns:
75
+ The updated object as a dict
76
+ """
77
+ pass
78
+
79
+ @abc.abstractmethod
80
+ def delete(self, endpoint: str, id: int) -> bool:
81
+ """
82
+ Delete an object from NetBox.
83
+
84
+ Args:
85
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
86
+ id: ID of the object to delete
87
+
88
+ Returns:
89
+ True if deletion was successful, False otherwise
90
+ """
91
+ pass
92
+
93
+ @abc.abstractmethod
94
+ def bulk_create(self, endpoint: str, data: list[dict[str, Any]]) -> list[dict[str, Any]]:
95
+ """
96
+ Create multiple objects in NetBox.
97
+
98
+ Args:
99
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
100
+ data: List of object data to create
101
+
102
+ Returns:
103
+ List of created objects as dicts
104
+ """
105
+ pass
106
+
107
+ @abc.abstractmethod
108
+ def bulk_update(self, endpoint: str, data: list[dict[str, Any]]) -> list[dict[str, Any]]:
109
+ """
110
+ Update multiple objects in NetBox.
111
+
112
+ Args:
113
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
114
+ data: List of object data to update (must include ID)
115
+
116
+ Returns:
117
+ List of updated objects as dicts
118
+ """
119
+ pass
120
+
121
+ @abc.abstractmethod
122
+ def bulk_delete(self, endpoint: str, ids: list[int]) -> bool:
123
+ """
124
+ Delete multiple objects from NetBox.
125
+
126
+ Args:
127
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
128
+ ids: List of IDs to delete
129
+
130
+ Returns:
131
+ True if deletion was successful, False otherwise
132
+ """
133
+ pass
134
+
135
+
136
+ class NetBoxRestClient(NetBoxClientBase):
137
+ """
138
+ NetBox client implementation using the REST API.
139
+ """
140
+
141
+ # # Example of how to use the client
142
+ # client = NetBoxRestClient(
143
+ # url="https://netbox.example.com",
144
+ # token="your_api_token_here",
145
+ # verify_ssl=True
146
+ # )
147
+
148
+ # # Get all sites
149
+ # sites = client.get("dcim/sites")
150
+ # print(f"Found {len(sites)} sites")
151
+
152
+ # # Get a specific site
153
+ # site = client.get("dcim/sites", id=1)
154
+ # print(f"Site name: {site.get('name')}")
155
+
156
+ # # Create a new site
157
+ # new_site = client.create("dcim/sites", {
158
+ # "name": "New Site",
159
+ # "slug": "new-site",
160
+ # "status": "active"
161
+ # })
162
+ # print(f"Created site: {new_site.get('name')} (ID: {new_site.get('id')})")
163
+
164
+ def __init__(
165
+ self,
166
+ url: str,
167
+ token: str | None,
168
+ verify_ssl: bool = True,
169
+ session: httpx.Client | None = None,
170
+ ):
171
+ """
172
+ Initialize the REST API client.
173
+
174
+ Args:
175
+ url: The base URL of the NetBox instance (e.g., 'https://netbox.example.com')
176
+ token: API token for authentication, or None to send no credentials
177
+ verify_ssl: Whether to verify SSL certificates
178
+ session: Optional HTTP session to share with other clients (see with_token)
179
+ """
180
+ self.base_url = url.rstrip("/")
181
+ self.api_url = f"{self.base_url}/api"
182
+ self.token = token
183
+ self.verify_ssl = verify_ssl
184
+ self.session = session or httpx.Client(verify=self.verify_ssl)
185
+ self.session.headers.update(
186
+ {
187
+ "Content-Type": "application/json",
188
+ "Accept": "application/json",
189
+ }
190
+ )
191
+ # Sent per request instead of on the session, so clients sharing a
192
+ # session can each use their own token.
193
+ self.request_headers: dict[str, str] = {}
194
+ if token:
195
+ auth_scheme = "Bearer" if token.startswith("nbt_") else "Token"
196
+ self.request_headers["Authorization"] = f"{auth_scheme} {token}"
197
+
198
+ def with_token(self, token: str) -> "NetBoxRestClient":
199
+ """
200
+ Return a client that uses another token but shares this client's connections.
201
+
202
+ Args:
203
+ token: API token for the new client
204
+
205
+ Returns:
206
+ A NetBoxRestClient authenticated with the given token
207
+ """
208
+ return NetBoxRestClient(self.base_url, token, self.verify_ssl, session=self.session)
209
+
210
+ def _request(self, method: str, url: str, **kwargs: Any) -> httpx.Response:
211
+ """Send a request with this client's per-request headers."""
212
+ return self.session.request(method, url, headers=self.request_headers, **kwargs)
213
+
214
+ def _build_url(self, endpoint: str, id: int | None = None) -> str:
215
+ """Build the full URL for an API request."""
216
+ endpoint = endpoint.strip("/")
217
+ if id is not None:
218
+ return f"{self.api_url}/{endpoint}/{id}/"
219
+ return f"{self.api_url}/{endpoint}/"
220
+
221
+ def get(
222
+ self,
223
+ endpoint: str,
224
+ id: int | None = None,
225
+ params: dict[str, Any] | None = None,
226
+ fallback_endpoint: str | None = None,
227
+ ) -> dict[str, Any] | list[dict[str, Any]]:
228
+ """
229
+ Retrieve one or more objects from NetBox via the REST API.
230
+
231
+ Args:
232
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
233
+ id: Optional ID to retrieve a specific object
234
+ params: Optional query parameters for filtering
235
+ fallback_endpoint: Optional alternative endpoint to try if primary returns 404
236
+ (used for NetBox version compatibility)
237
+
238
+ Returns:
239
+ For single object queries (with id): Returns the object dict
240
+ For list queries (without id): Returns the full paginated response dict with:
241
+ - count: Total number of objects matching the query
242
+ - next: URL to next page (or null)
243
+ - previous: URL to previous page (or null)
244
+ - results: Array of objects for this page
245
+
246
+ Raises:
247
+ httpx.HTTPStatusError: If the request fails
248
+ """
249
+ url = self._build_url(endpoint, id)
250
+ response = self._request("GET", url, params=params)
251
+
252
+ # Try fallback endpoint if primary returns 404
253
+ if response.status_code == 404 and fallback_endpoint:
254
+ fallback_url = self._build_url(fallback_endpoint, id)
255
+ response = self._request("GET", fallback_url, params=params)
256
+
257
+ response.raise_for_status()
258
+
259
+ return response.json()
260
+
261
+ def create(self, endpoint: str, data: dict[str, Any]) -> dict[str, Any]:
262
+ """
263
+ Create a new object in NetBox via the REST API.
264
+
265
+ Args:
266
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
267
+ data: Object data to create
268
+
269
+ Returns:
270
+ The created object as a dict
271
+
272
+ Raises:
273
+ httpx.HTTPStatusError: If the request fails
274
+ """
275
+ url = self._build_url(endpoint)
276
+ response = self._request("POST", url, json=data)
277
+ response.raise_for_status()
278
+ return response.json()
279
+
280
+ def update(self, endpoint: str, id: int, data: dict[str, Any]) -> dict[str, Any]:
281
+ """
282
+ Update an existing object in NetBox via the REST API.
283
+
284
+ Args:
285
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
286
+ id: ID of the object to update
287
+ data: Object data to update
288
+
289
+ Returns:
290
+ The updated object as a dict
291
+
292
+ Raises:
293
+ httpx.HTTPStatusError: If the request fails
294
+ """
295
+ url = self._build_url(endpoint, id)
296
+ response = self._request("PATCH", url, json=data)
297
+ response.raise_for_status()
298
+ return response.json()
299
+
300
+ def delete(self, endpoint: str, id: int) -> bool:
301
+ """
302
+ Delete an object from NetBox via the REST API.
303
+
304
+ Args:
305
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
306
+ id: ID of the object to delete
307
+
308
+ Returns:
309
+ True if deletion was successful, False otherwise
310
+
311
+ Raises:
312
+ httpx.HTTPStatusError: If the request fails
313
+ """
314
+ url = self._build_url(endpoint, id)
315
+ response = self._request("DELETE", url)
316
+ response.raise_for_status()
317
+ return response.status_code == 204
318
+
319
+ def bulk_create(self, endpoint: str, data: list[dict[str, Any]]) -> list[dict[str, Any]]:
320
+ """
321
+ Create multiple objects in NetBox via the REST API.
322
+
323
+ Args:
324
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
325
+ data: List of object data to create
326
+
327
+ Returns:
328
+ List of created objects as dicts
329
+
330
+ Raises:
331
+ httpx.HTTPStatusError: If the request fails
332
+ """
333
+ url = self._build_url(endpoint)
334
+ response = self._request("POST", url, json=data)
335
+ response.raise_for_status()
336
+ return response.json()
337
+
338
+ def bulk_update(self, endpoint: str, data: list[dict[str, Any]]) -> list[dict[str, Any]]:
339
+ """
340
+ Update multiple objects in NetBox via the REST API.
341
+
342
+ Args:
343
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
344
+ data: List of object data to update (must include ID)
345
+
346
+ Returns:
347
+ List of updated objects as dicts
348
+
349
+ Raises:
350
+ httpx.HTTPStatusError: If the request fails
351
+ """
352
+ url = self._build_url(endpoint)
353
+ response = self._request("PATCH", url, json=data)
354
+ response.raise_for_status()
355
+ return response.json()
356
+
357
+ def bulk_delete(self, endpoint: str, ids: list[int]) -> bool:
358
+ """
359
+ Delete multiple objects from NetBox via the REST API.
360
+
361
+ Args:
362
+ endpoint: The API endpoint (e.g., 'dcim/sites', 'ipam/prefixes')
363
+ ids: List of IDs to delete
364
+
365
+ Returns:
366
+ True if deletion was successful, False otherwise
367
+
368
+ Raises:
369
+ httpx.HTTPStatusError: If the request fails
370
+ """
371
+ url = self._build_url(endpoint)
372
+ data = [{"id": id} for id in ids]
373
+ response = self._request("DELETE", url, json=data)
374
+ response.raise_for_status()
375
+ return response.status_code == 204