dms-mcp 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,5 @@
1
+ .venv/
2
+ __pycache__/
3
+ dist/
4
+ build/
5
+ *.egg-info/
dms_mcp-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 obaaio
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
dms_mcp-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,105 @@
1
+ Metadata-Version: 2.5
2
+ Name: dms-mcp
3
+ Version: 0.1.0
4
+ Summary: MCP server for administering docker-mailserver via its setup CLI
5
+ Author: obaaio
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Keywords: docker-mailserver,dovecot,email,mcp,model-context-protocol,postfix
9
+ Classifier: Operating System :: POSIX
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Communications :: Email :: Mail Transport Agents
12
+ Classifier: Topic :: System :: Systems Administration
13
+ Requires-Python: >=3.10
14
+ Requires-Dist: mcp<3,>=2.3
15
+ Description-Content-Type: text/markdown
16
+
17
+ # dms-mcp
18
+
19
+ An MCP server for administering [docker-mailserver](https://github.com/docker-mailserver/docker-mailserver).
20
+ Each tool wraps the container's `setup` script (`docker exec -i <container> setup ...`), locally or on a remote host over SSH.
21
+
22
+ ## Tools
23
+
24
+ | Area | Tools |
25
+ |---|---|
26
+ | Accounts | `list_accounts`, `add_account`, `update_password`, `delete_account`, `list_restrictions`, `restrict_account` |
27
+ | Aliases | `list_aliases`, `add_alias` (supports `@domain` catch-all), `delete_alias` |
28
+ | Quotas | `set_quota`, `delete_quota` |
29
+ | DKIM | `generate_dkim`, `show_dkim_record` |
30
+ | Fail2ban | `fail2ban_status`, `fail2ban_ban`, `fail2ban_unban` |
31
+ | Ops | `mail_log` (tail + filter), `mail_queue`, `flush_queue`, `server_status` |
32
+
33
+ - Passwords go over stdin and never appear in process arguments. If you omit the password, the tool generates a 24-character one and returns it.
34
+ - `delete_account` keeps stored mail unless `delete_mail=true`.
35
+ - Every input is validated (addresses, domains, IPs, quotas), and in SSH mode every argument is shell-quoted.
36
+ - Tools carry read-only/destructive hints, so MCP clients can ask for confirmation before destructive actions.
37
+
38
+ ## Install
39
+
40
+ No clone needed. Run it straight from PyPI with [uv](https://docs.astral.sh/uv/):
41
+
42
+ ```bash
43
+ uvx dms-mcp --version
44
+ ```
45
+
46
+ or install it as a command with pipx or pip:
47
+
48
+ ```bash
49
+ pipx install dms-mcp # or: pip install dms-mcp
50
+ ```
51
+
52
+ ## Configure
53
+
54
+ | Env var | Default | Purpose |
55
+ |---|---|---|
56
+ | `DMS_CONTAINER` | `mailserver` | Container name |
57
+ | `DMS_SSH_HOST` | (unset) | e.g. `admin@mail.example.com`, which runs docker on that host over SSH (needs key auth) |
58
+ | `DMS_DOCKER_BIN` | `docker` | Docker binary on the target host |
59
+ | `DMS_TIMEOUT` | `60` | Per-command timeout in seconds |
60
+
61
+ Instead of `DMS_SSH_HOST`, you can also set `DOCKER_HOST=ssh://admin@mail.example.com` or `DOCKER_CONTEXT`; the docker CLI handles both natively.
62
+
63
+ ### Claude Code
64
+
65
+ ```bash
66
+ claude mcp add dms -s user \
67
+ -e DMS_SSH_HOST=admin@mail.example.com -e DMS_CONTAINER=mailserver \
68
+ -- uvx dms-mcp
69
+ ```
70
+
71
+ ### Claude Desktop / Cursor / other clients (`mcpServers` JSON)
72
+
73
+ ```json
74
+ {
75
+ "mcpServers": {
76
+ "dms": {
77
+ "command": "uvx",
78
+ "args": ["dms-mcp"],
79
+ "env": { "DMS_SSH_HOST": "admin@mail.example.com", "DMS_CONTAINER": "mailserver" }
80
+ }
81
+ }
82
+ }
83
+ ```
84
+
85
+ If you installed with pipx/pip, use `"command": "dms-mcp"` and drop `args`.
86
+
87
+ ## Security
88
+
89
+ Running this server is the same as having shell access to the mail container, and docker access usually means root on that host. Use a dedicated SSH key, and consider restricting it with a `command=` wrapper in `authorized_keys` that only allows `docker exec -i mailserver ...`.
90
+
91
+ ## Development
92
+
93
+ ```bash
94
+ python3 -m venv .venv && .venv/bin/pip install -e .
95
+ .venv/bin/python tests/test_server.py # uses a stub docker binary, no server needed
96
+ ```
97
+
98
+ ## Releasing
99
+
100
+ CI (`.gitea/workflows/ci.yaml`) runs the tests on every push and PR. To publish to PyPI:
101
+
102
+ 1. Bump `version` in `pyproject.toml` and commit.
103
+ 2. Tag and push: `git tag v0.1.0 && git push origin v0.1.0`
104
+
105
+ The publish job checks that the tag matches the version in `pyproject.toml`, then uploads using the `PYPI_API_TOKEN` org secret.
@@ -0,0 +1,89 @@
1
+ # dms-mcp
2
+
3
+ An MCP server for administering [docker-mailserver](https://github.com/docker-mailserver/docker-mailserver).
4
+ Each tool wraps the container's `setup` script (`docker exec -i <container> setup ...`), locally or on a remote host over SSH.
5
+
6
+ ## Tools
7
+
8
+ | Area | Tools |
9
+ |---|---|
10
+ | Accounts | `list_accounts`, `add_account`, `update_password`, `delete_account`, `list_restrictions`, `restrict_account` |
11
+ | Aliases | `list_aliases`, `add_alias` (supports `@domain` catch-all), `delete_alias` |
12
+ | Quotas | `set_quota`, `delete_quota` |
13
+ | DKIM | `generate_dkim`, `show_dkim_record` |
14
+ | Fail2ban | `fail2ban_status`, `fail2ban_ban`, `fail2ban_unban` |
15
+ | Ops | `mail_log` (tail + filter), `mail_queue`, `flush_queue`, `server_status` |
16
+
17
+ - Passwords go over stdin and never appear in process arguments. If you omit the password, the tool generates a 24-character one and returns it.
18
+ - `delete_account` keeps stored mail unless `delete_mail=true`.
19
+ - Every input is validated (addresses, domains, IPs, quotas), and in SSH mode every argument is shell-quoted.
20
+ - Tools carry read-only/destructive hints, so MCP clients can ask for confirmation before destructive actions.
21
+
22
+ ## Install
23
+
24
+ No clone needed. Run it straight from PyPI with [uv](https://docs.astral.sh/uv/):
25
+
26
+ ```bash
27
+ uvx dms-mcp --version
28
+ ```
29
+
30
+ or install it as a command with pipx or pip:
31
+
32
+ ```bash
33
+ pipx install dms-mcp # or: pip install dms-mcp
34
+ ```
35
+
36
+ ## Configure
37
+
38
+ | Env var | Default | Purpose |
39
+ |---|---|---|
40
+ | `DMS_CONTAINER` | `mailserver` | Container name |
41
+ | `DMS_SSH_HOST` | (unset) | e.g. `admin@mail.example.com`, which runs docker on that host over SSH (needs key auth) |
42
+ | `DMS_DOCKER_BIN` | `docker` | Docker binary on the target host |
43
+ | `DMS_TIMEOUT` | `60` | Per-command timeout in seconds |
44
+
45
+ Instead of `DMS_SSH_HOST`, you can also set `DOCKER_HOST=ssh://admin@mail.example.com` or `DOCKER_CONTEXT`; the docker CLI handles both natively.
46
+
47
+ ### Claude Code
48
+
49
+ ```bash
50
+ claude mcp add dms -s user \
51
+ -e DMS_SSH_HOST=admin@mail.example.com -e DMS_CONTAINER=mailserver \
52
+ -- uvx dms-mcp
53
+ ```
54
+
55
+ ### Claude Desktop / Cursor / other clients (`mcpServers` JSON)
56
+
57
+ ```json
58
+ {
59
+ "mcpServers": {
60
+ "dms": {
61
+ "command": "uvx",
62
+ "args": ["dms-mcp"],
63
+ "env": { "DMS_SSH_HOST": "admin@mail.example.com", "DMS_CONTAINER": "mailserver" }
64
+ }
65
+ }
66
+ }
67
+ ```
68
+
69
+ If you installed with pipx/pip, use `"command": "dms-mcp"` and drop `args`.
70
+
71
+ ## Security
72
+
73
+ Running this server is the same as having shell access to the mail container, and docker access usually means root on that host. Use a dedicated SSH key, and consider restricting it with a `command=` wrapper in `authorized_keys` that only allows `docker exec -i mailserver ...`.
74
+
75
+ ## Development
76
+
77
+ ```bash
78
+ python3 -m venv .venv && .venv/bin/pip install -e .
79
+ .venv/bin/python tests/test_server.py # uses a stub docker binary, no server needed
80
+ ```
81
+
82
+ ## Releasing
83
+
84
+ CI (`.gitea/workflows/ci.yaml`) runs the tests on every push and PR. To publish to PyPI:
85
+
86
+ 1. Bump `version` in `pyproject.toml` and commit.
87
+ 2. Tag and push: `git tag v0.1.0 && git push origin v0.1.0`
88
+
89
+ The publish job checks that the tag matches the version in `pyproject.toml`, then uploads using the `PYPI_API_TOKEN` org secret.
@@ -0,0 +1,29 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "dms-mcp"
7
+ version = "0.1.0"
8
+ description = "MCP server for administering docker-mailserver via its setup CLI"
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ authors = [{ name = "obaaio" }]
13
+ keywords = ["mcp", "docker-mailserver", "email", "postfix", "dovecot", "model-context-protocol"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: POSIX",
17
+ "Topic :: Communications :: Email :: Mail Transport Agents",
18
+ "Topic :: System :: Systems Administration",
19
+ ]
20
+ dependencies = ["mcp>=2.3,<3"]
21
+
22
+ [project.scripts]
23
+ dms-mcp = "dms_mcp.server:main"
24
+
25
+ [tool.hatch.build.targets.sdist]
26
+ include = ["src/dms_mcp", "tests", "README.md", "LICENSE"]
27
+
28
+ [tool.hatch.build.targets.wheel]
29
+ packages = ["src/dms_mcp"]
@@ -0,0 +1,8 @@
1
+ """MCP server for administering docker-mailserver."""
2
+
3
+ from importlib.metadata import PackageNotFoundError, version
4
+
5
+ try:
6
+ __version__ = version("dms-mcp")
7
+ except PackageNotFoundError: # running from a source checkout
8
+ __version__ = "0.0.0"
@@ -0,0 +1,3 @@
1
+ from dms_mcp.server import main
2
+
3
+ main()
@@ -0,0 +1,330 @@
1
+ """MCP server for administering a docker-mailserver (DMS) instance.
2
+
3
+ Every tool is a thin wrapper around the container's `setup` script, so behaviour
4
+ matches `docker exec <container> setup ...` exactly.
5
+
6
+ Configuration (environment variables):
7
+ DMS_CONTAINER Container name (default: mailserver)
8
+ DMS_SSH_HOST Optional. Run docker on a remote host over SSH, e.g. admin@mail.example.com
9
+ (uses your ssh config / agent; key auth required, no prompts).
10
+ DMS_DOCKER_BIN Docker binary on the target host (default: docker)
11
+ DMS_TIMEOUT Seconds before a command is aborted (default: 60)
12
+ Alternatively, leave DMS_SSH_HOST unset and use DOCKER_HOST=ssh://... or
13
+ DOCKER_CONTEXT, which the docker CLI honours natively.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import ipaddress
19
+ import os
20
+ import re
21
+ import secrets
22
+ import shlex
23
+ import string
24
+ import subprocess
25
+
26
+ from mcp.server.mcpserver import MCPServer
27
+ from mcp.types import ToolAnnotations
28
+
29
+ CONTAINER = os.environ.get("DMS_CONTAINER", "mailserver")
30
+ SSH_HOST = os.environ.get("DMS_SSH_HOST", "").strip()
31
+ DOCKER_BIN = os.environ.get("DMS_DOCKER_BIN", "docker")
32
+ TIMEOUT = int(os.environ.get("DMS_TIMEOUT", "60"))
33
+
34
+ mcp = MCPServer(
35
+ name="docker-mailserver",
36
+ instructions=(
37
+ "Administer a docker-mailserver instance: mailboxes, aliases, quotas, "
38
+ "send/receive restrictions, DKIM, Fail2ban and logs. Confirm with the "
39
+ "user before deleting accounts or aliases."
40
+ ),
41
+ )
42
+
43
+ READ = ToolAnnotations(readOnlyHint=True, idempotentHint=True)
44
+ WRITE = ToolAnnotations(readOnlyHint=False, destructiveHint=False)
45
+ DESTRUCTIVE = ToolAnnotations(readOnlyHint=False, destructiveHint=True)
46
+
47
+ # --------------------------------------------------------------------------- helpers
48
+
49
+ _EMAIL = re.compile(r"^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+$")
50
+ _DOMAIN = re.compile(r"^[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+$")
51
+ _QUOTA = re.compile(r"^\d+[BkKMGT]?$")
52
+ _SELECTOR = re.compile(r"^[A-Za-z0-9_-]{1,63}$")
53
+
54
+
55
+ def _email(value: str, field: str = "address") -> str:
56
+ value = value.strip()
57
+ if not _EMAIL.match(value):
58
+ raise ValueError(f"Invalid {field}: {value!r}")
59
+ return value
60
+
61
+
62
+ def _alias_or_email(value: str) -> str:
63
+ """Aliases may be a full address or a catch-all like @example.com."""
64
+ value = value.strip()
65
+ if value.startswith("@") and _DOMAIN.match(value[1:]):
66
+ return value
67
+ return _email(value, "alias")
68
+
69
+
70
+ def _domain(value: str) -> str:
71
+ value = value.strip()
72
+ if not _DOMAIN.match(value):
73
+ raise ValueError(f"Invalid domain: {value!r}")
74
+ return value
75
+
76
+
77
+ def _ip(value: str) -> str:
78
+ value = value.strip()
79
+ try:
80
+ ipaddress.ip_network(value, strict=False)
81
+ except ValueError as e:
82
+ raise ValueError(f"Invalid IP/CIDR: {value!r}") from e
83
+ return value
84
+
85
+
86
+ def _gen_password(length: int = 24) -> str:
87
+ alphabet = string.ascii_letters + string.digits + "-_.,"
88
+ return "".join(secrets.choice(alphabet) for _ in range(length))
89
+
90
+
91
+ def _build_cmd(args: list[str]) -> list[str]:
92
+ inner = [DOCKER_BIN, "exec", "-i", CONTAINER, *args]
93
+ if SSH_HOST:
94
+ # ssh joins remote args into a shell string, so quote every token.
95
+ return ["ssh", "-o", "BatchMode=yes", SSH_HOST, "--", shlex.join(inner)]
96
+ return inner
97
+
98
+
99
+ def _run(args: list[str], stdin: str | None = None) -> str:
100
+ cmd = _build_cmd(args)
101
+ try:
102
+ proc = subprocess.run(
103
+ # Always supply stdin: inheriting it would hand the child the MCP stdio pipe.
104
+ cmd, input=stdin or "", capture_output=True, text=True, timeout=TIMEOUT
105
+ )
106
+ except FileNotFoundError as e:
107
+ raise RuntimeError(f"Command not found: {cmd[0]}") from e
108
+ except subprocess.TimeoutExpired as e:
109
+ raise RuntimeError(f"Timed out after {TIMEOUT}s: {' '.join(args)}") from e
110
+ out = (proc.stdout + ("\n" + proc.stderr if proc.stderr.strip() else "")).strip()
111
+ # Strip the interactive password prompt echoed when we feed passwords on stdin.
112
+ out = re.sub(r"^Enter Password:\s*", "", out, flags=re.M).strip()
113
+ if proc.returncode != 0:
114
+ raise RuntimeError(f"`setup {' '.join(args[1:])}` failed (exit {proc.returncode}):\n{out}")
115
+ return out or "OK"
116
+
117
+
118
+ def _setup(*args: str, stdin: str | None = None) -> str:
119
+ return _run(["setup", *args], stdin=stdin)
120
+
121
+
122
+ # --------------------------------------------------------------------------- accounts
123
+
124
+
125
+ @mcp.tool(annotations=READ)
126
+ def list_accounts() -> str:
127
+ """List all mailboxes with their quota usage and aliases."""
128
+ return _setup("email", "list")
129
+
130
+
131
+ @mcp.tool(annotations=WRITE)
132
+ def add_account(address: str, password: str | None = None) -> str:
133
+ """Create a mailbox. If no password is given, a strong one is generated and returned.
134
+
135
+ The password is passed over stdin, never on the command line.
136
+ """
137
+ address = _email(address)
138
+ generated = password is None
139
+ pw = password or _gen_password()
140
+ out = _setup("email", "add", address, stdin=pw + "\n")
141
+ return f"{out}\nGenerated password for {address}: {pw}" if generated else out
142
+
143
+
144
+ @mcp.tool(annotations=WRITE)
145
+ def update_password(address: str, password: str | None = None) -> str:
146
+ """Change a mailbox password. If none is given, a strong one is generated and returned."""
147
+ address = _email(address)
148
+ generated = password is None
149
+ pw = password or _gen_password()
150
+ out = _setup("email", "update", address, stdin=pw + "\n")
151
+ return f"{out}\nNew password for {address}: {pw}" if generated else out
152
+
153
+
154
+ @mcp.tool(annotations=DESTRUCTIVE)
155
+ def delete_account(address: str, delete_mail: bool = False) -> str:
156
+ """Delete a mailbox account.
157
+
158
+ delete_mail=False keeps the stored mail on disk; True removes it permanently.
159
+ """
160
+ address = _email(address)
161
+ # -y skips the "delete mail data?" prompt and deletes it; without -y we answer "n".
162
+ if delete_mail:
163
+ return _setup("email", "del", "-y", address)
164
+ return _setup("email", "del", address, stdin="n\n")
165
+
166
+
167
+ @mcp.tool(annotations=READ)
168
+ def list_restrictions(direction: str) -> str:
169
+ """List addresses blocked from sending or receiving. direction: 'send' or 'receive'."""
170
+ if direction not in ("send", "receive"):
171
+ raise ValueError("direction must be 'send' or 'receive'")
172
+ return _setup("email", "restrict", "list", direction)
173
+
174
+
175
+ @mcp.tool(annotations=WRITE)
176
+ def restrict_account(address: str, direction: str, restrict: bool = True) -> str:
177
+ """Block (restrict=True) or unblock (restrict=False) an address from sending or receiving.
178
+
179
+ direction: 'send' or 'receive'.
180
+ """
181
+ if direction not in ("send", "receive"):
182
+ raise ValueError("direction must be 'send' or 'receive'")
183
+ return _setup("email", "restrict", "add" if restrict else "del", direction, _email(address))
184
+
185
+
186
+ # --------------------------------------------------------------------------- aliases
187
+
188
+
189
+ @mcp.tool(annotations=READ)
190
+ def list_aliases() -> str:
191
+ """List all aliases and their recipients."""
192
+ return _setup("alias", "list")
193
+
194
+
195
+ @mcp.tool(annotations=WRITE)
196
+ def add_alias(alias: str, recipient: str) -> str:
197
+ """Forward `alias` (address, or @domain for a catch-all) to `recipient`."""
198
+ return _setup("alias", "add", _alias_or_email(alias), _email(recipient, "recipient"))
199
+
200
+
201
+ @mcp.tool(annotations=DESTRUCTIVE)
202
+ def delete_alias(alias: str, recipient: str) -> str:
203
+ """Remove `recipient` from `alias`."""
204
+ return _setup("alias", "del", _alias_or_email(alias), _email(recipient, "recipient"))
205
+
206
+
207
+ # --------------------------------------------------------------------------- quotas
208
+
209
+
210
+ @mcp.tool(annotations=WRITE)
211
+ def set_quota(address: str, quota: str) -> str:
212
+ """Set a mailbox quota, e.g. '500M', '2G' or '0' for unlimited."""
213
+ quota = quota.strip()
214
+ if not _QUOTA.match(quota):
215
+ raise ValueError("quota must look like 500M, 2G, 0 ...")
216
+ return _setup("quota", "set", _email(address), quota)
217
+
218
+
219
+ @mcp.tool(annotations=WRITE)
220
+ def delete_quota(address: str) -> str:
221
+ """Remove a mailbox's custom quota (falls back to the server default)."""
222
+ return _setup("quota", "del", _email(address))
223
+
224
+
225
+ # --------------------------------------------------------------------------- DKIM
226
+
227
+
228
+ @mcp.tool(annotations=WRITE)
229
+ def generate_dkim(domain: str | None = None, selector: str = "mail", keysize: int = 2048) -> str:
230
+ """Generate DKIM keys (all domains if none given). Prints the DNS TXT record to publish.
231
+
232
+ The mail server usually needs a restart to start signing with new keys.
233
+ """
234
+ if keysize not in (1024, 2048, 4096):
235
+ raise ValueError("keysize must be 1024, 2048 or 4096")
236
+ if not _SELECTOR.match(selector):
237
+ raise ValueError("invalid selector")
238
+ args = ["config", "dkim", "keysize", str(keysize), "selector", selector]
239
+ if domain:
240
+ args += ["domain", _domain(domain)]
241
+ return _setup(*args)
242
+
243
+
244
+ @mcp.tool(annotations=READ)
245
+ def show_dkim_record(domain: str, selector: str = "mail") -> str:
246
+ """Show the DKIM public-key DNS record for a domain (OpenDKIM/Rspamd default paths)."""
247
+ domain = _domain(domain)
248
+ if not _SELECTOR.match(selector):
249
+ raise ValueError("invalid selector")
250
+ paths = [
251
+ f"/tmp/docker-mailserver/opendkim/keys/{domain}/{selector}.txt",
252
+ f"/tmp/docker-mailserver/rspamd/dkim/rsa-2048-{selector}-{domain}.public.dns.txt",
253
+ f"/tmp/docker-mailserver/rspamd/dkim/rsa-4096-{selector}-{domain}.public.dns.txt",
254
+ f"/tmp/docker-mailserver/rspamd/dkim/rsa-1024-{selector}-{domain}.public.dns.txt",
255
+ ]
256
+ for p in paths:
257
+ try:
258
+ return f"{p}:\n" + _run(["cat", p])
259
+ except RuntimeError:
260
+ continue
261
+ raise RuntimeError(f"No DKIM record found for {domain} (selector {selector}). Run generate_dkim first.")
262
+
263
+
264
+ # --------------------------------------------------------------------------- fail2ban
265
+
266
+
267
+ @mcp.tool(annotations=READ)
268
+ def fail2ban_status() -> str:
269
+ """Show currently banned IPs per jail."""
270
+ return _setup("fail2ban")
271
+
272
+
273
+ @mcp.tool(annotations=WRITE)
274
+ def fail2ban_ban(ip: str) -> str:
275
+ """Ban an IP address or CIDR range."""
276
+ return _setup("fail2ban", "ban", _ip(ip))
277
+
278
+
279
+ @mcp.tool(annotations=WRITE)
280
+ def fail2ban_unban(ip: str) -> str:
281
+ """Unban an IP address or CIDR range."""
282
+ return _setup("fail2ban", "unban", _ip(ip))
283
+
284
+
285
+ # --------------------------------------------------------------------------- logs / health
286
+
287
+
288
+ @mcp.tool(annotations=READ)
289
+ def mail_log(lines: int = 100, grep: str | None = None) -> str:
290
+ """Tail the mail log (Postfix/Dovecot). Optionally filter with a fixed string (case-insensitive)."""
291
+ lines = max(1, min(int(lines), 2000))
292
+ if grep:
293
+ # Search further back when filtering, then return the last N matches.
294
+ out = _run(["tail", "-n", "20000", "/var/log/mail/mail.log"])
295
+ matches = [l for l in out.splitlines() if grep.lower() in l.lower()]
296
+ return "\n".join(matches[-lines:]) or f"No lines matching {grep!r}"
297
+ return _run(["tail", "-n", str(lines), "/var/log/mail/mail.log"])
298
+
299
+
300
+ @mcp.tool(annotations=READ)
301
+ def mail_queue() -> str:
302
+ """Show the Postfix mail queue (deferred/held messages)."""
303
+ return _run(["postqueue", "-p"])
304
+
305
+
306
+ @mcp.tool(annotations=WRITE)
307
+ def flush_queue() -> str:
308
+ """Retry delivery of all queued messages now."""
309
+ return _run(["postqueue", "-f"])
310
+
311
+
312
+ @mcp.tool(annotations=READ)
313
+ def server_status() -> str:
314
+ """Check that the container is reachable and show service status."""
315
+ return _run(["supervisorctl", "status"])
316
+
317
+
318
+ def main() -> None:
319
+ import argparse
320
+
321
+ from dms_mcp import __version__
322
+
323
+ parser = argparse.ArgumentParser(prog="dms-mcp", description=__doc__.split("\n\n")[0])
324
+ parser.add_argument("--version", action="version", version=f"dms-mcp {__version__}")
325
+ parser.parse_args()
326
+ mcp.run()
327
+
328
+
329
+ if __name__ == "__main__":
330
+ main()
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env bash
2
+ # Stub for `docker`: records argv and stdin, mimics a little setup output.
3
+ log="${FAKE_LOG:-/tmp/fake_docker.log}"
4
+ stdin=""; if [ ! -t 0 ]; then stdin="$(cat)"; fi
5
+ printf 'ARGV:%s\nSTDIN:%s\n' "$*" "$stdin" >> "$log"
6
+ case "$*" in
7
+ *"setup email list"*) echo "* alice@example.com ( 1M / 500M ) [0%]";;
8
+ *"setup email add"*) printf 'Enter Password: \n';;
9
+ *"fail2ban ban"*) echo "Banned";;
10
+ *"cat /tmp/docker-mailserver/opendkim"*) echo "nope" >&2; exit 1;;
11
+ *"cat /tmp/docker-mailserver/rspamd/dkim/rsa-2048"*) echo 'mail._domainkey IN TXT "v=DKIM1; p=ABC"';;
12
+ *"tail"*) printf 'postfix/smtp: to=<a@x.com> status=sent\npostfix/smtp: status=bounced\n';;
13
+ *"boom"*) echo "error!" >&2; exit 3;;
14
+ esac
@@ -0,0 +1,68 @@
1
+ import asyncio, os, sys, tempfile
2
+ from pathlib import Path
3
+ HERE = Path(__file__).parent
4
+ LOG = Path(tempfile.mkdtemp()) / "log"
5
+ os.environ.update(DMS_DOCKER_BIN=str(HERE / "fake_docker.sh"), FAKE_LOG=str(LOG), DMS_CONTAINER="mail")
6
+ from dms_mcp import server as s
7
+
8
+ def last(): return LOG.read_text().strip().splitlines()[-2:]
9
+
10
+ def check(cond, msg):
11
+ print(("PASS " if cond else "FAIL ") + msg); assert cond, msg
12
+
13
+ check("alice@example.com" in s.list_accounts(), "list_accounts output")
14
+ out = s.add_account("bob@example.com")
15
+ argv, stdin = last()
16
+ check(argv == "ARGV:exec -i mail setup email add bob@example.com", "add_account argv has no password")
17
+ pw = out.rsplit(": ", 1)[1]
18
+ check(stdin == f"STDIN:{pw}" and len(pw) == 24, "generated password piped via stdin")
19
+ check("Enter Password" not in out, "prompt stripped")
20
+ s.update_password("bob@example.com", "S3cret pw")
21
+ check(last() == ["ARGV:exec -i mail setup email update bob@example.com", "STDIN:S3cret pw"], "update_password via stdin")
22
+ s.delete_account("bob@example.com")
23
+ check(last() == ["ARGV:exec -i mail setup email del bob@example.com", "STDIN:n"], "delete keeps mail")
24
+ s.delete_account("bob@example.com", delete_mail=True)
25
+ check(last()[0] == "ARGV:exec -i mail setup email del -y bob@example.com", "delete -y")
26
+ s.add_alias("@example.com", "alice@example.com")
27
+ check(last()[0] == "ARGV:exec -i mail setup alias add @example.com alice@example.com", "catch-all alias")
28
+ s.set_quota("alice@example.com", "2G")
29
+ check(last()[0] == "ARGV:exec -i mail setup quota set alice@example.com 2G", "quota")
30
+ s.restrict_account("alice@example.com", "send")
31
+ check(last()[0] == "ARGV:exec -i mail setup email restrict add send alice@example.com", "restrict")
32
+ s.generate_dkim("example.com")
33
+ check(last()[0] == "ARGV:exec -i mail setup config dkim keysize 2048 selector mail domain example.com", "dkim")
34
+ check("p=ABC" in s.show_dkim_record("example.com"), "dkim record fallback path")
35
+ check(s.fail2ban_ban("203.0.113.0/24") == "Banned", "fail2ban ban")
36
+ check(s.mail_log(grep="BOUNCED") == "postfix/smtp: status=bounced", "mail_log grep")
37
+
38
+ for bad in [lambda: s.add_account("x; rm -rf /"), lambda: s.fail2ban_ban("1.2.3.4; id"),
39
+ lambda: s.set_quota("a@b.co", "1G && id"), lambda: s.add_alias("$(id)@x.com", "a@b.co"),
40
+ lambda: s.generate_dkim(selector="a b")]:
41
+ try: bad(); check(False, "rejected bad input")
42
+ except ValueError: pass
43
+ print("PASS injection inputs rejected")
44
+
45
+ try: s._run(["boom"]); check(False, "error raised")
46
+ except RuntimeError as e: check("exit 3" in str(e) and "error!" in str(e), "non-zero exit surfaces stderr")
47
+
48
+ # SSH mode quoting
49
+ s.SSH_HOST = "admin@mail.example.com"
50
+ cmd = s._build_cmd(["setup", "alias", "add", "a@b.co", "c@d.co"])
51
+ check(cmd[:5] == ["ssh", "-o", "BatchMode=yes", "admin@mail.example.com", "--"] and cmd[5].endswith("setup alias add a@b.co c@d.co"), "ssh command")
52
+ s.SSH_HOST = ""
53
+
54
+ # MCP protocol: list tools over stdio
55
+ from mcp import ClientSession, StdioServerParameters
56
+ from mcp.client.stdio import stdio_client
57
+ async def proto():
58
+ params = StdioServerParameters(command=sys.executable, args=["-m", "dms_mcp"], env=dict(os.environ))
59
+ async with stdio_client(params) as (r, w):
60
+ async with ClientSession(r, w) as sess:
61
+ await sess.initialize()
62
+ tools = (await sess.list_tools()).tools
63
+ res = await sess.call_tool("list_accounts", {})
64
+ return [t.name for t in tools], res.content[0].text
65
+ names, text = asyncio.run(proto())
66
+ check(len(names) == 20 and "add_account" in names, f"MCP lists {len(names)} tools")
67
+ check("alice@example.com" in text, "MCP call_tool works end-to-end")
68
+ print("ALL PASSED")