mcpwarden-ui 1.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.
Files changed (53) hide show
  1. mcpwarden_ui-1.1.0/PKG-INFO +121 -0
  2. mcpwarden_ui-1.1.0/README.md +95 -0
  3. mcpwarden_ui-1.1.0/pyproject.toml +43 -0
  4. mcpwarden_ui-1.1.0/setup.cfg +17 -0
  5. mcpwarden_ui-1.1.0/src/mcpwarden_ui/__init__.py +3 -0
  6. mcpwarden_ui-1.1.0/src/mcpwarden_ui/__main__.py +320 -0
  7. mcpwarden_ui-1.1.0/src/mcpwarden_ui/api.py +1001 -0
  8. mcpwarden_ui-1.1.0/src/mcpwarden_ui/inbox.py +111 -0
  9. mcpwarden_ui-1.1.0/src/mcpwarden_ui/mcp_server.py +828 -0
  10. mcpwarden_ui-1.1.0/src/mcpwarden_ui/policyview.py +124 -0
  11. mcpwarden_ui-1.1.0/src/mcpwarden_ui/rbac.py +76 -0
  12. mcpwarden_ui-1.1.0/src/mcpwarden_ui/server.py +1282 -0
  13. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/barlow-condensed-latin-500-normal-BgYH2mbd.woff2 +0 -0
  14. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/barlow-condensed-latin-700-normal-v1xN8_Wq.woff2 +0 -0
  15. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/barlow-condensed-latin-ext-500-normal-yA5ONLQ9.woff2 +0 -0
  16. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/barlow-condensed-latin-ext-700-normal-CwuXbfVR.woff2 +0 -0
  17. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/charts-DQksOnlo.js +79 -0
  18. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/index-C2WSRE7M.js +278 -0
  19. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/index-vVXLzbsF.js +307 -0
  20. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/jost-latin-ext-wght-normal-BDUtSsKd.woff2 +0 -0
  21. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/jost-latin-wght-normal-ObQm3Zd1.woff2 +0 -0
  22. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/react-DbsxZ-Ry.js +48 -0
  23. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/style-BRg7cN4b.css +1 -0
  24. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/assets/style-D1OzGJBk.css +1 -0
  25. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/brand/a43-logo-sm.webp +0 -0
  26. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/brand/apple-touch-icon.png +0 -0
  27. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/brand/favicon.ico +0 -0
  28. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/brand/favicon.svg +4 -0
  29. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/index.html +22 -0
  30. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/manifest.json +102 -0
  31. mcpwarden_ui-1.1.0/src/mcpwarden_ui/static/theme-init.js +11 -0
  32. mcpwarden_ui-1.1.0/src/mcpwarden_ui.egg-info/PKG-INFO +121 -0
  33. mcpwarden_ui-1.1.0/src/mcpwarden_ui.egg-info/SOURCES.txt +52 -0
  34. mcpwarden_ui-1.1.0/src/mcpwarden_ui.egg-info/dependency_links.txt +1 -0
  35. mcpwarden_ui-1.1.0/src/mcpwarden_ui.egg-info/entry_points.txt +3 -0
  36. mcpwarden_ui-1.1.0/src/mcpwarden_ui.egg-info/requires.txt +3 -0
  37. mcpwarden_ui-1.1.0/src/mcpwarden_ui.egg-info/top_level.txt +1 -0
  38. mcpwarden_ui-1.1.0/tests/test_browser_csp.py +522 -0
  39. mcpwarden_ui-1.1.0/tests/test_config_service.py +1146 -0
  40. mcpwarden_ui-1.1.0/tests/test_inbox_ui.py +942 -0
  41. mcpwarden_ui-1.1.0/tests/test_rbac.py +142 -0
  42. mcpwarden_ui-1.1.0/tests/test_review5b_ui.py +148 -0
  43. mcpwarden_ui-1.1.0/tests/test_review_ui2.py +155 -0
  44. mcpwarden_ui-1.1.0/tests/test_stats_api.py +1015 -0
  45. mcpwarden_ui-1.1.0/tests/test_ui_api.py +674 -0
  46. mcpwarden_ui-1.1.0/tests/test_ui_build.py +365 -0
  47. mcpwarden_ui-1.1.0/tests/test_ui_builder.py +216 -0
  48. mcpwarden_ui-1.1.0/tests/test_ui_frontend_static.py +433 -0
  49. mcpwarden_ui-1.1.0/tests/test_ui_hostile.py +641 -0
  50. mcpwarden_ui-1.1.0/tests/test_ui_review.py +655 -0
  51. mcpwarden_ui-1.1.0/tests/test_ui_security.py +831 -0
  52. mcpwarden_ui-1.1.0/tests/test_ui_server.py +501 -0
  53. mcpwarden_ui-1.1.0/tests/test_ui_stream.py +505 -0
@@ -0,0 +1,121 @@
1
+ Metadata-Version: 2.4
2
+ Name: mcpwarden-ui
3
+ Version: 1.1.0
4
+ Summary: Local dashboard for mcpwarden-gate: visualise audit logs, edit policy, and manage approval requests.
5
+ Author: Tim Gelzleichter, A+43 Studios
6
+ License: MIT
7
+ Project-URL: Homepage, https://www.a043.xyz
8
+ Project-URL: Source, https://github.com/A043-studios/mcp-policy-gateway
9
+ Project-URL: Documentation, https://www.a043.xyz/mcpwarden
10
+ Keywords: mcp,security,gateway,ai-safety,policy
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: System Administrators
14
+ Classifier: Topic :: Security
15
+ Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
16
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
17
+ Classifier: License :: OSI Approved :: MIT License
18
+ Classifier: Programming Language :: Python :: 3
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ Requires-Dist: mcpwarden-gate<1.2,>=1.1.0.dev0
24
+ Requires-Dist: mcp>=2
25
+ Requires-Dist: httpx>=0.27
26
+
27
+ # mcpwarden-ui
28
+
29
+ Local dashboard for **mcpwarden-gate** — the MCP security gateway.
30
+
31
+ Visualise audit logs, edit policy, approve (or deny) tool calls in real time, and query the gateway from within your AI client via `mcpwarden-mcp`.
32
+
33
+ ---
34
+
35
+ ## Install
36
+
37
+ ```bash
38
+ pip install "mcpwarden-gate[ui]"
39
+ # or separately:
40
+ pip install mcpwarden-ui
41
+ ```
42
+
43
+ Requires Python 3.11+ and `mcpwarden-gate>=1.1`.
44
+
45
+ ---
46
+
47
+ ## Usage
48
+
49
+ ```bash
50
+ # Read-only dashboard (audit log viewer + policy page)
51
+ mcpwarden-ui --policy gateway.toml
52
+
53
+ # With live approval inbox (approval = "inbox" in gateway.toml)
54
+ mcpwarden-ui --policy gateway.toml --inbox
55
+
56
+ # Point at an existing audit log without a policy file
57
+ mcpwarden-ui --log audit.jsonl
58
+ ```
59
+
60
+ Opens at `http://127.0.0.1:8421` with a one-time bearer-token link printed to stdout. No data leaves your machine.
61
+
62
+ ### Docker
63
+
64
+ ```bash
65
+ docker run --rm -p 8421:8421 \
66
+ -v "$PWD/gateway.toml:/policy/gateway.toml:ro" \
67
+ -v "$PWD/audit.jsonl:/logs/audit.jsonl:ro" \
68
+ ghcr.io/a043-studios/mcpwarden-gate:latest \
69
+ mcpwarden-ui --policy /policy/gateway.toml --log /logs/audit.jsonl --host 0.0.0.0
70
+ ```
71
+
72
+ ---
73
+
74
+ ## Dashboard pages
75
+
76
+ | Page | Description |
77
+ |------|-------------|
78
+ | **Overview** | Session counts, call timeline, top tools, egress targets, recent sessions |
79
+ | **Live feed** | Real-time stream of every gateway decision |
80
+ | **Sessions** | Sortable table of all sessions; click for full timeline |
81
+ | **Blocks** | Per-control block counts, tools, and exact reasons |
82
+ | **Egress targets** | All destination hosts, with allowlist status |
83
+ | **Approvals** | Grant/deny stats per control |
84
+ | **Quarantine** | Tools blocked by pinning (changed or unreviewed) |
85
+ | **Policy** | Full loaded policy; edit in-browser when started with `--policy` |
86
+ | **Inbox** | Live approval requests (requires `--inbox`) |
87
+ | **MCP servers** | Catalog of all configured MCP servers with tool annotations |
88
+
89
+ ---
90
+
91
+ ## mcpwarden-mcp — dashboard as MCP server
92
+
93
+ `mcpwarden-mcp` exposes audit and policy data as MCP resources so your AI client can query session history without opening a browser.
94
+
95
+ ```bash
96
+ mcpwarden-mcp --policy gateway.toml --log audit.jsonl
97
+ ```
98
+
99
+ Add it alongside the gateway in your client config — see [../docs/Integrations.md](../docs/Integrations.md) for Claude Desktop, VS Code, and Cursor examples.
100
+
101
+ ---
102
+
103
+ ## Rebuilding the frontend (contributors only)
104
+
105
+ The compiled frontend (`ui/src/mcpwarden_ui/static/`) is committed. Users do **not** need Node.js.
106
+
107
+ If you edit the frontend source:
108
+
109
+ ```bash
110
+ cd ui/frontend
111
+ npm ci
112
+ npm run build:install # rebuilds and copies into ../src/mcpwarden_ui/static/
113
+ ```
114
+
115
+ ---
116
+
117
+ ## Links
118
+
119
+ - Gateway: [mcpwarden-gate on PyPI](https://pypi.org/project/mcpwarden-gate/)
120
+ - Source: [github.com/A043-studios/mcpwarden-gate](https://github.com/A043-studios/mcpwarden-gate)
121
+ - Docs: [a043.xyz/mcpwarden](https://www.a043.xyz/mcpwarden)
@@ -0,0 +1,95 @@
1
+ # mcpwarden-ui
2
+
3
+ Local dashboard for **mcpwarden-gate** — the MCP security gateway.
4
+
5
+ Visualise audit logs, edit policy, approve (or deny) tool calls in real time, and query the gateway from within your AI client via `mcpwarden-mcp`.
6
+
7
+ ---
8
+
9
+ ## Install
10
+
11
+ ```bash
12
+ pip install "mcpwarden-gate[ui]"
13
+ # or separately:
14
+ pip install mcpwarden-ui
15
+ ```
16
+
17
+ Requires Python 3.11+ and `mcpwarden-gate>=1.1`.
18
+
19
+ ---
20
+
21
+ ## Usage
22
+
23
+ ```bash
24
+ # Read-only dashboard (audit log viewer + policy page)
25
+ mcpwarden-ui --policy gateway.toml
26
+
27
+ # With live approval inbox (approval = "inbox" in gateway.toml)
28
+ mcpwarden-ui --policy gateway.toml --inbox
29
+
30
+ # Point at an existing audit log without a policy file
31
+ mcpwarden-ui --log audit.jsonl
32
+ ```
33
+
34
+ Opens at `http://127.0.0.1:8421` with a one-time bearer-token link printed to stdout. No data leaves your machine.
35
+
36
+ ### Docker
37
+
38
+ ```bash
39
+ docker run --rm -p 8421:8421 \
40
+ -v "$PWD/gateway.toml:/policy/gateway.toml:ro" \
41
+ -v "$PWD/audit.jsonl:/logs/audit.jsonl:ro" \
42
+ ghcr.io/a043-studios/mcpwarden-gate:latest \
43
+ mcpwarden-ui --policy /policy/gateway.toml --log /logs/audit.jsonl --host 0.0.0.0
44
+ ```
45
+
46
+ ---
47
+
48
+ ## Dashboard pages
49
+
50
+ | Page | Description |
51
+ |------|-------------|
52
+ | **Overview** | Session counts, call timeline, top tools, egress targets, recent sessions |
53
+ | **Live feed** | Real-time stream of every gateway decision |
54
+ | **Sessions** | Sortable table of all sessions; click for full timeline |
55
+ | **Blocks** | Per-control block counts, tools, and exact reasons |
56
+ | **Egress targets** | All destination hosts, with allowlist status |
57
+ | **Approvals** | Grant/deny stats per control |
58
+ | **Quarantine** | Tools blocked by pinning (changed or unreviewed) |
59
+ | **Policy** | Full loaded policy; edit in-browser when started with `--policy` |
60
+ | **Inbox** | Live approval requests (requires `--inbox`) |
61
+ | **MCP servers** | Catalog of all configured MCP servers with tool annotations |
62
+
63
+ ---
64
+
65
+ ## mcpwarden-mcp — dashboard as MCP server
66
+
67
+ `mcpwarden-mcp` exposes audit and policy data as MCP resources so your AI client can query session history without opening a browser.
68
+
69
+ ```bash
70
+ mcpwarden-mcp --policy gateway.toml --log audit.jsonl
71
+ ```
72
+
73
+ Add it alongside the gateway in your client config — see [../docs/Integrations.md](../docs/Integrations.md) for Claude Desktop, VS Code, and Cursor examples.
74
+
75
+ ---
76
+
77
+ ## Rebuilding the frontend (contributors only)
78
+
79
+ The compiled frontend (`ui/src/mcpwarden_ui/static/`) is committed. Users do **not** need Node.js.
80
+
81
+ If you edit the frontend source:
82
+
83
+ ```bash
84
+ cd ui/frontend
85
+ npm ci
86
+ npm run build:install # rebuilds and copies into ../src/mcpwarden_ui/static/
87
+ ```
88
+
89
+ ---
90
+
91
+ ## Links
92
+
93
+ - Gateway: [mcpwarden-gate on PyPI](https://pypi.org/project/mcpwarden-gate/)
94
+ - Source: [github.com/A043-studios/mcpwarden-gate](https://github.com/A043-studios/mcpwarden-gate)
95
+ - Docs: [a043.xyz/mcpwarden](https://www.a043.xyz/mcpwarden)
@@ -0,0 +1,43 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "mcpwarden-ui"
7
+ version = "1.1.0"
8
+ description = "Local dashboard for mcpwarden-gate: visualise audit logs, edit policy, and manage approval requests."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = { text = "MIT" }
12
+ authors = [{ name = "Tim Gelzleichter, A+43 Studios" }]
13
+ keywords = ["mcp", "security", "gateway", "ai-safety", "policy"]
14
+ classifiers = [
15
+ "Development Status :: 4 - Beta",
16
+ "Intended Audience :: Developers",
17
+ "Intended Audience :: System Administrators",
18
+ "Topic :: Security",
19
+ "Topic :: Internet :: WWW/HTTP :: HTTP Servers",
20
+ "Topic :: Software Development :: Libraries :: Python Modules",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Programming Language :: Python :: 3",
23
+ "Programming Language :: Python :: 3.11",
24
+ "Programming Language :: Python :: 3.12",
25
+ ]
26
+ dependencies = ["mcpwarden-gate>=1.1.0.dev0,<1.2", "mcp>=2", "httpx>=0.27"]
27
+
28
+ [project.urls]
29
+ Homepage = "https://www.a043.xyz"
30
+ Source = "https://github.com/A043-studios/mcp-policy-gateway"
31
+ Documentation = "https://www.a043.xyz/mcpwarden"
32
+
33
+ [project.scripts]
34
+ mcpwarden-ui = "mcpwarden_ui.__main__:main"
35
+ mcpwarden-mcp = "mcpwarden_ui.mcp_server:main"
36
+
37
+ [tool.setuptools.packages.find]
38
+ where = ["src"]
39
+
40
+ [tool.setuptools.package-data]
41
+ # the whole checked-in build of the interface (index.html, manifest.json, assets/, brand/): the server serves what the
42
+ # manifest lists and refuses to start when a listed file is missing
43
+ mcpwarden_ui = ["static/*", "static/**/*"]
@@ -0,0 +1,17 @@
1
+ [options]
2
+ package_dir =
3
+ = src
4
+ packages = find:
5
+
6
+ [options.packages.find]
7
+ where = src
8
+
9
+ [options.package_data]
10
+ mcpwarden_ui =
11
+ static/*
12
+ static/**/*
13
+
14
+ [egg_info]
15
+ tag_build =
16
+ tag_date = 0
17
+
@@ -0,0 +1,3 @@
1
+ """mcpwarden-ui: a local, read-only dashboard for the audit log of mcpwarden-gate (docs/SPEC-ui.md, part B)."""
2
+
3
+ __version__ = "1.1.0.dev0"
@@ -0,0 +1,320 @@
1
+ """``mcpwarden-ui`` / ``python -m mcpwarden_ui``: start the local, read-only dashboard (docs/SPEC-ui.md, B1).
2
+
3
+ mcpwarden-ui [--policy gateway.toml] [--log PATH] [--port 8421] [--no-open] [--stale-after 300]
4
+ [--inbox [--state-dir DIR]]
5
+
6
+ Binds to 127.0.0.1 only. ``--bind-in-container`` binds to 0.0.0.0 instead (requires ``/.dockerenv`` or
7
+ ``MCPWARDEN_IN_CONTAINER=1``); use it only inside a container whose port mapping is ``127.0.0.1:PORT:PORT``
8
+ so the host sees only the loopback address. Prints one line with the URL; the token
9
+ is in the fragment (``#t=``), so it never reaches a server log, a Referer header or a proxy. The browser
10
+ that is started is NOT given the token (it would stand in the argument list of the starter and in the
11
+ browser history) but a one-time code (``#c=``, valid 30 seconds, used once) that the page trades for the
12
+ token (``Handoff`` in ``server.py``).
13
+ With ``--inbox`` the dashboard is NOT read-only any more: it shows the open requests of the approvals inbox
14
+ (docs/SPEC-inbox.md) and one POST endpoint lets a person grant or deny one request (a signed decision file in the
15
+ state directory). Without ``--inbox`` nothing changes: only GET and HEAD, no key is read, no state directory is opened.
16
+ Exit codes: 0 normal end (Ctrl-C, SIGTERM), 2 for a missing log, a policy that cannot be loaded, a
17
+ port that is taken or an unusable argument.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import errno
24
+ import os
25
+ import secrets
26
+ import signal
27
+ import sys
28
+ import threading
29
+ import time
30
+ from pathlib import Path
31
+
32
+ from . import __version__
33
+
34
+
35
+ def _safe(text) -> str:
36
+ """Text for a message on the terminal: control characters shown as escapes."""
37
+ return "".join(c if c.isprintable() else f"\\x{ord(c):02x}" for c in str(text))
38
+
39
+
40
+ def _mask(token: str) -> str:
41
+ """Return first 8 characters of token followed by ellipsis, to avoid logging full tokens."""
42
+ return token[:8] + "…" if len(token) > 8 else token
43
+
44
+
45
+ def _parser() -> argparse.ArgumentParser:
46
+ p = argparse.ArgumentParser(prog="mcpwarden-ui", description="Local dashboard for the mcpwarden-gate audit log "
47
+ "(read-only; with --inbox it also records decisions of the approvals inbox).")
48
+ p.add_argument("--policy", help="policy file (allowlist comparison and the policy view; default log path)")
49
+ p.add_argument("--log", help="audit log: a file or a directory (default: audit_log of the policy)")
50
+ p.add_argument("--port", type=int, default=8421, help="port on 127.0.0.1 (default 8421; 0 picks a free one)")
51
+ p.add_argument("--no-open", action="store_true", help="do not open the browser")
52
+ p.add_argument("--stale-after", type=float, default=300.0, help="seconds after which a session without session_end counts as inactive (default 300)")
53
+ p.add_argument("--inbox", action="store_true",
54
+ help="also show the open approvals of the inbox and let a person decide them (not read-only any more; "
55
+ "needs --policy or --state-dir)")
56
+ p.add_argument("--state-dir", help="--inbox: the state directory of the gateway (default: state_dir of the policy)")
57
+ p.add_argument("--manage", action="store_true",
58
+ help="enable the write layer (propose/apply policy changes, run tools); "
59
+ "POSIX only; requires --policy and a TTY; the dashboard is NOT read-only any more")
60
+ p.add_argument("--manage-dir", default=None,
61
+ help="override the manage directory (default: ~/.local/state/mcpwarden-gate/manage/<hash>)")
62
+ p.add_argument("--bind-in-container", action="store_true",
63
+ help="bind to 0.0.0.0 instead of 127.0.0.1 (container use only; requires /.dockerenv or "
64
+ "MCPWARDEN_IN_CONTAINER=1; map only 127.0.0.1:PORT:PORT on the host)")
65
+ p.add_argument("--viewer-token", metavar="TOKEN",
66
+ default=os.environ.get("MCPWARDEN_VIEWER_TOKEN"),
67
+ help="register this token with viewer role (read-only access; or set MCPWARDEN_VIEWER_TOKEN env var)")
68
+ p.add_argument("--approver-token", metavar="TOKEN",
69
+ default=os.environ.get("MCPWARDEN_APPROVER_TOKEN"),
70
+ help="register this token with approver role (viewer + inbox decisions; or set MCPWARDEN_APPROVER_TOKEN env var)")
71
+ p.add_argument("--version", action="version", version=f"mcpwarden-ui {__version__}")
72
+ return p
73
+
74
+
75
+ def main(argv: list[str] | None = None) -> int:
76
+ args = _parser().parse_args(argv)
77
+ if not 0 <= args.port <= 65535:
78
+ print("mcpwarden-ui: --port must be between 0 and 65535", file=sys.stderr)
79
+ return 2
80
+ if not args.stale_after > 0:
81
+ print("mcpwarden-ui: --stale-after must be greater than 0", file=sys.stderr)
82
+ return 2
83
+ bind_host = "127.0.0.1"
84
+ if args.bind_in_container:
85
+ in_container = Path("/.dockerenv").exists() or os.environ.get("MCPWARDEN_IN_CONTAINER") == "1"
86
+ if not in_container:
87
+ print("mcpwarden-ui: --bind-in-container requires /.dockerenv or MCPWARDEN_IN_CONTAINER=1 "
88
+ "(do not use this flag outside a container)", file=sys.stderr)
89
+ return 2
90
+ bind_host = "0.0.0.0"
91
+ from mcpwarden_gate.config import Policy
92
+
93
+ from . import api, policyview, rbac
94
+ from .server import Handoff, StaticError, UIServer, load_static
95
+
96
+ try: # the build of the interface must match its manifest
97
+ static = load_static()
98
+ except StaticError as exc:
99
+ print(f"mcpwarden-ui: {_safe(exc)}; reinstall the package (or run `npm run build:install` in ui/frontend)",
100
+ file=sys.stderr)
101
+ return 2
102
+
103
+ if args.manage and not args.policy:
104
+ print("mcpwarden-ui: --manage needs --policy", file=sys.stderr)
105
+ return 2
106
+ if args.state_dir and not args.inbox:
107
+ print("mcpwarden-ui: --state-dir is only for --inbox", file=sys.stderr)
108
+ return 2
109
+ if args.inbox and not (args.policy or args.state_dir):
110
+ print("mcpwarden-ui: --inbox needs --policy (its state_dir) or --state-dir", file=sys.stderr)
111
+ return 2
112
+
113
+ manager = None
114
+ tty_fd = -1
115
+ if args.manage:
116
+ # Platform check
117
+ if os.name != "posix":
118
+ print("mcpwarden-ui: --manage is not supported on Windows", file=sys.stderr)
119
+ return 2
120
+ # Policy required
121
+ if not args.policy:
122
+ print("mcpwarden-ui: --manage requires --policy", file=sys.stderr)
123
+ return 2
124
+ # TTY check
125
+ try:
126
+ tty_fd = os.open("/dev/tty", os.O_RDWR | os.O_NOCTTY)
127
+ except OSError:
128
+ print("mcpwarden-ui: --manage requires a terminal: start in the foreground with a TTY",
129
+ file=sys.stderr)
130
+ return 2
131
+ # Background check
132
+ try:
133
+ if os.tcgetpgrp(tty_fd) != os.getpgrp():
134
+ os.close(tty_fd)
135
+ print("mcpwarden-ui: --manage must run in the foreground (not background)", file=sys.stderr)
136
+ return 2
137
+ except OSError:
138
+ os.close(tty_fd)
139
+ print("mcpwarden-ui: --manage requires a terminal: start in the foreground with a TTY",
140
+ file=sys.stderr)
141
+ return 2
142
+ # Resolve manage_dir and open manager
143
+ from mcpwarden_gate.manage import resolve_manage_dir, open_manage, ManageStartError
144
+ try:
145
+ manage_dir = resolve_manage_dir(args.policy, args.manage_dir)
146
+ except ManageStartError as exc:
147
+ os.close(tty_fd)
148
+ print(f"mcpwarden-ui: cannot start manage: {_safe(exc.message)}", file=sys.stderr)
149
+ return 2
150
+ try:
151
+ manager = open_manage(args.policy, manage_dir=manage_dir,
152
+ state_dir=args.state_dir if args.inbox else None,
153
+ inbox=args.inbox, via="ui")
154
+ except ManageStartError as exc:
155
+ os.close(tty_fd)
156
+ print(f"mcpwarden-ui: cannot start manage: {_safe(exc.message)}", file=sys.stderr)
157
+ return 2
158
+
159
+ policy = None
160
+ if args.policy:
161
+ try:
162
+ policy = Policy.load(args.policy)
163
+ except (OSError, ValueError, UnicodeDecodeError) as exc:
164
+ print(f"mcpwarden-ui: cannot load the policy: {_safe(exc)}", file=sys.stderr)
165
+ return 2
166
+ except Exception as exc: # tomllib.TOMLDecodeError and the like
167
+ import tomllib as _tomllib # noqa: PLC0415
168
+ if isinstance(exc, _tomllib.TOMLDecodeError):
169
+ print(f"mcpwarden-ui: TOML syntax error in {_safe(args.policy)}: {_safe(exc)}", file=sys.stderr)
170
+ else:
171
+ print(f"mcpwarden-ui: cannot load the policy: {type(exc).__name__}: {_safe(exc)}", file=sys.stderr)
172
+ return 2
173
+ log = Path(args.log) if args.log else (policy.audit_log if policy else None)
174
+ if log is None:
175
+ print("mcpwarden-ui: no audit log: give --log, or --policy with an audit_log", file=sys.stderr)
176
+ return 2
177
+ if not log.exists():
178
+ print(f"mcpwarden-ui: the audit log does not exist: {_safe(log)}", file=sys.stderr)
179
+ return 2
180
+ policy_json = api.dumps(policyview.summarize(policy) if policy else policyview.unknown())
181
+ service = None
182
+ if args.inbox:
183
+ from mcpwarden_gate import inbox as core
184
+
185
+ from .inbox import InboxService
186
+ try:
187
+ state = Path(args.state_dir) if args.state_dir else policy.resolved_state_dir()
188
+ except core.InboxError as exc:
189
+ print(f"mcpwarden-ui: the inbox cannot be used: {_safe(exc)}", file=sys.stderr)
190
+ return 2
191
+ service = InboxService(state)
192
+ try:
193
+ service.check() # directory 0700 and ours, key readable with 0600
194
+ except core.InboxError as exc:
195
+ print(f"mcpwarden-ui: the inbox cannot be used: {_safe(exc)}", file=sys.stderr)
196
+ return 2
197
+
198
+ config_service = api.ConfigService(Path(args.policy)) if args.policy else None
199
+ token = secrets.token_urlsafe(32)
200
+ registry = rbac.TokenRegistry()
201
+ registry.add(token, "admin")
202
+ if args.viewer_token:
203
+ registry.add(args.viewer_token, "viewer")
204
+ if args.approver_token:
205
+ registry.add(args.approver_token, "approver")
206
+ hub = api.Hub(log, stale_after=args.stale_after, allow=policy.egress_allow if policy else None,
207
+ policy_path=args.policy)
208
+ handoff = Handoff()
209
+ try:
210
+ server = UIServer(args.port, hub, token, policy_json, handoff, service, static, config_service,
211
+ registry=registry, bind_host=bind_host, manage=manager, policy=policy)
212
+ except OSError as exc:
213
+ why = "port in use" if exc.errno == errno.EADDRINUSE else _safe(exc.strerror or type(exc).__name__)
214
+ if tty_fd >= 0:
215
+ os.close(tty_fd)
216
+ if manager is not None:
217
+ manager.close()
218
+ print(f"mcpwarden-ui: cannot listen on {bind_host}:{args.port}: {why}", file=sys.stderr)
219
+ return 2
220
+
221
+ def stop(*_a) -> None:
222
+ threading.Thread(target=server.shutdown_all, daemon=True).start()
223
+
224
+ # The handlers go in BEFORE anything is printed: whoever reads the address may send SIGINT at once, and an
225
+ # interrupt that arrives while the start line is written must end the server quietly, not with a traceback.
226
+ # (A shutdown requested before serve_forever starts makes serve_forever return at once.)
227
+ for sig in (signal.SIGINT, signal.SIGTERM):
228
+ try:
229
+ signal.signal(sig, stop)
230
+ except (ValueError, OSError):
231
+ pass
232
+ # SIGHUP: terminal close (also relevant with --manage)
233
+ try:
234
+ signal.signal(signal.SIGHUP, stop) # type: ignore[attr-defined]
235
+ except (ValueError, OSError, AttributeError):
236
+ pass
237
+ hub.start() # reads the log once before the first answer
238
+ display_host = "localhost" if bind_host == "0.0.0.0" else "127.0.0.1"
239
+ if args.manage:
240
+ # With --manage: no token in stdout, no browser open
241
+ print(f"mcpwarden-ui listening on http://127.0.0.1:{server.port}/", flush=True)
242
+ print(f"mcpwarden-ui: --manage is on: this dashboard is NOT read-only; it can change "
243
+ f"{_safe(args.policy)}", file=sys.stderr, flush=True)
244
+ print(f"mcpwarden-ui: manage data in {_safe(manage_dir)}", file=sys.stderr, flush=True)
245
+ print("mcpwarden-ui: press Enter in this terminal for a one-time login link "
246
+ "(valid 30 s, single use)", file=sys.stderr, flush=True)
247
+ tty_file = os.fdopen(tty_fd, "r+", buffering=1)
248
+ tty_fd = -1 # ownership transferred to tty_file
249
+ threading.Thread(target=_login_thread, args=(tty_file, handoff, server.port, stop),
250
+ daemon=True, name="mcpwarden-ui-login").start()
251
+ else:
252
+ url = f"http://{display_host}:{server.port}/#t={token}"
253
+ print(f"Admin: {url}", flush=True)
254
+ if args.approver_token:
255
+ print(f"Approver: {_mask(args.approver_token)} (Bearer token — see startup log for full value or use env var)", flush=True)
256
+ if args.viewer_token:
257
+ print(f"Viewer: {_mask(args.viewer_token)} (Bearer token — see startup log for full value or use env var)", flush=True)
258
+ if not args.no_open: # the browser gets a one-time code, not the token
259
+ code_url = f"http://127.0.0.1:{server.port}/#c={handoff.issue()}"
260
+ threading.Thread(target=_open, args=(code_url,), daemon=True).start()
261
+ if service is not None:
262
+ print("mcpwarden-ui: --inbox is on: this dashboard is NOT read-only; it can record decisions on approvals "
263
+ f"({_safe(service.state_dir)})", file=sys.stderr, flush=True)
264
+ try:
265
+ server.serve_forever(poll_interval=0.25)
266
+ finally:
267
+ hub.close()
268
+ if manager is not None:
269
+ manager.close()
270
+ server.server_close()
271
+ if manager is not None:
272
+ manager.close()
273
+ return 0
274
+
275
+
276
+ def _open(url: str) -> None:
277
+ try:
278
+ import webbrowser
279
+ webbrowser.open(url)
280
+ except Exception:
281
+ pass
282
+
283
+
284
+ def _login_thread(tty_file, handoff, port: int, stop_fn) -> None:
285
+ """Reads Enter presses from /dev/tty and prints one-time login links (spec 1.1 point 4)."""
286
+ _last_code: str | None = None
287
+ _last_time: float = 0.0
288
+ try:
289
+ while True:
290
+ try:
291
+ line = tty_file.readline()
292
+ except (OSError, EOFError, ValueError):
293
+ stop_fn()
294
+ return
295
+ if not line:
296
+ stop_fn()
297
+ return
298
+ now = time.monotonic()
299
+ if _last_code is not None and now - _last_time < 2.0:
300
+ code = _last_code # re-print same code, do not issue a new one
301
+ else:
302
+ code = handoff.issue()
303
+ _last_code = code
304
+ _last_time = now
305
+ msg = f"mcpwarden-ui: open http://127.0.0.1:{port}/#c={code} (valid 30 s, single use)\n"
306
+ try:
307
+ tty_file.write(msg)
308
+ tty_file.flush()
309
+ except OSError:
310
+ stop_fn()
311
+ return
312
+ finally:
313
+ try:
314
+ tty_file.close()
315
+ except OSError:
316
+ pass
317
+
318
+
319
+ if __name__ == "__main__":
320
+ sys.exit(main())