@tera-system/core 0.2.9 → 0.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/MANIFEST.json +9 -9
- package/RELEASES.md +43 -0
- package/agents/auditor.md +1 -1
- package/agents/domain-research-agent.md +25 -4
- package/agents/red-team-agent.md +334 -0
- package/agents/security-auditor.md +281 -0
- package/agents/security-observer.md +241 -0
- package/assets/architecture/README.md +30 -0
- package/assets/structurizr-mcp/README.md +134 -0
- package/assets/structurizr-mcp/pyproject.toml +19 -0
- package/assets/structurizr-mcp/src/structurizr_mcp/__init__.py +0 -0
- package/assets/structurizr-mcp/src/structurizr_mcp/config.py +59 -0
- package/assets/structurizr-mcp/src/structurizr_mcp/server.py +101 -0
- package/assets/structurizr-mcp/src/structurizr_mcp/tools/__init__.py +0 -0
- package/assets/structurizr-mcp/src/structurizr_mcp/tools/api.py +63 -0
- package/assets/structurizr-mcp/src/structurizr_mcp/tools/dsl.py +36 -0
- package/assets/structurizr-mcp/src/structurizr_mcp/tools/export.py +258 -0
- package/assets/structurizr-mcp/src/structurizr_mcp/tools/validate.py +43 -0
- package/assets/structurizr-mcp/uv.lock +770 -0
- package/core/tera-system/AGENT_ACTIVATION_MATRIX.md +4 -1
- package/core/tera-system/AGENT_DEPENDENCY_MAP.md +6 -0
- package/core/tera-system/AGENT_PERMISSION_MODEL.md +17 -4
- package/core/tera-system/TERA_DISTRIBUTION_POLICY.md +26 -5
- package/core/tera-system/TOOLING_AND_MCP_POLICY.md +66 -1
- package/core/tera-system/TeraArchitectureMap.md +4 -1
- package/core/tera-system/TeraClientPolicy.md +1 -1
- package/core/tera-system/TeraHelperAgents.md +17 -1
- package/core/tera-system/TeraPolicyMap.md +8 -3
- package/core/tera-system/TeraPricingPolicy.md +16 -0
- package/core/tera-system/TeraSubAgents.md +27 -7
- package/core/tera-system/TeraSystemMaintenanceChecklist.md +8 -0
- package/core/tera-system/client-helpers/tera-client-engagement-pricing.md +1 -1
- package/core/tera-system/runtime/DOMAIN_INTELLIGENCE_PROTOCOL.md +42 -0
- package/core/tera-system/runtime/TERA_RUNTIME_CHECKLISTS.md +10 -0
- package/opencode.tera.example.json +3 -3
- package/package.json +1 -1
- package/tools/tera-tooling.ps1 +221 -0
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "structurizr-mcp"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "MCP server for Structurizr Lite — read/write DSL, validate, export diagrams"
|
|
9
|
+
requires-python = ">=3.11"
|
|
10
|
+
dependencies = [
|
|
11
|
+
"mcp[cli]>=1.0.0",
|
|
12
|
+
"httpx>=0.27.0",
|
|
13
|
+
]
|
|
14
|
+
|
|
15
|
+
[project.scripts]
|
|
16
|
+
structurizr-mcp = "structurizr_mcp.server:main"
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["src/structurizr_mcp"]
|
|
File without changes
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import hashlib
|
|
2
|
+
import hmac
|
|
3
|
+
import base64
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
@dataclass
|
|
10
|
+
class Config:
|
|
11
|
+
structurizr_url: str = field(default_factory=lambda: os.environ.get("STRUCTURIZR_URL", "http://localhost:8080"))
|
|
12
|
+
api_key: str | None = field(default_factory=lambda: os.environ.get("STRUCTURIZR_API_KEY"))
|
|
13
|
+
api_secret: str | None = field(default_factory=lambda: os.environ.get("STRUCTURIZR_API_SECRET"))
|
|
14
|
+
workspace_id: str = field(default_factory=lambda: os.environ.get("STRUCTURIZR_WORKSPACE_ID", "1"))
|
|
15
|
+
# Base directory that bounds all file access (the sandbox root). When several workspaces
|
|
16
|
+
# live side by side, point this at their common parent and select one per call via the
|
|
17
|
+
# `workspace` tool argument (or the STRUCTURIZR_DEFAULT_WORKSPACE fallback below).
|
|
18
|
+
workspace_dir: str = field(default_factory=lambda: os.environ.get("STRUCTURIZR_WORKSPACE_DIR", "."))
|
|
19
|
+
# Optional sub-directory under workspace_dir used when a tool call omits `workspace`.
|
|
20
|
+
default_workspace: str | None = field(default_factory=lambda: os.environ.get("STRUCTURIZR_DEFAULT_WORKSPACE") or None)
|
|
21
|
+
|
|
22
|
+
def effective_workspace_dir(self, workspace: str | None = None) -> "Path":
|
|
23
|
+
"""
|
|
24
|
+
Resolve the working directory for a call: workspace_dir / (workspace or default_workspace).
|
|
25
|
+
|
|
26
|
+
Returns workspace_dir itself when neither is set. Raises if the result escapes
|
|
27
|
+
workspace_dir, so a caller can never reach outside the configured base.
|
|
28
|
+
"""
|
|
29
|
+
from pathlib import Path
|
|
30
|
+
base = Path(self.workspace_dir).resolve()
|
|
31
|
+
ws = workspace if workspace is not None else self.default_workspace
|
|
32
|
+
if ws:
|
|
33
|
+
resolved = (base / ws).resolve()
|
|
34
|
+
if not str(resolved).startswith(str(base)):
|
|
35
|
+
raise ValueError(f"Workspace '{ws}' escapes the base directory {base}")
|
|
36
|
+
return resolved
|
|
37
|
+
return base
|
|
38
|
+
|
|
39
|
+
def hmac_headers(self, method: str, path: str, body: bytes = b"") -> dict[str, str]:
|
|
40
|
+
"""
|
|
41
|
+
Build X-Authorization / Nonce headers for the Structurizr vNext REST API.
|
|
42
|
+
Returns an empty dict if no API key is configured (local mode with no auth).
|
|
43
|
+
"""
|
|
44
|
+
if not self.api_key or not self.api_secret:
|
|
45
|
+
return {}
|
|
46
|
+
content_type = "application/json"
|
|
47
|
+
nonce = str(int(time.time() * 1000))
|
|
48
|
+
md5 = hashlib.md5(body).hexdigest()
|
|
49
|
+
message = f"{method}\n{content_type}\n{md5}\n{nonce}\n{path}\n"
|
|
50
|
+
signature = base64.b64encode(
|
|
51
|
+
hmac.new(self.api_secret.encode(), message.encode(), hashlib.sha256).digest()
|
|
52
|
+
).decode()
|
|
53
|
+
return {
|
|
54
|
+
"X-Authorization": f"{self.api_key}:{signature}",
|
|
55
|
+
"Nonce": nonce,
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
config = Config()
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from mcp.server.fastmcp import FastMCP
|
|
2
|
+
from structurizr_mcp.tools.dsl import read_dsl_file, write_dsl_file, list_dsl_files
|
|
3
|
+
from structurizr_mcp.tools.validate import validate_workspace
|
|
4
|
+
from structurizr_mcp.tools.export import export_diagrams, SUPPORTED_FORMATS
|
|
5
|
+
from structurizr_mcp.tools.api import get_workspace_json, get_structurizr_status
|
|
6
|
+
|
|
7
|
+
mcp = FastMCP("structurizr")
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
@mcp.tool()
|
|
11
|
+
def read_dsl(path: str, workspace: str | None = None) -> str:
|
|
12
|
+
"""
|
|
13
|
+
Read a Structurizr DSL file. Path is relative to the selected workspace.
|
|
14
|
+
`workspace` selects a sub-directory under STRUCTURIZR_WORKSPACE_DIR (defaults to
|
|
15
|
+
STRUCTURIZR_DEFAULT_WORKSPACE, then to the base directory).
|
|
16
|
+
"""
|
|
17
|
+
return read_dsl_file(path, workspace)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@mcp.tool()
|
|
21
|
+
def write_dsl(path: str, content: str, workspace: str | None = None) -> str:
|
|
22
|
+
"""
|
|
23
|
+
Write or overwrite a Structurizr DSL file. Path is relative to the selected workspace.
|
|
24
|
+
Creates parent directories as needed. Structurizr will pick up the change automatically
|
|
25
|
+
if it is currently running. `workspace` selects a sub-directory under
|
|
26
|
+
STRUCTURIZR_WORKSPACE_DIR (defaults to STRUCTURIZR_DEFAULT_WORKSPACE, then to the base).
|
|
27
|
+
"""
|
|
28
|
+
return write_dsl_file(path, content, workspace)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@mcp.tool()
|
|
32
|
+
def list_dsl(directory: str = ".", workspace: str | None = None) -> list[str]:
|
|
33
|
+
"""
|
|
34
|
+
List all .dsl files under a directory. Path is relative to the selected workspace.
|
|
35
|
+
Returns paths relative to that workspace. `workspace` selects a sub-directory under
|
|
36
|
+
STRUCTURIZR_WORKSPACE_DIR (defaults to STRUCTURIZR_DEFAULT_WORKSPACE, then to the base).
|
|
37
|
+
"""
|
|
38
|
+
return list_dsl_files(directory, workspace)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@mcp.tool()
|
|
42
|
+
def validate(path: str, workspace: str | None = None) -> dict:
|
|
43
|
+
"""
|
|
44
|
+
Validate a Structurizr DSL file via Docker (structurizr/structurizr validate).
|
|
45
|
+
Returns {valid: bool, errors: [str], output: str}.
|
|
46
|
+
`workspace` selects a sub-directory under STRUCTURIZR_WORKSPACE_DIR (defaults to
|
|
47
|
+
STRUCTURIZR_DEFAULT_WORKSPACE, then to the base directory).
|
|
48
|
+
Requires Docker to be running.
|
|
49
|
+
"""
|
|
50
|
+
return validate_workspace(path, workspace)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@mcp.tool()
|
|
54
|
+
def export(path: str, format: str = "mermaid", output_dir: str | None = None, workspace: str | None = None) -> dict:
|
|
55
|
+
"""
|
|
56
|
+
Export diagrams from a DSL file via Docker.
|
|
57
|
+
|
|
58
|
+
Args:
|
|
59
|
+
path: Path to the .dsl file (relative to the selected workspace).
|
|
60
|
+
format: Output format. One of: mermaid (default), plantuml, svg, png,
|
|
61
|
+
json, static, websequencediagrams.
|
|
62
|
+
SVG and PNG capture diagrams exactly as they appear in the Structurizr
|
|
63
|
+
web UI using a Playwright headless browser — requires Structurizr to be
|
|
64
|
+
running at STRUCTURIZR_URL and the playwright Docker image to be available.
|
|
65
|
+
All other formats work without a running server.
|
|
66
|
+
output_dir: Where to write exported files (relative to the selected workspace).
|
|
67
|
+
Defaults to the same directory as the DSL file.
|
|
68
|
+
workspace: Sub-directory under STRUCTURIZR_WORKSPACE_DIR to target. Defaults to
|
|
69
|
+
STRUCTURIZR_DEFAULT_WORKSPACE, then to the base directory.
|
|
70
|
+
|
|
71
|
+
Returns {files: [str], output: str}.
|
|
72
|
+
Requires Docker to be running.
|
|
73
|
+
"""
|
|
74
|
+
return export_diagrams(path, format, output_dir, workspace)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
@mcp.tool()
|
|
78
|
+
def workspace_json() -> dict:
|
|
79
|
+
"""
|
|
80
|
+
Fetch the current workspace model from Structurizr's REST API (GET /api/workspace).
|
|
81
|
+
Returns the full architecture model as JSON: all elements, relationships, and views.
|
|
82
|
+
Requires Structurizr to be running (STRUCTURIZR_URL, default http://localhost:8080).
|
|
83
|
+
"""
|
|
84
|
+
return get_workspace_json()
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
@mcp.tool()
|
|
88
|
+
def structurizr_status() -> dict:
|
|
89
|
+
"""
|
|
90
|
+
Check whether Structurizr is reachable at the configured URL.
|
|
91
|
+
Returns {reachable: bool, url: str, message: str}.
|
|
92
|
+
"""
|
|
93
|
+
return get_structurizr_status()
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def main():
|
|
97
|
+
mcp.run()
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
if __name__ == "__main__":
|
|
101
|
+
main()
|
|
File without changes
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import httpx
|
|
2
|
+
from structurizr_mcp.config import config
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _workspace_url() -> str:
|
|
6
|
+
return f"{config.structurizr_url.rstrip('/')}/api/workspace/{config.workspace_id}"
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def get_workspace_json() -> dict:
|
|
10
|
+
"""
|
|
11
|
+
Fetch the current workspace model from the Structurizr REST API.
|
|
12
|
+
|
|
13
|
+
Returns the full workspace as a parsed JSON dict, including all elements,
|
|
14
|
+
relationships, and views.
|
|
15
|
+
|
|
16
|
+
Works with structurizr/structurizr (local mode) — the successor to Structurizr Lite.
|
|
17
|
+
"""
|
|
18
|
+
path = f"/api/workspace/{config.workspace_id}"
|
|
19
|
+
headers = config.hmac_headers("GET", path)
|
|
20
|
+
try:
|
|
21
|
+
response = httpx.get(_workspace_url(), headers=headers, timeout=10.0)
|
|
22
|
+
response.raise_for_status()
|
|
23
|
+
return response.json()
|
|
24
|
+
except httpx.ConnectError:
|
|
25
|
+
raise RuntimeError(
|
|
26
|
+
f"Cannot connect to Structurizr at {config.structurizr_url}. "
|
|
27
|
+
"Is the Docker container running? "
|
|
28
|
+
"Start it with: docker run -it --rm -p 8080:8080 "
|
|
29
|
+
"-v $PWD/architecture:/usr/local/structurizr structurizr/structurizr local"
|
|
30
|
+
)
|
|
31
|
+
except httpx.HTTPStatusError as e:
|
|
32
|
+
raise RuntimeError(f"Structurizr API returned {e.response.status_code}: {e.response.text}")
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def get_structurizr_status() -> dict:
|
|
36
|
+
"""
|
|
37
|
+
Check whether Structurizr is reachable at the configured URL.
|
|
38
|
+
|
|
39
|
+
Returns a dict with 'reachable' (bool), 'url' (str), and 'message' (str).
|
|
40
|
+
"""
|
|
41
|
+
base_url = config.structurizr_url.rstrip("/")
|
|
42
|
+
path = f"/api/workspace/{config.workspace_id}"
|
|
43
|
+
headers = config.hmac_headers("GET", path)
|
|
44
|
+
try:
|
|
45
|
+
response = httpx.get(f"{base_url}{path}", headers=headers, timeout=5.0)
|
|
46
|
+
reachable = response.status_code < 500
|
|
47
|
+
return {
|
|
48
|
+
"reachable": reachable,
|
|
49
|
+
"url": base_url,
|
|
50
|
+
"message": f"HTTP {response.status_code}",
|
|
51
|
+
}
|
|
52
|
+
except httpx.ConnectError:
|
|
53
|
+
return {
|
|
54
|
+
"reachable": False,
|
|
55
|
+
"url": base_url,
|
|
56
|
+
"message": "Connection refused — is the Docker container running?",
|
|
57
|
+
}
|
|
58
|
+
except httpx.TimeoutException:
|
|
59
|
+
return {
|
|
60
|
+
"reachable": False,
|
|
61
|
+
"url": base_url,
|
|
62
|
+
"message": "Connection timed out",
|
|
63
|
+
}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from pathlib import Path
|
|
2
|
+
from structurizr_mcp.config import config
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
def _resolve(path: str, workspace: str | None = None) -> Path:
|
|
6
|
+
"""Resolve path relative to the (optionally workspace-scoped) base; reject traversal attempts."""
|
|
7
|
+
base = config.effective_workspace_dir(workspace)
|
|
8
|
+
resolved = (base / path).resolve()
|
|
9
|
+
if not str(resolved).startswith(str(base)):
|
|
10
|
+
raise ValueError(f"Path '{path}' escapes the workspace directory")
|
|
11
|
+
return resolved
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def read_dsl_file(path: str, workspace: str | None = None) -> str:
|
|
15
|
+
"""Read a Structurizr DSL file and return its contents."""
|
|
16
|
+
resolved = _resolve(path, workspace)
|
|
17
|
+
if not resolved.exists():
|
|
18
|
+
raise FileNotFoundError(f"File not found: {resolved}")
|
|
19
|
+
return resolved.read_text(encoding="utf-8")
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def write_dsl_file(path: str, content: str, workspace: str | None = None) -> str:
|
|
23
|
+
"""Write content to a DSL file, creating parent directories as needed."""
|
|
24
|
+
resolved = _resolve(path, workspace)
|
|
25
|
+
resolved.parent.mkdir(parents=True, exist_ok=True)
|
|
26
|
+
resolved.write_text(content, encoding="utf-8")
|
|
27
|
+
return f"Written to {resolved}"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def list_dsl_files(directory: str = ".", workspace: str | None = None) -> list[str]:
|
|
31
|
+
"""List all .dsl files under a directory (relative to the workspace)."""
|
|
32
|
+
resolved = _resolve(directory, workspace)
|
|
33
|
+
if not resolved.is_dir():
|
|
34
|
+
raise NotADirectoryError(f"Not a directory: {resolved}")
|
|
35
|
+
base = config.effective_workspace_dir(workspace)
|
|
36
|
+
return [str(p.relative_to(base)) for p in sorted(resolved.rglob("*.dsl"))]
|
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
import json
|
|
2
|
+
import subprocess
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
from structurizr_mcp.config import config
|
|
5
|
+
from structurizr_mcp.tools.dsl import _resolve
|
|
6
|
+
|
|
7
|
+
DOCKER_IMAGE = "structurizr/structurizr"
|
|
8
|
+
PLAYWRIGHT_IMAGE = "mcr.microsoft.com/playwright:v1.44.0-jammy"
|
|
9
|
+
CONTAINER_WORKSPACE = "/usr/local/structurizr"
|
|
10
|
+
|
|
11
|
+
# Formats exported purely from the DSL — no running Structurizr server needed.
|
|
12
|
+
CLI_ONLY_FORMATS = ("mermaid", "plantuml", "json", "static", "websequencediagrams")
|
|
13
|
+
# Formats rendered by the Structurizr web UI via a headless browser — require a running server.
|
|
14
|
+
SERVER_FORMATS = ("svg", "png")
|
|
15
|
+
|
|
16
|
+
SUPPORTED_FORMATS = CLI_ONLY_FORMATS + SERVER_FORMATS
|
|
17
|
+
|
|
18
|
+
_EXTENSION_MAP = {
|
|
19
|
+
"mermaid": ".md",
|
|
20
|
+
"plantuml": ".puml",
|
|
21
|
+
"svg": ".svg",
|
|
22
|
+
"png": ".png",
|
|
23
|
+
"json": ".json",
|
|
24
|
+
"static": ".html",
|
|
25
|
+
"websequencediagrams": ".txt",
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _container_path(local: Path, workspace_dir: Path) -> str:
|
|
30
|
+
"""Translate a local absolute path to its equivalent inside the Docker container."""
|
|
31
|
+
return f"{CONTAINER_WORKSPACE}/{local.relative_to(workspace_dir)}"
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _docker_url(url: str) -> str:
|
|
35
|
+
"""Replace localhost/127.0.0.1 with host.docker.internal so containers can reach the host."""
|
|
36
|
+
return url.replace("localhost", "host.docker.internal").replace("127.0.0.1", "host.docker.internal")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _get_view_keys() -> list[str]:
|
|
40
|
+
"""Fetch all view keys from the running Structurizr workspace."""
|
|
41
|
+
from structurizr_mcp.tools.api import get_workspace_json
|
|
42
|
+
workspace = get_workspace_json()
|
|
43
|
+
views_section = workspace.get("views", {})
|
|
44
|
+
keys = []
|
|
45
|
+
for view_type in (
|
|
46
|
+
"systemLandscapeViews",
|
|
47
|
+
"systemContextViews",
|
|
48
|
+
"containerViews",
|
|
49
|
+
"componentViews",
|
|
50
|
+
"dynamicViews",
|
|
51
|
+
"deploymentViews",
|
|
52
|
+
"filteredViews",
|
|
53
|
+
"customViews",
|
|
54
|
+
):
|
|
55
|
+
for view in views_section.get(view_type, []):
|
|
56
|
+
key = view.get("key")
|
|
57
|
+
if key:
|
|
58
|
+
keys.append(key)
|
|
59
|
+
return keys
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _export_svg_via_browser(
|
|
63
|
+
view_keys: list[str],
|
|
64
|
+
out_resolved: Path,
|
|
65
|
+
workspace_dir: Path,
|
|
66
|
+
structurizr_url: str,
|
|
67
|
+
fmt: str = "svg",
|
|
68
|
+
) -> dict:
|
|
69
|
+
"""
|
|
70
|
+
Export diagrams as SVG using a Playwright headless browser pointed at the
|
|
71
|
+
running Structurizr server. Captures diagrams exactly as they appear in the
|
|
72
|
+
Structurizr web UI.
|
|
73
|
+
"""
|
|
74
|
+
# Parse port from structurizr_url (default 8080)
|
|
75
|
+
import urllib.parse as _urlparse
|
|
76
|
+
parsed = _urlparse.urlparse(structurizr_url)
|
|
77
|
+
remote_host = parsed.hostname or "localhost"
|
|
78
|
+
remote_port = parsed.port or 8080
|
|
79
|
+
# Convert localhost → host.docker.internal for the proxy target (container → host)
|
|
80
|
+
docker_host = remote_host.replace("localhost", "host.docker.internal").replace("127.0.0.1", "host.docker.internal")
|
|
81
|
+
|
|
82
|
+
container_out = _container_path(out_resolved, workspace_dir)
|
|
83
|
+
ext = ".svg" if fmt == "svg" else ".png"
|
|
84
|
+
|
|
85
|
+
tmp_dir = workspace_dir / ".playwright-tmp"
|
|
86
|
+
tmp_dir.mkdir(exist_ok=True)
|
|
87
|
+
script_path = tmp_dir / "export-diagrams.js"
|
|
88
|
+
|
|
89
|
+
script = f"""
|
|
90
|
+
const {{ chromium }} = require('playwright');
|
|
91
|
+
const net = require('net');
|
|
92
|
+
const fs = require('fs');
|
|
93
|
+
const path = require('path');
|
|
94
|
+
|
|
95
|
+
const views = {json.dumps(view_keys)};
|
|
96
|
+
const outputDir = '{container_out}';
|
|
97
|
+
// Structurizr validates the Host header and rejects 'host.docker.internal'.
|
|
98
|
+
// We create a TCP proxy inside the container: localhost:{remote_port} → {docker_host}:{remote_port}
|
|
99
|
+
// Playwright connects to localhost, so the Host header is 'localhost:{remote_port}' which Structurizr accepts.
|
|
100
|
+
const PROXY_PORT = {remote_port};
|
|
101
|
+
const REMOTE_HOST = '{docker_host}';
|
|
102
|
+
const REMOTE_PORT = {remote_port};
|
|
103
|
+
const baseUrl = 'http://localhost:' + PROXY_PORT;
|
|
104
|
+
|
|
105
|
+
const proxyServer = net.createServer(socket => {{
|
|
106
|
+
const remote = net.connect(REMOTE_PORT, REMOTE_HOST);
|
|
107
|
+
socket.pipe(remote);
|
|
108
|
+
remote.pipe(socket);
|
|
109
|
+
socket.on('error', () => remote.destroy());
|
|
110
|
+
remote.on('error', () => socket.destroy());
|
|
111
|
+
}});
|
|
112
|
+
|
|
113
|
+
(async () => {{
|
|
114
|
+
await new Promise(resolve => proxyServer.listen(PROXY_PORT, '127.0.0.1', resolve));
|
|
115
|
+
console.log('Proxy listening on localhost:' + PROXY_PORT + ' → ' + REMOTE_HOST + ':' + REMOTE_PORT);
|
|
116
|
+
|
|
117
|
+
const browser = await chromium.launch();
|
|
118
|
+
const page = await browser.newPage();
|
|
119
|
+
const errors = [];
|
|
120
|
+
|
|
121
|
+
for (const viewKey of views) {{
|
|
122
|
+
try {{
|
|
123
|
+
const url = baseUrl + '/workspace/1/diagrams#' + encodeURIComponent(viewKey);
|
|
124
|
+
console.log('Exporting: ' + viewKey);
|
|
125
|
+
await page.goto(url, {{ waitUntil: 'networkidle', timeout: 30000 }});
|
|
126
|
+
|
|
127
|
+
// Wait until Structurizr has loaded and the export function is available
|
|
128
|
+
await page.waitForFunction(
|
|
129
|
+
() => typeof structurizr !== 'undefined' &&
|
|
130
|
+
structurizr.diagram &&
|
|
131
|
+
typeof structurizr.diagram.exportCurrentDiagramToSVG === 'function',
|
|
132
|
+
{{ timeout: 30000 }}
|
|
133
|
+
);
|
|
134
|
+
// Extra settle time for layout engine to finish
|
|
135
|
+
await page.waitForTimeout(1500);
|
|
136
|
+
|
|
137
|
+
const svgMarkup = await page.evaluate(
|
|
138
|
+
() => structurizr.diagram.exportCurrentDiagramToSVG({{}}).markup
|
|
139
|
+
);
|
|
140
|
+
|
|
141
|
+
const outFile = path.join(outputDir, 'structurizr-' + viewKey + '{ext}');
|
|
142
|
+
fs.writeFileSync(outFile, svgMarkup);
|
|
143
|
+
console.log('Written: ' + outFile);
|
|
144
|
+
}} catch (err) {{
|
|
145
|
+
errors.push(viewKey + ': ' + err.message);
|
|
146
|
+
console.error('Failed ' + viewKey + ': ' + err.message);
|
|
147
|
+
}}
|
|
148
|
+
}}
|
|
149
|
+
|
|
150
|
+
await browser.close();
|
|
151
|
+
proxyServer.close();
|
|
152
|
+
if (errors.length > 0) {{
|
|
153
|
+
process.stderr.write('Errors: ' + errors.join(', ') + '\\n');
|
|
154
|
+
process.exit(1);
|
|
155
|
+
}}
|
|
156
|
+
}})();
|
|
157
|
+
"""
|
|
158
|
+
|
|
159
|
+
# package.json lets npm install playwright and caches node_modules in the workspace
|
|
160
|
+
# dir (which is a Docker volume), so only the first run is slow.
|
|
161
|
+
pkg_json = tmp_dir / "package.json"
|
|
162
|
+
pkg_json.write_text(json.dumps({
|
|
163
|
+
"name": "playwright-export",
|
|
164
|
+
"version": "1.0.0",
|
|
165
|
+
"dependencies": {"playwright": "1.44.0"},
|
|
166
|
+
}))
|
|
167
|
+
script_path.write_text(script)
|
|
168
|
+
|
|
169
|
+
container_tmp = _container_path(tmp_dir, workspace_dir)
|
|
170
|
+
container_script = _container_path(script_path, workspace_dir)
|
|
171
|
+
|
|
172
|
+
try:
|
|
173
|
+
result = subprocess.run(
|
|
174
|
+
[
|
|
175
|
+
"docker", "run", "--rm",
|
|
176
|
+
"--add-host=host.docker.internal:host-gateway",
|
|
177
|
+
"-v", f"{workspace_dir}:{CONTAINER_WORKSPACE}",
|
|
178
|
+
"-e", "PLAYWRIGHT_BROWSERS_PATH=/ms-playwright",
|
|
179
|
+
PLAYWRIGHT_IMAGE,
|
|
180
|
+
"bash", "-c",
|
|
181
|
+
f"cd {container_tmp} && npm install --prefer-offline --silent 2>/dev/null && node {container_script}",
|
|
182
|
+
],
|
|
183
|
+
capture_output=True,
|
|
184
|
+
text=True,
|
|
185
|
+
)
|
|
186
|
+
output = (result.stdout + result.stderr).strip()
|
|
187
|
+
if result.returncode != 0:
|
|
188
|
+
raise RuntimeError(f"Playwright SVG export failed:\n{output}")
|
|
189
|
+
finally:
|
|
190
|
+
script_path.unlink(missing_ok=True)
|
|
191
|
+
pkg_json.unlink(missing_ok=True)
|
|
192
|
+
|
|
193
|
+
files = [str(p) for p in sorted(out_resolved.glob(f"*{ext}"))]
|
|
194
|
+
return {"files": files, "output": output}
|
|
195
|
+
|
|
196
|
+
|
|
197
|
+
def export_diagrams(path: str, format: str = "mermaid", output_dir: str | None = None, workspace: str | None = None) -> dict:
|
|
198
|
+
"""
|
|
199
|
+
Export diagrams from a Structurizr DSL file.
|
|
200
|
+
|
|
201
|
+
CLI formats (mermaid, plantuml, json, static, websequencediagrams) use
|
|
202
|
+
Docker (structurizr/structurizr export) and work without a running server.
|
|
203
|
+
|
|
204
|
+
SVG and PNG use a Playwright headless browser (mcr.microsoft.com/playwright)
|
|
205
|
+
that connects to the running Structurizr server and captures diagrams exactly
|
|
206
|
+
as they appear in the web UI. Both Docker images must be available.
|
|
207
|
+
|
|
208
|
+
Args:
|
|
209
|
+
path: Path to the .dsl file (relative to the selected workspace).
|
|
210
|
+
format: Output format — mermaid (default), plantuml, svg, png,
|
|
211
|
+
json, static, websequencediagrams.
|
|
212
|
+
output_dir: Where to write exported files (relative to the selected workspace).
|
|
213
|
+
Defaults to the same directory as the DSL file.
|
|
214
|
+
workspace: Sub-directory under STRUCTURIZR_WORKSPACE_DIR to target. Defaults to
|
|
215
|
+
STRUCTURIZR_DEFAULT_WORKSPACE, then to the base directory.
|
|
216
|
+
|
|
217
|
+
Returns a dict with 'files' (list of output paths) and 'output' (raw CLI output).
|
|
218
|
+
"""
|
|
219
|
+
fmt = format.lower()
|
|
220
|
+
if fmt not in SUPPORTED_FORMATS:
|
|
221
|
+
raise ValueError(f"Unsupported format '{format}'. Choose from: {', '.join(SUPPORTED_FORMATS)}")
|
|
222
|
+
|
|
223
|
+
workspace_dir = config.effective_workspace_dir(workspace)
|
|
224
|
+
resolved = _resolve(path, workspace)
|
|
225
|
+
if not resolved.exists():
|
|
226
|
+
raise FileNotFoundError(f"File not found: {resolved}")
|
|
227
|
+
|
|
228
|
+
if output_dir is None:
|
|
229
|
+
out_resolved = resolved.parent
|
|
230
|
+
else:
|
|
231
|
+
out_resolved = _resolve(output_dir, workspace)
|
|
232
|
+
out_resolved.mkdir(parents=True, exist_ok=True)
|
|
233
|
+
|
|
234
|
+
if fmt in SERVER_FORMATS:
|
|
235
|
+
view_keys = _get_view_keys()
|
|
236
|
+
return _export_svg_via_browser(view_keys, out_resolved, workspace_dir, config.structurizr_url, fmt)
|
|
237
|
+
|
|
238
|
+
# CLI-only formats: use structurizr/structurizr export
|
|
239
|
+
cmd = [
|
|
240
|
+
"docker", "run", "--rm",
|
|
241
|
+
"--add-host=host.docker.internal:host-gateway",
|
|
242
|
+
"-v", f"{workspace_dir}:{CONTAINER_WORKSPACE}",
|
|
243
|
+
DOCKER_IMAGE, "export",
|
|
244
|
+
"-w", _container_path(resolved, workspace_dir),
|
|
245
|
+
"-f", fmt,
|
|
246
|
+
"-o", _container_path(out_resolved, workspace_dir),
|
|
247
|
+
]
|
|
248
|
+
|
|
249
|
+
result = subprocess.run(cmd, capture_output=True, text=True)
|
|
250
|
+
output = (result.stdout + result.stderr).strip()
|
|
251
|
+
|
|
252
|
+
if result.returncode != 0:
|
|
253
|
+
raise RuntimeError(f"Structurizr export failed:\n{output}")
|
|
254
|
+
|
|
255
|
+
ext = _EXTENSION_MAP.get(fmt, f".{fmt}")
|
|
256
|
+
files = [str(p) for p in sorted(out_resolved.glob(f"*{ext}"))]
|
|
257
|
+
|
|
258
|
+
return {"files": files, "output": output}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import subprocess
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from structurizr_mcp.config import config
|
|
4
|
+
from structurizr_mcp.tools.dsl import _resolve
|
|
5
|
+
from structurizr_mcp.tools.export import DOCKER_IMAGE, CONTAINER_WORKSPACE, _container_path
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def validate_workspace(path: str, workspace: str | None = None) -> dict:
|
|
9
|
+
"""
|
|
10
|
+
Validate a Structurizr DSL file via Docker (structurizr/structurizr validate).
|
|
11
|
+
Returns a dict with 'valid' (bool), 'errors' (list of str), and 'output' (raw CLI output).
|
|
12
|
+
"""
|
|
13
|
+
workspace_dir = config.effective_workspace_dir(workspace)
|
|
14
|
+
resolved = _resolve(path, workspace)
|
|
15
|
+
if not resolved.exists():
|
|
16
|
+
raise FileNotFoundError(f"File not found: {resolved}")
|
|
17
|
+
|
|
18
|
+
result = subprocess.run(
|
|
19
|
+
[
|
|
20
|
+
"docker", "run", "--rm",
|
|
21
|
+
"-v", f"{workspace_dir}:{CONTAINER_WORKSPACE}",
|
|
22
|
+
DOCKER_IMAGE, "validate",
|
|
23
|
+
"-w", _container_path(resolved, workspace_dir),
|
|
24
|
+
],
|
|
25
|
+
capture_output=True,
|
|
26
|
+
text=True,
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
output = (result.stdout + result.stderr).strip()
|
|
30
|
+
valid = result.returncode == 0
|
|
31
|
+
errors = _parse_errors(result.stderr or result.stdout)
|
|
32
|
+
|
|
33
|
+
return {"valid": valid, "errors": errors, "output": output}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _parse_errors(text: str) -> list[str]:
|
|
37
|
+
"""Extract error lines from CLI output."""
|
|
38
|
+
errors = []
|
|
39
|
+
for line in text.splitlines():
|
|
40
|
+
stripped = line.strip()
|
|
41
|
+
if stripped and any(word in stripped.lower() for word in ("error", "warning", "invalid", "unexpected")):
|
|
42
|
+
errors.append(stripped)
|
|
43
|
+
return errors
|