gomami-mcp 0.1.1__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,220 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: gomami-mcp
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: Unofficial MCP server for managing GoMami servers, read-only by default
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/Guoqiang1006/gomami-mcp
|
|
7
|
+
Project-URL: Issues, https://github.com/Guoqiang1006/gomami-mcp/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/Guoqiang1006/gomami-mcp/releases
|
|
9
|
+
Keywords: mcp,model-context-protocol,gomami,vps
|
|
10
|
+
Classifier: Development Status :: 3 - Alpha
|
|
11
|
+
Classifier: Environment :: Console
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Intended Audience :: System Administrators
|
|
14
|
+
Classifier: Operating System :: MacOS
|
|
15
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Description-Content-Type: text/markdown
|
|
23
|
+
License-File: LICENSE
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# GoMami MCP
|
|
27
|
+
|
|
28
|
+
<!-- mcp-name: io.github.Guoqiang1006/gomami-mcp -->
|
|
29
|
+
|
|
30
|
+
[](https://github.com/Guoqiang1006/gomami-mcp/actions/workflows/test.yml)
|
|
31
|
+
[](https://github.com/Guoqiang1006/gomami-mcp/releases)
|
|
32
|
+
[](https://github.com/Guoqiang1006/gomami-mcp/blob/main/pyproject.toml)
|
|
33
|
+
[](https://github.com/Guoqiang1006/gomami-mcp/blob/main/LICENSE)
|
|
34
|
+
|
|
35
|
+
[简体中文](https://github.com/Guoqiang1006/gomami-mcp/blob/main/README.zh-CN.md)
|
|
36
|
+
|
|
37
|
+
Manage your GoMami servers from any AI agent that supports the [Model Context Protocol](https://modelcontextprotocol.io), including Claude Code, Codex, Cursor and VS Code.
|
|
38
|
+
|
|
39
|
+
- **Read-only by default.** Changing a server has to be turned on explicitly.
|
|
40
|
+
- **Runs on your computer.** There is nothing to host, and your token goes only to GoMami.
|
|
41
|
+
- **No third-party Python dependencies.** It covers all 29 operations in the GoMami API reference.
|
|
42
|
+
|
|
43
|
+
> **Not affiliated with GoMami.** This is an independent community project.
|
|
44
|
+
|
|
45
|
+
> **Alpha.** `verify_connection`, `get_account` and `list_servers` have been tested against the live API. All other tools, including every tool that changes a server, have only been tested against a local mock. Try them on a disposable server first.
|
|
46
|
+
|
|
47
|
+
## What you can ask
|
|
48
|
+
|
|
49
|
+
- "List my GoMami servers and show their IP addresses."
|
|
50
|
+
- "When does this server's current traffic period end?"
|
|
51
|
+
- "Show the recent tasks for this server and tell me if any failed."
|
|
52
|
+
- "Which OS templates can I rebuild this server with?"
|
|
53
|
+
|
|
54
|
+
## Supported agents
|
|
55
|
+
|
|
56
|
+
Any agent that can start a local MCP server over stdio should work.
|
|
57
|
+
|
|
58
|
+
| Agent | Status |
|
|
59
|
+
| --- | --- |
|
|
60
|
+
| Claude Code | Tested with the live API |
|
|
61
|
+
| Official MCP Python SDK | Protocol tested |
|
|
62
|
+
| Codex | Should work, not tested yet |
|
|
63
|
+
| Cursor | Should work, not tested yet |
|
|
64
|
+
| VS Code | Should work, not tested yet |
|
|
65
|
+
| Claude Desktop | Should work, not tested yet |
|
|
66
|
+
| DeepSeek Harness | Should work through its MCP client plugin, not tested yet |
|
|
67
|
+
| Web-only agents that need a remote HTTP server | Not supported |
|
|
68
|
+
|
|
69
|
+
If you try it with another agent, please share the result in [Discussions](https://github.com/Guoqiang1006/gomami-mcp/discussions).
|
|
70
|
+
|
|
71
|
+
## Quick start
|
|
72
|
+
|
|
73
|
+
You need macOS or Linux, Python 3.10 or newer, [uv](https://docs.astral.sh/uv/) and a GoMami API token.
|
|
74
|
+
|
|
75
|
+
### 1. Create a token
|
|
76
|
+
|
|
77
|
+
Sign in at `gomami.io` and open [Create API Token](https://gomami.io/createapi.php). The token has full account access and is shown only once.
|
|
78
|
+
|
|
79
|
+
### 2. Save the token
|
|
80
|
+
|
|
81
|
+
Run this command, paste the token (nothing is displayed), then press Enter:
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
(umask 077; mkdir -p ~/.config/gomami-mcp; IFS= read -rs t; printf '%s\n' "$t" > ~/.config/gomami-mcp/token; unset t)
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
### 3. Add the server to your agent
|
|
88
|
+
|
|
89
|
+
Use one of the configurations below, then start a new session.
|
|
90
|
+
|
|
91
|
+
### 4. Check the connection
|
|
92
|
+
|
|
93
|
+
Ask your agent to run `verify_connection`.
|
|
94
|
+
|
|
95
|
+
## Agent configuration
|
|
96
|
+
|
|
97
|
+
Desktop apps may not find `uvx` on their `PATH`. If the server fails to start, replace `uvx` with the full path printed by `command -v uvx`.
|
|
98
|
+
|
|
99
|
+
### Claude Code
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
claude mcp add gomami --scope user -- uvx gomami-mcp@0.1.1
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
### Codex
|
|
106
|
+
|
|
107
|
+
Add this to `~/.codex/config.toml`:
|
|
108
|
+
|
|
109
|
+
```toml
|
|
110
|
+
[mcp_servers.gomami]
|
|
111
|
+
command = "uvx"
|
|
112
|
+
args = ["gomami-mcp@0.1.1"]
|
|
113
|
+
env = { GOMAMI_MCP_ACCESS = "read" }
|
|
114
|
+
startup_timeout_sec = 60
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Cursor
|
|
118
|
+
|
|
119
|
+
Add this to `~/.cursor/mcp.json`:
|
|
120
|
+
|
|
121
|
+
```json
|
|
122
|
+
{
|
|
123
|
+
"mcpServers": {
|
|
124
|
+
"gomami": {
|
|
125
|
+
"type": "stdio",
|
|
126
|
+
"command": "uvx",
|
|
127
|
+
"args": ["gomami-mcp@0.1.1"],
|
|
128
|
+
"env": { "GOMAMI_MCP_ACCESS": "read" }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
### VS Code
|
|
135
|
+
|
|
136
|
+
Add this to `.vscode/mcp.json`:
|
|
137
|
+
|
|
138
|
+
```json
|
|
139
|
+
{
|
|
140
|
+
"servers": {
|
|
141
|
+
"gomami": {
|
|
142
|
+
"type": "stdio",
|
|
143
|
+
"command": "uvx",
|
|
144
|
+
"args": ["gomami-mcp@0.1.1"],
|
|
145
|
+
"env": { "GOMAMI_MCP_ACCESS": "read" }
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Claude Desktop
|
|
152
|
+
|
|
153
|
+
Add this to `claude_desktop_config.json`:
|
|
154
|
+
|
|
155
|
+
```json
|
|
156
|
+
{
|
|
157
|
+
"mcpServers": {
|
|
158
|
+
"gomami": {
|
|
159
|
+
"command": "uvx",
|
|
160
|
+
"args": ["gomami-mcp@0.1.1"],
|
|
161
|
+
"env": { "GOMAMI_MCP_ACCESS": "read" }
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
### Other agents
|
|
168
|
+
|
|
169
|
+
Configure a local stdio server with this command:
|
|
170
|
+
|
|
171
|
+
```bash
|
|
172
|
+
uvx gomami-mcp@0.1.1
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
For DeepSeek Harness, use this command with its `@deepseek-ai/dsh-mcp-client` plugin.
|
|
176
|
+
|
|
177
|
+
## Settings
|
|
178
|
+
|
|
179
|
+
| Environment variable | Default | Purpose |
|
|
180
|
+
| --- | --- | --- |
|
|
181
|
+
| `GOMAMI_MCP_ACCESS` | `read` | Access tier: `read`, `operate` or `full`. Unknown values fall back to `read`. |
|
|
182
|
+
| `GOMAMI_MCP_PROTECTED_SERVERS` | empty | Comma-separated server IDs that can be read but not changed. |
|
|
183
|
+
| `GOMAMI_API_TOKEN` | empty | Token value. Takes priority over `~/.config/gomami-mcp/token`. |
|
|
184
|
+
|
|
185
|
+
## Tools
|
|
186
|
+
|
|
187
|
+
| Tier | Tools |
|
|
188
|
+
| --- | --- |
|
|
189
|
+
| `read` | `verify_connection`, `get_account`, `list_ssh_keys`, `list_servers`, `get_server`, `list_os_templates`, `list_swap_options`, `list_isos`, `list_tasks`, `get_task`, `list_resource_packs`, `get_resource_pack` |
|
|
190
|
+
| `operate` | All of the above, plus `get_vnc_status`, `boot_server`, `restart_server`, `shutdown_server`, `power_off_server`, `rename_server` |
|
|
191
|
+
| `full` | All of the above, plus `rebuild_server`, `reset_server_password`, `toggle_rescue`, `toggle_vnc`, `set_iso`, `set_boot_order`, `update_server_settings`, `add_ssh_key`, `delete_ssh_key`, `create_resource_pack_server`, `delete_resource_pack_server` |
|
|
192
|
+
|
|
193
|
+
## Safety
|
|
194
|
+
|
|
195
|
+
- **Protect production servers.** Add them to `GOMAMI_MCP_PROTECTED_SERVERS`. The MCP server enforces this list in every agent.
|
|
196
|
+
- **Do not rely on approval prompts alone.** Whether an agent asks before running a tool depends on that agent and its settings.
|
|
197
|
+
- **Confirmation text prevents mistakes, not decisions.** Tools that change a server need text such as `REBUILD <server-id>`, but a model can fill it in by itself.
|
|
198
|
+
- **Secrets stay out of the chat.** VNC credentials are hidden, and reset passwords are saved under `~/.config/gomami-mcp/secrets/` with mode `600`.
|
|
199
|
+
- **Write requests are never retried automatically.**
|
|
200
|
+
|
|
201
|
+
See [SECURITY.md](https://github.com/Guoqiang1006/gomami-mcp/blob/main/SECURITY.md) for details and limits.
|
|
202
|
+
|
|
203
|
+
## Known limitations
|
|
204
|
+
|
|
205
|
+
- Windows is not supported.
|
|
206
|
+
- The API reference does not say what value `set_iso` needs to eject an ISO.
|
|
207
|
+
- The API reference describes `GET /server/{id}/vnc` as a toggle, which looks like a typo. It is placed in the `operate` tier to be safe.
|
|
208
|
+
- The API is behind Cloudflare. Blocked requests are reported clearly, and this project does not try to work around them.
|
|
209
|
+
|
|
210
|
+
## Development
|
|
211
|
+
|
|
212
|
+
```bash
|
|
213
|
+
python3 -m unittest discover -s tests -v
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
Tests use a local mock and never contact GoMami.
|
|
217
|
+
|
|
218
|
+
## License
|
|
219
|
+
|
|
220
|
+
[MIT](https://github.com/Guoqiang1006/gomami-mcp/blob/main/LICENSE)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
gomami_mcp.py,sha256=xfSqwdWpW-RpAmu8WkZIROrl2R_Y5kQgzioaKNOH4cA,28141
|
|
2
|
+
gomami_mcp-0.1.1.dist-info/licenses/LICENSE,sha256=SFAVMEMjUC4hzyImt3UdROUTnos044ocFw2s4IBCe3s,1080
|
|
3
|
+
gomami_mcp-0.1.1.dist-info/METADATA,sha256=W9Ml5PgUL0c0LKWRqP1ZoqJUMDlzNnqma6GzoxTIxmc,7914
|
|
4
|
+
gomami_mcp-0.1.1.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
5
|
+
gomami_mcp-0.1.1.dist-info/entry_points.txt,sha256=BdegicjL7kX2TTl0A-60MfDKgtVjKKzwhKtJSVH4sMY,47
|
|
6
|
+
gomami_mcp-0.1.1.dist-info/top_level.txt,sha256=ROpMFb1qnVZP37W28IPSBwRMDkcDgcEoeOnNZdQSVUk,11
|
|
7
|
+
gomami_mcp-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 gomami-mcp contributors
|
|
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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
gomami_mcp
|
gomami_mcp.py
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""Unofficial MCP server for the GoMami customer API. Standard library only."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
import os
|
|
7
|
+
import re
|
|
8
|
+
import stat
|
|
9
|
+
import sys
|
|
10
|
+
import urllib.error
|
|
11
|
+
import urllib.parse
|
|
12
|
+
import urllib.request
|
|
13
|
+
from dataclasses import dataclass, field
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Callable
|
|
16
|
+
|
|
17
|
+
__version__ = "0.1.1"
|
|
18
|
+
|
|
19
|
+
API_BASE = "https://cp.gomami.io/api"
|
|
20
|
+
PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
|
|
21
|
+
TIMEOUT_SECONDS = 30
|
|
22
|
+
MAX_RESPONSE_BYTES = 2 * 1024 * 1024
|
|
23
|
+
REDACTED = "[hidden; view it in the GoMami control panel]"
|
|
24
|
+
SENSITIVE_KEY = re.compile(r"password|passphrase|secret|token|^wss$", re.IGNORECASE)
|
|
25
|
+
TIERS = ("read", "operate", "full")
|
|
26
|
+
SAFE_ID = r"^[A-Za-z0-9_-]{1,64}$"
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
class ToolError(Exception):
|
|
30
|
+
"""A failure the calling model should see as a tool result."""
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
# --- Tool table ------------------------------------------------------------
|
|
34
|
+
|
|
35
|
+
SERVER_ID = {"type": "string", "pattern": SAFE_ID, "description": "Server ID (UUID) from list_servers"}
|
|
36
|
+
RESULTS = {"type": "integer", "minimum": 1, "maximum": 200, "description": "Results per page (default 20, max 200)"}
|
|
37
|
+
PAGE = {"type": "integer", "minimum": 1, "description": "Page number, starting at 1"}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _check_build(args: dict[str, Any]) -> None:
|
|
41
|
+
if args["method"] == "template" and "templateId" not in args:
|
|
42
|
+
raise ToolError("templateId is required when method is template. Use list_os_templates to find one.")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _check_settings(args: dict[str, Any]) -> None:
|
|
46
|
+
if "autoConfiguration" not in args and "bootType" not in args:
|
|
47
|
+
raise ToolError("Provide at least one of autoConfiguration or bootType.")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Tool:
|
|
52
|
+
name: str
|
|
53
|
+
title: str
|
|
54
|
+
description: str
|
|
55
|
+
tier: str
|
|
56
|
+
method: str
|
|
57
|
+
path: str
|
|
58
|
+
props: dict[str, dict[str, Any]] = field(default_factory=dict)
|
|
59
|
+
required: tuple[str, ...] = ()
|
|
60
|
+
query: tuple[str, ...] = ()
|
|
61
|
+
body: tuple[str, ...] = ()
|
|
62
|
+
confirm: str | None = None
|
|
63
|
+
destructive: bool = True
|
|
64
|
+
check: Callable[[dict[str, Any]], None] | None = None
|
|
65
|
+
|
|
66
|
+
@property
|
|
67
|
+
def read_only(self) -> bool:
|
|
68
|
+
return self.tier == "read"
|
|
69
|
+
|
|
70
|
+
def input_schema(self) -> dict[str, Any]:
|
|
71
|
+
props = dict(self.props)
|
|
72
|
+
required = list(self.required)
|
|
73
|
+
if self.confirm:
|
|
74
|
+
props["confirm"] = {
|
|
75
|
+
"type": "string",
|
|
76
|
+
"description": f"Confirmation text. Must exactly match: {self.confirm}",
|
|
77
|
+
}
|
|
78
|
+
required.append("confirm")
|
|
79
|
+
return {"type": "object", "properties": props, "required": required, "additionalProperties": False}
|
|
80
|
+
|
|
81
|
+
def describe(self) -> dict[str, Any]:
|
|
82
|
+
return {
|
|
83
|
+
"name": self.name,
|
|
84
|
+
"title": self.title,
|
|
85
|
+
"description": self.description,
|
|
86
|
+
"inputSchema": self.input_schema(),
|
|
87
|
+
"annotations": {
|
|
88
|
+
"title": self.title,
|
|
89
|
+
"readOnlyHint": self.read_only,
|
|
90
|
+
"destructiveHint": False if self.read_only else self.destructive,
|
|
91
|
+
"idempotentHint": self.read_only,
|
|
92
|
+
"openWorldHint": True,
|
|
93
|
+
},
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def _server_read(name: str, title: str, description: str, suffix: str) -> Tool:
|
|
98
|
+
return Tool(name, title, description, "read", "GET", f"/server/{{serverId}}/{suffix}",
|
|
99
|
+
{"serverId": SERVER_ID}, ("serverId",))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def _power(name: str, title: str, description: str, suffix: str, destructive: bool = True) -> Tool:
|
|
103
|
+
return Tool(name, title, description, "operate", "POST", f"/server/{{serverId}}/{suffix}",
|
|
104
|
+
{"serverId": SERVER_ID}, ("serverId",), confirm="{serverId}", destructive=destructive)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
TOOLS: tuple[Tool, ...] = (
|
|
108
|
+
# Read only.
|
|
109
|
+
Tool("verify_connection", "Verify connection", "Check that the API is reachable and the token is valid.",
|
|
110
|
+
"read", "GET", "/connect"),
|
|
111
|
+
Tool("get_account", "Account", "Read the account name, email address and timezone.", "read", "GET", "/account"),
|
|
112
|
+
Tool("list_ssh_keys", "SSH keys", "List the SSH public keys on the account.", "read", "GET", "/account/sshKeys",
|
|
113
|
+
{"results": RESULTS, "page": PAGE}, query=("results", "page")),
|
|
114
|
+
Tool("list_servers", "Servers", "List the servers on the account.", "read", "GET", "/server",
|
|
115
|
+
{"results": RESULTS, "page": PAGE}, query=("results", "page")),
|
|
116
|
+
Tool("get_server", "Server details",
|
|
117
|
+
"Read a server's configuration, network and traffic period. Set state=true to include its live state.",
|
|
118
|
+
"read", "GET", "/server/{serverId}",
|
|
119
|
+
{"serverId": SERVER_ID, "state": {"type": "boolean", "description": "Include the live server state"}},
|
|
120
|
+
("serverId",), query=("state",)),
|
|
121
|
+
_server_read("list_os_templates", "OS templates", "List the OS templates available for a rebuild.",
|
|
122
|
+
"operatingSystemTemplates"),
|
|
123
|
+
_server_read("list_swap_options", "Swap options", "List the swap sizes available for a rebuild.", "swap"),
|
|
124
|
+
_server_read("list_isos", "ISOs", "List the ISO images available to this server.", "isos"),
|
|
125
|
+
Tool("list_tasks", "Tasks", "List a server's recent tasks.", "read", "GET", "/server/{serverId}/tasks",
|
|
126
|
+
{"serverId": SERVER_ID, "results": {"type": "integer", "minimum": 1, "description": "Results per page"},
|
|
127
|
+
"page": PAGE},
|
|
128
|
+
("serverId",), query=("results", "page")),
|
|
129
|
+
Tool("get_task", "Task details", "Read the status of one task.", "read", "GET", "/server/{serverId}/task/{taskId}",
|
|
130
|
+
{"serverId": SERVER_ID, "taskId": {"type": "string", "pattern": SAFE_ID, "description": "Task ID"}},
|
|
131
|
+
("serverId", "taskId")),
|
|
132
|
+
Tool("list_resource_packs", "Resource packs", "List resource packs and their usage.", "read", "GET", "/resourcePack"),
|
|
133
|
+
Tool("get_resource_pack", "Resource pack details",
|
|
134
|
+
"Read a resource pack's options, including the createId values needed to create a server.",
|
|
135
|
+
"read", "GET", "/resourcePack/{resourcePackId}",
|
|
136
|
+
{"resourcePackId": {"type": "integer", "minimum": 1, "description": "Resource pack ID"}},
|
|
137
|
+
("resourcePackId",)),
|
|
138
|
+
|
|
139
|
+
# Day-to-day operations.
|
|
140
|
+
Tool("get_vnc_status", "VNC status",
|
|
141
|
+
"Read whether VNC is enabled, with its address and port. The password and connection token are hidden.",
|
|
142
|
+
"operate", "GET", "/server/{serverId}/vnc", {"serverId": SERVER_ID}, ("serverId",), destructive=False),
|
|
143
|
+
_power("boot_server", "Boot server", "Start the server.", "boot", destructive=False),
|
|
144
|
+
_power("restart_server", "Restart server", "Restart the server. Running services are briefly interrupted.", "restart"),
|
|
145
|
+
_power("shutdown_server", "Shut down server", "Shut the server down cleanly. Services stay down until it is booted.",
|
|
146
|
+
"shutdown"),
|
|
147
|
+
_power("power_off_server", "Power off server", "Cut power immediately. Data not yet written to disk may be lost.",
|
|
148
|
+
"powerOff"),
|
|
149
|
+
Tool("rename_server", "Rename server", "Change the server's display name in the control panel.", "operate", "PUT",
|
|
150
|
+
"/server/{serverId}/name",
|
|
151
|
+
{"serverId": SERVER_ID, "name": {"type": "string", "minLength": 1, "maxLength": 255, "description": "New name"}},
|
|
152
|
+
("serverId", "name"), body=("name",), confirm="{serverId}", destructive=False),
|
|
153
|
+
|
|
154
|
+
# High-risk operations.
|
|
155
|
+
Tool("rebuild_server", "Rebuild server", "Rebuild the server. All data on its disk is permanently erased.", "full",
|
|
156
|
+
"POST", "/server/{serverId}/build",
|
|
157
|
+
{
|
|
158
|
+
"serverId": SERVER_ID,
|
|
159
|
+
"method": {"type": "string", "enum": ["template", "self"], "description": "Install method"},
|
|
160
|
+
"templateId": {"type": "integer", "description": "OS template ID. Required when method is template"},
|
|
161
|
+
"name": {"type": "string", "description": "Server name"},
|
|
162
|
+
"hostname": {"type": "string", "description": "Hostname"},
|
|
163
|
+
"sshKeys": {"type": "array", "items": {"type": "integer"}, "description": "SSH key IDs"},
|
|
164
|
+
"swap": {"type": "integer", "description": "Swap value from list_swap_options"},
|
|
165
|
+
"ipv6": {"type": "boolean", "description": "Enable IPv6"},
|
|
166
|
+
"timezone": {"type": "string", "description": "Timezone, for example America/Los_Angeles"},
|
|
167
|
+
"userData": {"type": "string", "description": "cloud-init user_data"},
|
|
168
|
+
},
|
|
169
|
+
("serverId", "method"),
|
|
170
|
+
body=("method", "templateId", "name", "hostname", "sshKeys", "swap", "ipv6", "timezone", "userData"),
|
|
171
|
+
confirm="REBUILD {serverId}", check=_check_build),
|
|
172
|
+
Tool("reset_server_password", "Reset server password",
|
|
173
|
+
"Reset the server's login password. The new password is saved to a private local file, not returned to the chat.",
|
|
174
|
+
"full", "POST", "/server/{serverId}/resetPassword", {"serverId": SERVER_ID}, ("serverId",),
|
|
175
|
+
confirm="RESET_PASSWORD {serverId}"),
|
|
176
|
+
Tool("toggle_rescue", "Toggle rescue mode", "Turn rescue mode on or off. This changes the server's running state.",
|
|
177
|
+
"full", "POST", "/server/{serverId}/rescue", {"serverId": SERVER_ID}, ("serverId",),
|
|
178
|
+
confirm="RESCUE {serverId}"),
|
|
179
|
+
Tool("toggle_vnc", "Toggle VNC", "Turn the VNC console on or off. When on, the console is reachable over the network.",
|
|
180
|
+
"full", "POST", "/server/{serverId}/vnc", {"serverId": SERVER_ID}, ("serverId",), confirm="VNC {serverId}"),
|
|
181
|
+
Tool("set_iso", "Insert or eject ISO",
|
|
182
|
+
"Change ISO media by ISO ID or remote URL. The API reference does not say what value ejects an ISO.",
|
|
183
|
+
"full", "POST", "/server/{serverId}/iso",
|
|
184
|
+
{"serverId": SERVER_ID, "iso": {"type": "string", "minLength": 1, "description": "ISO ID or remote ISO URL"}},
|
|
185
|
+
("serverId", "iso"), body=("iso",), confirm="ISO {serverId}"),
|
|
186
|
+
Tool("set_boot_order", "Set boot order", "Set the disk and CD-ROM boot order.", "full", "POST",
|
|
187
|
+
"/server/{serverId}/bootOrder",
|
|
188
|
+
{"serverId": SERVER_ID,
|
|
189
|
+
"order": {"type": "string", "enum": ["hdd,cdrom", "cdrom,hdd"], "description": "Boot order"}},
|
|
190
|
+
("serverId", "order"), body=("order",), confirm="BOOT_ORDER {serverId}"),
|
|
191
|
+
Tool("update_server_settings", "Update server settings",
|
|
192
|
+
"Change the boot type or auto-configuration. A wrong value can stop the server from booting.",
|
|
193
|
+
"full", "PUT", "/server/{serverId}/settings",
|
|
194
|
+
{
|
|
195
|
+
"serverId": SERVER_ID,
|
|
196
|
+
"autoConfiguration": {"type": "boolean", "description": "Enable auto-configuration"},
|
|
197
|
+
"bootType": {"type": "string", "enum": ["uefi", "bios"], "description": "Boot type"},
|
|
198
|
+
},
|
|
199
|
+
("serverId",), body=("autoConfiguration", "bootType"), confirm="SETTINGS {serverId}", check=_check_settings),
|
|
200
|
+
Tool("add_ssh_key", "Add SSH key", "Add an SSH public key to the account.", "full", "POST", "/account/sshKeys",
|
|
201
|
+
{
|
|
202
|
+
"name": {"type": "string", "pattern": r"^[^\r\n]{1,100}$", "description": "Key name"},
|
|
203
|
+
"publicKey": {"type": "string", "minLength": 1, "description": "SSH public key"},
|
|
204
|
+
},
|
|
205
|
+
("name", "publicKey"), body=("name", "publicKey"), confirm="ADD_SSH_KEY {name}"),
|
|
206
|
+
Tool("delete_ssh_key", "Delete SSH key", "Delete an SSH public key from the account.", "full", "DELETE",
|
|
207
|
+
"/account/sshKeys/{sshKeyId}",
|
|
208
|
+
{"sshKeyId": {"type": "string", "pattern": SAFE_ID, "description": "SSH key ID"}}, ("sshKeyId",),
|
|
209
|
+
confirm="DELETE_SSH_KEY {sshKeyId}"),
|
|
210
|
+
Tool("create_resource_pack_server", "Create server", "Create a server from a resource pack. This uses pack quota.",
|
|
211
|
+
"full", "POST", "/resourcePack/{resourcePackId}/{createId}",
|
|
212
|
+
{
|
|
213
|
+
"resourcePackId": {"type": "integer", "minimum": 1, "description": "Resource pack ID"},
|
|
214
|
+
"createId": {"type": "string", "pattern": SAFE_ID, "description": "createId from get_resource_pack"},
|
|
215
|
+
"cpuCores": {"type": "integer", "minimum": 1, "description": "CPU cores, for variable plans only"},
|
|
216
|
+
"memory": {"type": "integer", "minimum": 1, "description": "Memory, for variable plans only"},
|
|
217
|
+
"storage": {"type": "integer", "minimum": 1, "description": "Storage, for variable plans only"},
|
|
218
|
+
},
|
|
219
|
+
("resourcePackId", "createId"), body=("cpuCores", "memory", "storage"),
|
|
220
|
+
confirm="CREATE_SERVER {resourcePackId} {createId}"),
|
|
221
|
+
Tool("delete_resource_pack_server", "Delete server",
|
|
222
|
+
"Delete a server created from a resource pack. Its data cannot be recovered.", "full", "DELETE",
|
|
223
|
+
"/resourcePack/{serverId}", {"serverId": SERVER_ID}, ("serverId",), confirm="DELETE_SERVER {serverId}"),
|
|
224
|
+
)
|
|
225
|
+
TOOLS_BY_NAME = {tool.name: tool for tool in TOOLS}
|
|
226
|
+
|
|
227
|
+
|
|
228
|
+
# --- Argument validation ---------------------------------------------------
|
|
229
|
+
|
|
230
|
+
def _matches_type(value: Any, expected: str) -> bool:
|
|
231
|
+
if expected == "integer":
|
|
232
|
+
return isinstance(value, int) and not isinstance(value, bool)
|
|
233
|
+
return isinstance(value, {"string": str, "boolean": bool, "array": list}[expected])
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def _validate_value(name: str, value: Any, schema: dict[str, Any]) -> None:
|
|
237
|
+
if not _matches_type(value, schema["type"]):
|
|
238
|
+
raise ToolError(f"Argument {name} must be of type {schema['type']}.")
|
|
239
|
+
if "enum" in schema and value not in schema["enum"]:
|
|
240
|
+
raise ToolError(f"Argument {name} must be one of: {', '.join(schema['enum'])}.")
|
|
241
|
+
if "minimum" in schema and value < schema["minimum"]:
|
|
242
|
+
raise ToolError(f"Argument {name} must be at least {schema['minimum']}.")
|
|
243
|
+
if "maximum" in schema and value > schema["maximum"]:
|
|
244
|
+
raise ToolError(f"Argument {name} must be at most {schema['maximum']}.")
|
|
245
|
+
if "minLength" in schema and len(value) < schema["minLength"]:
|
|
246
|
+
raise ToolError(f"Argument {name} must not be empty.")
|
|
247
|
+
if "maxLength" in schema and len(value) > schema["maxLength"]:
|
|
248
|
+
raise ToolError(f"Argument {name} is too long.")
|
|
249
|
+
if "pattern" in schema and not re.fullmatch(schema["pattern"].strip("^$"), value):
|
|
250
|
+
raise ToolError(f"Argument {name} has an invalid format.")
|
|
251
|
+
if schema["type"] == "array":
|
|
252
|
+
for item in value:
|
|
253
|
+
_validate_value(f"{name}[]", item, schema["items"])
|
|
254
|
+
|
|
255
|
+
|
|
256
|
+
def validate_arguments(tool: Tool, args: dict[str, Any]) -> None:
|
|
257
|
+
schema = tool.input_schema()
|
|
258
|
+
unknown = sorted(set(args) - set(schema["properties"]))
|
|
259
|
+
if unknown:
|
|
260
|
+
raise ToolError(f"Unsupported arguments: {', '.join(unknown)}.")
|
|
261
|
+
missing = [name for name in schema["required"] if name not in args]
|
|
262
|
+
if missing:
|
|
263
|
+
raise ToolError(f"Missing arguments: {', '.join(missing)}.")
|
|
264
|
+
for name, value in args.items():
|
|
265
|
+
_validate_value(name, value, schema["properties"][name])
|
|
266
|
+
if tool.check:
|
|
267
|
+
tool.check(args)
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
# --- Output handling -------------------------------------------------------
|
|
271
|
+
|
|
272
|
+
def redact(value: Any) -> Any:
|
|
273
|
+
if isinstance(value, dict):
|
|
274
|
+
return {k: REDACTED if SENSITIVE_KEY.search(str(k)) else redact(v) for k, v in value.items()}
|
|
275
|
+
if isinstance(value, list):
|
|
276
|
+
return [redact(item) for item in value]
|
|
277
|
+
return value
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
def save_secret(directory: Path, filename: str, secret: str) -> Path:
|
|
281
|
+
if os.name != "posix":
|
|
282
|
+
raise ToolError("Saving a reset password needs POSIX file permissions, so the request was not sent.")
|
|
283
|
+
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
284
|
+
os.chmod(directory, 0o700)
|
|
285
|
+
path = directory / filename
|
|
286
|
+
fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
|
|
287
|
+
with os.fdopen(fd, "w", encoding="utf-8") as handle:
|
|
288
|
+
os.fchmod(handle.fileno(), 0o600)
|
|
289
|
+
handle.write(secret + "\n")
|
|
290
|
+
return path
|
|
291
|
+
|
|
292
|
+
|
|
293
|
+
# --- HTTP client -----------------------------------------------------------
|
|
294
|
+
|
|
295
|
+
class _NoRedirect(urllib.request.HTTPRedirectHandler):
|
|
296
|
+
"""Never forward the bearer token to another location."""
|
|
297
|
+
|
|
298
|
+
def redirect_request(self, *args: Any, **kwargs: Any) -> None:
|
|
299
|
+
return None
|
|
300
|
+
|
|
301
|
+
|
|
302
|
+
class GomamiClient:
|
|
303
|
+
def __init__(self, token_loader: Callable[[], str], base_url: str = API_BASE):
|
|
304
|
+
self._token_loader = token_loader
|
|
305
|
+
self._base_url = base_url.rstrip("/")
|
|
306
|
+
self._opener = urllib.request.build_opener(_NoRedirect)
|
|
307
|
+
|
|
308
|
+
def request(self, method: str, path: str, query: dict[str, Any], body: dict[str, Any] | None) -> Any:
|
|
309
|
+
url = self._base_url + path
|
|
310
|
+
if query:
|
|
311
|
+
url += "?" + urllib.parse.urlencode(
|
|
312
|
+
{k: str(v).lower() if isinstance(v, bool) else v for k, v in query.items()}
|
|
313
|
+
)
|
|
314
|
+
data = b"" if method in ("POST", "PUT") else None
|
|
315
|
+
if body:
|
|
316
|
+
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
|
317
|
+
request = urllib.request.Request(url, data=data, method=method, headers={
|
|
318
|
+
"Authorization": f"Bearer {self._token_loader()}",
|
|
319
|
+
"Accept": "application/json",
|
|
320
|
+
"Content-Type": "application/json",
|
|
321
|
+
"User-Agent": f"gomami-mcp/{__version__}",
|
|
322
|
+
})
|
|
323
|
+
try:
|
|
324
|
+
with self._opener.open(request, timeout=TIMEOUT_SECONDS) as response:
|
|
325
|
+
return self._parse_success(response.status, response.headers, response.read(MAX_RESPONSE_BYTES + 1))
|
|
326
|
+
except urllib.error.HTTPError as error:
|
|
327
|
+
with error:
|
|
328
|
+
raise ToolError(self._describe_error(error.code, error.headers, error.read(MAX_RESPONSE_BYTES))) from None
|
|
329
|
+
except (urllib.error.URLError, TimeoutError, OSError) as error:
|
|
330
|
+
reason = getattr(error, "reason", error)
|
|
331
|
+
hint = "" if method == "GET" else " The action may have been submitted. Check list_tasks before retrying."
|
|
332
|
+
raise ToolError(f"Could not reach the GoMami API: {reason}.{hint}") from None
|
|
333
|
+
|
|
334
|
+
@staticmethod
|
|
335
|
+
def _parse_success(status: int, headers: Any, raw: bytes) -> Any:
|
|
336
|
+
if len(raw) > MAX_RESPONSE_BYTES:
|
|
337
|
+
raise ToolError("The GoMami API response was too large, so reading stopped.")
|
|
338
|
+
if not raw.strip(): # GET /connect answers 200 with an empty text/html body.
|
|
339
|
+
return {"ok": True, "status": status}
|
|
340
|
+
if "text/html" in (headers.get("Content-Type") or "").lower():
|
|
341
|
+
raise ToolError("The GoMami API returned a web page instead of JSON. Cloudflare may have blocked the request.")
|
|
342
|
+
try:
|
|
343
|
+
return json.loads(raw)
|
|
344
|
+
except ValueError:
|
|
345
|
+
return {"ok": True, "status": status, "body": raw[:500].decode("utf-8", "replace")}
|
|
346
|
+
|
|
347
|
+
@staticmethod
|
|
348
|
+
def _describe_error(status: int, headers: Any, raw: bytes) -> str:
|
|
349
|
+
content_type = (headers.get("Content-Type") or "").lower()
|
|
350
|
+
if headers.get("cf-mitigated") or "text/html" in content_type and status in (403, 429, 503):
|
|
351
|
+
return f"Cloudflare blocked the request (HTTP {status}). This is not a token or argument problem."
|
|
352
|
+
detail = ""
|
|
353
|
+
try:
|
|
354
|
+
errors = json.loads(raw).get("errors")
|
|
355
|
+
if isinstance(errors, list):
|
|
356
|
+
detail = "; ".join(str(item) for item in errors)
|
|
357
|
+
elif errors:
|
|
358
|
+
detail = str(errors)
|
|
359
|
+
except (ValueError, AttributeError):
|
|
360
|
+
pass
|
|
361
|
+
messages = {
|
|
362
|
+
401: "The token is missing, invalid or expired (HTTP 401).",
|
|
363
|
+
404: "The resource does not exist or is not on this account (HTTP 404).",
|
|
364
|
+
409: "The server's current state does not allow this action. A task may be running (HTTP 409).",
|
|
365
|
+
422: "GoMami rejected these arguments (HTTP 422).",
|
|
366
|
+
503: "The GoMami API is temporarily unavailable (HTTP 503).",
|
|
367
|
+
}
|
|
368
|
+
if status == 429:
|
|
369
|
+
message = f"Too many requests (HTTP 429). Limit resets at: {headers.get('X-RateLimit-Reset') or 'unknown'}."
|
|
370
|
+
elif status in (301, 302, 303, 307, 308):
|
|
371
|
+
message = f"The GoMami API returned a redirect (HTTP {status}). It was not followed, to protect the token."
|
|
372
|
+
else:
|
|
373
|
+
message = messages.get(status, f"The GoMami API returned an error (HTTP {status}).")
|
|
374
|
+
return f"{message} {detail}".strip()
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
# --- Token loading ---------------------------------------------------------
|
|
378
|
+
|
|
379
|
+
def load_token(environ: dict[str, str], token_file: Path) -> str:
|
|
380
|
+
token = environ.get("GOMAMI_API_TOKEN", "").strip()
|
|
381
|
+
if not token:
|
|
382
|
+
try:
|
|
383
|
+
mode = token_file.stat().st_mode
|
|
384
|
+
except FileNotFoundError:
|
|
385
|
+
raise ToolError(f"No token configured. Set GOMAMI_API_TOKEN or save the token to {token_file}.") from None
|
|
386
|
+
if os.name == "posix" and stat.S_IMODE(mode) & 0o077:
|
|
387
|
+
raise ToolError(f"The token file is too permissive. Run: chmod 600 {token_file}")
|
|
388
|
+
token = token_file.read_text(encoding="utf-8").strip()
|
|
389
|
+
if not token or re.search(r"\s", token):
|
|
390
|
+
raise ToolError("The token is empty or malformed.")
|
|
391
|
+
return token
|
|
392
|
+
|
|
393
|
+
|
|
394
|
+
# --- Tool execution --------------------------------------------------------
|
|
395
|
+
|
|
396
|
+
class GomamiService:
|
|
397
|
+
def __init__(self, client: GomamiClient, access: str, protected: set[str], config_dir: Path):
|
|
398
|
+
self.client = client
|
|
399
|
+
self.access = access
|
|
400
|
+
self.protected = protected
|
|
401
|
+
self.config_dir = config_dir
|
|
402
|
+
|
|
403
|
+
def enabled(self, tool: Tool) -> bool:
|
|
404
|
+
return TIERS.index(tool.tier) <= TIERS.index(self.access)
|
|
405
|
+
|
|
406
|
+
def list_tools(self) -> list[dict[str, Any]]:
|
|
407
|
+
return [tool.describe() for tool in TOOLS if self.enabled(tool)]
|
|
408
|
+
|
|
409
|
+
def call(self, tool: Tool, args: dict[str, Any]) -> Any:
|
|
410
|
+
if not self.enabled(tool):
|
|
411
|
+
raise ToolError(f"{tool.name} requires GOMAMI_MCP_ACCESS={tool.tier}. Current access: {self.access}.")
|
|
412
|
+
validate_arguments(tool, args)
|
|
413
|
+
if tool.confirm:
|
|
414
|
+
expected = tool.confirm.format(**args)
|
|
415
|
+
if args["confirm"] != expected:
|
|
416
|
+
raise ToolError(f"Confirmation text did not match, so nothing was done. Expected: {expected}")
|
|
417
|
+
server_id = str(args.get("serverId", "")).lower()
|
|
418
|
+
if server_id in self.protected:
|
|
419
|
+
raise ToolError(f"Server {args['serverId']} is in GOMAMI_MCP_PROTECTED_SERVERS. Refused {tool.name}.")
|
|
420
|
+
if tool.name == "reset_server_password" and os.name != "posix":
|
|
421
|
+
raise ToolError("reset_server_password needs POSIX file permissions, so the request was not sent.")
|
|
422
|
+
|
|
423
|
+
path = re.sub(r"\{(\w+)\}", lambda m: urllib.parse.quote(str(args[m.group(1)]), safe=""), tool.path)
|
|
424
|
+
query = {name: args[name] for name in tool.query if name in args}
|
|
425
|
+
body = {name: args[name] for name in tool.body if name in args}
|
|
426
|
+
result = self.client.request(tool.method, path, query, body or None)
|
|
427
|
+
if tool.name == "reset_server_password":
|
|
428
|
+
result = self._store_reset_password(args["serverId"], result)
|
|
429
|
+
return redact(result)
|
|
430
|
+
|
|
431
|
+
def _store_reset_password(self, server_id: str, result: Any) -> Any:
|
|
432
|
+
data = result.get("data") if isinstance(result, dict) else None
|
|
433
|
+
password = data.pop("expectedPassword", None) if isinstance(data, dict) else None
|
|
434
|
+
if isinstance(password, str) and password:
|
|
435
|
+
path = save_secret(self.config_dir / "secrets", f"reset-password-{server_id}.txt", password)
|
|
436
|
+
data["credentialFile"] = str(path)
|
|
437
|
+
return result
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
# --- MCP over stdio --------------------------------------------------------
|
|
441
|
+
|
|
442
|
+
def _text_result(payload: Any, is_error: bool = False) -> dict[str, Any]:
|
|
443
|
+
text = payload if isinstance(payload, str) else json.dumps(payload, ensure_ascii=False, indent=2)
|
|
444
|
+
return {"content": [{"type": "text", "text": text}], "isError": is_error}
|
|
445
|
+
|
|
446
|
+
|
|
447
|
+
class RpcError(Exception):
|
|
448
|
+
def __init__(self, code: int, message: str):
|
|
449
|
+
super().__init__(message)
|
|
450
|
+
self.code = code
|
|
451
|
+
self.message = message
|
|
452
|
+
|
|
453
|
+
|
|
454
|
+
class McpServer:
|
|
455
|
+
def __init__(self, service: GomamiService):
|
|
456
|
+
self.service = service
|
|
457
|
+
|
|
458
|
+
def dispatch(self, method: str, params: dict[str, Any]) -> dict[str, Any]:
|
|
459
|
+
if method == "initialize":
|
|
460
|
+
requested = params.get("protocolVersion")
|
|
461
|
+
return {
|
|
462
|
+
"protocolVersion": requested if requested in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0],
|
|
463
|
+
"capabilities": {"tools": {"listChanged": False}},
|
|
464
|
+
"serverInfo": {"name": "gomami", "title": "GoMami (unofficial)", "version": __version__},
|
|
465
|
+
"instructions": (
|
|
466
|
+
f"Manages GoMami servers. Current access: {self.service.access}. "
|
|
467
|
+
"These servers may run production services. Before any action that changes a server, "
|
|
468
|
+
"explain the impact to the user and get their agreement."
|
|
469
|
+
),
|
|
470
|
+
}
|
|
471
|
+
if method == "ping":
|
|
472
|
+
return {}
|
|
473
|
+
if method == "tools/list":
|
|
474
|
+
return {"tools": self.service.list_tools()}
|
|
475
|
+
if method == "tools/call":
|
|
476
|
+
return self._call_tool(params)
|
|
477
|
+
raise RpcError(-32601, f"Method not found: {method}")
|
|
478
|
+
|
|
479
|
+
def _call_tool(self, params: dict[str, Any]) -> dict[str, Any]:
|
|
480
|
+
tool = TOOLS_BY_NAME.get(params.get("name"))
|
|
481
|
+
args = params.get("arguments", {})
|
|
482
|
+
if tool is None:
|
|
483
|
+
raise RpcError(-32602, f"Unknown tool: {params.get('name')}")
|
|
484
|
+
if not isinstance(args, dict):
|
|
485
|
+
raise RpcError(-32602, "arguments must be an object")
|
|
486
|
+
try:
|
|
487
|
+
return _text_result(self.service.call(tool, args))
|
|
488
|
+
except ToolError as error:
|
|
489
|
+
return _text_result(str(error), is_error=True)
|
|
490
|
+
except OSError as error:
|
|
491
|
+
return _text_result(f"Local file operation failed: {error.strerror or type(error).__name__}", is_error=True)
|
|
492
|
+
|
|
493
|
+
def handle_line(self, line: bytes) -> dict[str, Any] | None:
|
|
494
|
+
try:
|
|
495
|
+
message = json.loads(line.decode("utf-8"))
|
|
496
|
+
except (UnicodeDecodeError, ValueError):
|
|
497
|
+
return {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "Parse error"}}
|
|
498
|
+
if not isinstance(message, dict):
|
|
499
|
+
return {"jsonrpc": "2.0", "id": None, "error": {"code": -32600, "message": "Invalid Request"}}
|
|
500
|
+
method = message.get("method")
|
|
501
|
+
if method is None and ("result" in message or "error" in message):
|
|
502
|
+
return None
|
|
503
|
+
if "id" not in message:
|
|
504
|
+
return None
|
|
505
|
+
request_id = message["id"]
|
|
506
|
+
try:
|
|
507
|
+
params = message.get("params", {})
|
|
508
|
+
if not isinstance(method, str):
|
|
509
|
+
raise RpcError(-32600, "Invalid Request")
|
|
510
|
+
if not isinstance(params, dict):
|
|
511
|
+
raise RpcError(-32602, "params must be an object")
|
|
512
|
+
return {"jsonrpc": "2.0", "id": request_id, "result": self.dispatch(method, params)}
|
|
513
|
+
except RpcError as error:
|
|
514
|
+
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": error.code, "message": error.message}}
|
|
515
|
+
except Exception as error: # Keep the server alive; never echo request data.
|
|
516
|
+
print(f"gomami-mcp: internal error: {type(error).__name__}", file=sys.stderr)
|
|
517
|
+
return {"jsonrpc": "2.0", "id": request_id, "error": {"code": -32603, "message": "Internal error"}}
|
|
518
|
+
|
|
519
|
+
def serve(self, stdin: Any, stdout: Any) -> None:
|
|
520
|
+
for line in stdin:
|
|
521
|
+
if not line.strip():
|
|
522
|
+
continue
|
|
523
|
+
response = self.handle_line(line)
|
|
524
|
+
if response is not None:
|
|
525
|
+
stdout.write(json.dumps(response, ensure_ascii=False).encode("utf-8") + b"\n")
|
|
526
|
+
stdout.flush()
|
|
527
|
+
|
|
528
|
+
|
|
529
|
+
def build_service(environ: dict[str, str]) -> GomamiService:
|
|
530
|
+
access = environ.get("GOMAMI_MCP_ACCESS", "read").strip().lower() or "read"
|
|
531
|
+
if access not in TIERS:
|
|
532
|
+
print("gomami-mcp: unknown GOMAMI_MCP_ACCESS, falling back to read", file=sys.stderr)
|
|
533
|
+
access = "read"
|
|
534
|
+
config_dir = Path.home() / ".config" / "gomami-mcp"
|
|
535
|
+
protected = {item.strip().lower() for item in environ.get("GOMAMI_MCP_PROTECTED_SERVERS", "").split(",") if item.strip()}
|
|
536
|
+
client = GomamiClient(lambda: load_token(environ, config_dir / "token"))
|
|
537
|
+
return GomamiService(client, access, protected, config_dir)
|
|
538
|
+
|
|
539
|
+
|
|
540
|
+
def main() -> None:
|
|
541
|
+
McpServer(build_service(dict(os.environ))).serve(sys.stdin.buffer, sys.stdout.buffer)
|
|
542
|
+
|
|
543
|
+
|
|
544
|
+
if __name__ == "__main__":
|
|
545
|
+
main()
|