mcp-server-gaussdb-data 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3 @@
1
+ """GaussDB 507 Data MCP server (data plane)."""
2
+
3
+ __version__ = "0.1.0"
@@ -0,0 +1,57 @@
1
+ """审计:继承 core AuditLogger,把 SQL 文本截断从 200 放宽(诊断需要),
2
+ 并附加 HTTP 客户端身份(auth 中间件写入 contextvar)。
3
+
4
+ 双版本兼容(依赖范围 huaweicloud-mcp-core>=1.0,<2):
5
+ - core 1.0.0:``emit(**event)`` kwargs 调用、masking 引擎是私有 ``_masking``;
6
+ - core 1.1.1:``emit(event_dict)`` 位置调用、masking 引擎公开为 ``masking``。
7
+ core 把 ``value[:200]`` 硬编码在方法体内,子类预截断后调 ``super().emit()``
8
+ 会被二次截回 200——因此完整重写 emit,仅放宽 query 键,其余键保持 core 语义
9
+ (200 截断 + masking)。masking 引擎经属性探测获取;两个版本都没有时跳过
10
+ 脱敏(审计记录仍完整落盘,降级安全)。
11
+ """
12
+
13
+ import json
14
+ import sys
15
+ from contextvars import ContextVar
16
+ from datetime import datetime, timezone
17
+ from pathlib import Path
18
+ from typing import Any
19
+
20
+ from huaweicloud_mcp_core.guardrails.audit import AuditLogger
21
+
22
+ client_name: ContextVar[str] = ContextVar("mcp_server_gaussdb_data_client", default="stdio")
23
+
24
+
25
+ class SqlAuditLogger(AuditLogger):
26
+ def __init__(self, file_path: str | None = None, *, sql_trunc: int = 2000) -> None:
27
+ super().__init__(file_path=file_path)
28
+ self.sql_trunc = sql_trunc
29
+
30
+ def emit(self, *args: Any, **event: Any) -> None:
31
+ # 归一两种调用形态:1.1.x 位置传 dict;1.0.0 kwargs 传字段。
32
+ source: dict[str, Any] = args[0] if args else event
33
+ payload: dict[str, Any] = {
34
+ "ts": datetime.now(timezone.utc).isoformat(),
35
+ "event": "tool_call",
36
+ **source,
37
+ "client": client_name.get(),
38
+ }
39
+ params = payload.get("params")
40
+ if isinstance(params, dict):
41
+ trimmed = {
42
+ key: (
43
+ value[: self.sql_trunc]
44
+ if isinstance(value, str) and key == "query"
45
+ else value[:200] if isinstance(value, str) else value
46
+ )
47
+ for key, value in params.items()
48
+ }
49
+ masker = getattr(self, "masking", None) or getattr(self, "_masking", None)
50
+ if masker is not None:
51
+ trimmed = masker.mask(trimmed)
52
+ payload["params"] = trimmed
53
+ line = json.dumps(payload, ensure_ascii=False, separators=(",", ":"))
54
+ sys.stderr.write(line + "\n")
55
+ if self.file_path:
56
+ with Path(self.file_path).open("a", encoding="utf-8") as stream:
57
+ stream.write(line + "\n")
@@ -0,0 +1,70 @@
1
+ """HTTP 传输的 Bearer 鉴权中间件(core 没有的能力——两个 example 都在 0.0.0.0 裸奔)。
2
+
3
+ - tokens 文件每次请求热读(与凭证同款轮换语义)。
4
+ - 常数时间比较(bytes 形式:str 版 compare_digest 遇非 ASCII 会抛 TypeError);
5
+ 失败一律 401 + WWW-Authenticate。
6
+ - tokens 文件不可用(缺失/损坏,如原子替换的中间态)→ 503 + Retry-After: 5,
7
+ 而非异常冒泡成 500;scheme 大小写不敏感(RFC 7235)。
8
+ - stdio 模式不经过本中间件(本地信任边界)。
9
+ """
10
+
11
+ import hmac
12
+ from collections.abc import Awaitable, Callable
13
+ from typing import Any
14
+
15
+ from huaweicloud_mcp_core.errors import McpToolError
16
+
17
+ from .audit import client_name
18
+ from .credentials import load_tokens
19
+
20
+ _WWW_AUTH = (b"www-authenticate", b'Bearer realm="gaussdb-data-mcp"')
21
+ _RETRY_AFTER = (b"retry-after", b"5")
22
+
23
+ # ASGI 三件套(无 starlette 依赖的轻量别名)
24
+ Scope = dict[str, Any]
25
+ Receive = Callable[[], Any]
26
+ Send = Callable[..., Any]
27
+ ASGIApp = Callable[..., Awaitable[None]]
28
+
29
+
30
+ class BearerAuthMiddleware:
31
+ def __init__(self, app: ASGIApp, *, tokens_file: str) -> None:
32
+ self.app = app
33
+ self.tokens_file = tokens_file
34
+
35
+ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
36
+ if scope["type"] != "http":
37
+ await self.app(scope, receive, send)
38
+ return
39
+ header = next(
40
+ (value for key, value in scope.get("headers", []) if key == b"authorization"), b""
41
+ )
42
+ # RFC 7235:认证 scheme 大小写不敏感(bearer 与 Bearer 等价)
43
+ scheme, _, value = header.decode("latin-1").partition(" ")
44
+ token = value.strip().encode("utf-8") if scheme.lower() == "bearer" else b""
45
+ try:
46
+ tokens = load_tokens(self.tokens_file)
47
+ except McpToolError:
48
+ await send(
49
+ {"type": "http.response.start", "status": 503,
50
+ "headers": [_RETRY_AFTER, (b"content-length", b"0")]}
51
+ )
52
+ await send({"type": "http.response.body", "body": b""})
53
+ return
54
+ matched = next(
55
+ (
56
+ name
57
+ for name, value in tokens.items()
58
+ if hmac.compare_digest(value.encode("utf-8"), token)
59
+ ),
60
+ None,
61
+ )
62
+ if matched is None:
63
+ await send(
64
+ {"type": "http.response.start", "status": 401,
65
+ "headers": [_WWW_AUTH, (b"content-length", b"0")]}
66
+ )
67
+ await send({"type": "http.response.body", "body": b""})
68
+ return
69
+ client_name.set(matched)
70
+ await self.app(scope, receive, send)
@@ -0,0 +1,73 @@
1
+ """GAUSSDB_DATA_MCP_* 配置(das-only:唯一传输为 DAS 管控面 HTTPS)。"""
2
+
3
+ import os
4
+ from dataclasses import dataclass
5
+
6
+ from huaweicloud_mcp_core.errors import McpToolError
7
+
8
+
9
+ def _env_bool(name: str, default: bool) -> bool:
10
+ value = os.getenv(name, str(default)).lower()
11
+ if value not in {"true", "false", "1", "0", "yes", "no"}:
12
+ raise McpToolError("MCP_INVALID_ARGS", f"{name} must be true or false.")
13
+ return value in {"true", "1", "yes"}
14
+
15
+
16
+ def _env_int(name: str, default: str) -> int:
17
+ # 裸 int() 对非数字抛 ValueError 裸栈;统一映射为 McpToolError(issue #1)
18
+ raw = os.getenv(name, default)
19
+ try:
20
+ return int(raw)
21
+ except ValueError:
22
+ raise McpToolError("MCP_INVALID_ARGS", f"{name} must be an integer.") from None
23
+
24
+
25
+ def _env_csv(name: str) -> tuple[str, ...]:
26
+ return tuple(item.strip() for item in os.getenv(name, "").split(",") if item.strip())
27
+
28
+
29
+ @dataclass(frozen=True)
30
+ class DataMcpSettings:
31
+ # 安全开关(用户决策:写能力一期可用,但代码级默认值必须安全)
32
+ read_only: bool = True
33
+ enable_ddl: bool = False
34
+ # 文件
35
+ credentials_file: str | None = None
36
+ tokens_file: str | None = None
37
+ guardrails_config_path: str | None = None
38
+ audit_file: str | None = None
39
+ # guardrails 资源保护(传给 core load_rules)
40
+ protected_ids: tuple[str, ...] = ()
41
+ protected_names: tuple[str, ...] = ()
42
+ protected_tags: tuple[str, ...] = ()
43
+ # HTTP 监听(默认回环;非回环 + 无 tokens → 拒绝启动,见 server.py)
44
+ server_host: str = "127.0.0.1"
45
+ server_port: int = 8000
46
+ # 资源限制
47
+ max_rows: int = 200
48
+ max_cell_chars: int = 256
49
+ max_sql_chars: int = 65536
50
+
51
+ @classmethod
52
+ def from_env(cls) -> "DataMcpSettings":
53
+ settings = cls(
54
+ read_only=_env_bool("GAUSSDB_DATA_MCP_READ_ONLY", True),
55
+ enable_ddl=_env_bool("GAUSSDB_DATA_MCP_ENABLE_DDL", False),
56
+ credentials_file=os.getenv("GAUSSDB_DATA_MCP_CREDENTIALS_FILE"),
57
+ tokens_file=os.getenv("GAUSSDB_DATA_MCP_TOKENS_FILE"),
58
+ guardrails_config_path=os.getenv("GAUSSDB_DATA_MCP_GUARDRAILS_CONFIG"),
59
+ audit_file=os.getenv("GAUSSDB_DATA_MCP_AUDIT_FILE"),
60
+ protected_ids=_env_csv("GAUSSDB_DATA_MCP_PROTECTED_IDS"),
61
+ protected_names=_env_csv("GAUSSDB_DATA_MCP_PROTECTED_NAMES"),
62
+ protected_tags=_env_csv("GAUSSDB_DATA_MCP_PROTECTED_TAGS"),
63
+ server_host=os.getenv("MCP_SERVER_HOST", "127.0.0.1"),
64
+ server_port=_env_int("MCP_SERVER_PORT", "8000"),
65
+ max_rows=_env_int("GAUSSDB_DATA_MCP_MAX_ROWS", "200"),
66
+ max_cell_chars=_env_int("GAUSSDB_DATA_MCP_MAX_CELL_CHARS", "256"),
67
+ max_sql_chars=_env_int("GAUSSDB_DATA_MCP_MAX_SQL_CHARS", "65536"),
68
+ )
69
+ if not 1 <= settings.server_port <= 65535:
70
+ raise McpToolError("MCP_INVALID_ARGS", "MCP_SERVER_PORT must be 1..65535.")
71
+ if settings.max_rows < 1:
72
+ raise McpToolError("MCP_INVALID_ARGS", "MAX_ROWS must be >= 1.")
73
+ return settings
@@ -0,0 +1,243 @@
1
+ """数据库凭证与 MCP token 的热轮换读取(对齐 core 的 credentials 模式)。
2
+
3
+ - 每次工具调用都重新读文件(原子替换即可轮换,无需重启)。
4
+ - 文件必须 0600(Windows 跳过权限位检查,与 core 一致)。
5
+ """
6
+
7
+ import contextlib
8
+ import hashlib
9
+ import json
10
+ import os
11
+ import stat
12
+ import tempfile
13
+ from collections.abc import Callable
14
+ from dataclasses import dataclass, field, replace
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from huaweicloud_mcp_core.errors import McpToolError
19
+
20
+ from .config import DataMcpSettings
21
+
22
+ _PRIVATE_HOSTNAMES = {"localhost", "host.docker.internal"}
23
+
24
+ def _read_secret_file(path: str) -> dict[str, Any]:
25
+ try:
26
+ with Path(path).expanduser().open("r", encoding="utf-8") as stream:
27
+ mode = os.fstat(stream.fileno()).st_mode
28
+ if not stat.S_ISREG(mode) or (os.name != "nt" and mode & 0o077):
29
+ raise ValueError("file must be regular with mode 0600 or stricter")
30
+ value = json.load(stream)
31
+ except (OSError, ValueError) as exc:
32
+ raise McpToolError(
33
+ "MCP_CREDENTIAL_ERROR",
34
+ "The hot-reload credential file is unavailable or invalid.",
35
+ hint=f"Atomically replace '{path}' with valid JSON and mode 0600 ({exc}).",
36
+ ) from None
37
+ if not isinstance(value, dict):
38
+ raise McpToolError("MCP_CREDENTIAL_ERROR", "Credential file must be a JSON object.")
39
+ return value
40
+
41
+
42
+ _REGION_ALIAS = {
43
+ "北京四": "cn-north-4", "华北-北京四": "cn-north-4",
44
+ "贵阳一": "cn-southwest-2", "西南-贵阳一": "cn-southwest-2",
45
+ "上海一": "cn-east-3", "华东-上海一": "cn-east-3",
46
+ "上海二": "cn-east-2", "华东-上海二": "cn-east-2",
47
+ "广州": "cn-south-1", "华南-广州": "cn-south-1",
48
+ "广州-友好用户环境": "cn-south-4", "华南-广州-友好用户环境": "cn-south-4",
49
+ "深圳": "cn-south-2", "华南-深圳": "cn-south-2",
50
+ "香港": "ap-southeast-1", "新加坡": "ap-southeast-3",
51
+ "曼谷": "ap-southeast-2", "东京": "ap-southeast-4",
52
+ "首尔": "ap-southeast-5", "莫斯科": "ru-north-4",
53
+ }
54
+
55
+
56
+ def normalize_region(region: str | None) -> str:
57
+ """中文区域名 → region code;未知值原样返回(已是 code 的情况)。"""
58
+ value = (region or "").strip()
59
+ return _REGION_ALIAS.get(value, value)
60
+
61
+
62
+ @dataclass(frozen=True)
63
+ class DbCredentials:
64
+ dbname: str
65
+ user: str
66
+ password: str = field(repr=False)
67
+ fingerprint: str = ""
68
+ # das 轨(SQL over 管控面 HTTPS,survey/07):仅 GAUSSDB_DATA_MCP_DRIVER=das 时使用
69
+ das_connection_id: str = ""
70
+ das_ak: str = field(default="", repr=False)
71
+ das_sk: str = field(default="", repr=False)
72
+ das_project_id: str = ""
73
+ das_region: str = "cn-north-4"
74
+ das_schema: str = "public"
75
+ das_host: str = ""
76
+ instance_id: str = ""
77
+ das_activated: bool = False
78
+
79
+ @classmethod
80
+ def _load_das(
81
+ cls, pick: Callable[[str, Any], Any], settings: DataMcpSettings, instance: str | None
82
+ ) -> "DbCredentials":
83
+ """das 轨 v2:多实例映射(survey/07 §8);兼容 v1 平铺结构。
84
+
85
+ v2 结构:{ak, sk, region, default_instance, instances: {iid: {das_connection_id,
86
+ dbname, schema, user, password, region?}}}。project_id 可省略(das 轨按
87
+ AK/SK+region 自动查询)。connection_id 缺失但条目有 user/password 时允许
88
+ 自动注册(das 轨执行前补注册)。
89
+ """
90
+ secret = _read_secret_file(settings.credentials_file) if settings.credentials_file else {}
91
+ instances = secret.get("instances") if isinstance(secret.get("instances"), dict) else None
92
+
93
+ def env_or(name: str) -> str:
94
+ return os.environ.get(name, "")
95
+
96
+ if instances:
97
+ ak = pick("ak", "") or env_or("GAUSSDB_DATA_MCP_CLOUD_AK")
98
+ sk = pick("sk", "") or env_or("GAUSSDB_DATA_MCP_CLOUD_SK")
99
+ region = (
100
+ normalize_region(pick("region", "") or env_or("GAUSSDB_DATA_MCP_CLOUD_REGION"))
101
+ or "cn-north-4"
102
+ )
103
+ iid = (instance or pick("default_instance", "") or "").strip()
104
+ if not iid:
105
+ if len(instances) == 1:
106
+ iid = next(iter(instances))
107
+ else:
108
+ raise McpToolError(
109
+ "MCP_CREDENTIAL_ERROR",
110
+ "Multiple DAS instances configured; "
111
+ "pass 'instance' or set default_instance.",
112
+ hint=f"Configured instances: {', '.join(sorted(instances))}.",
113
+ )
114
+ entry = instances.get(iid)
115
+ if not isinstance(entry, dict):
116
+ raise McpToolError(
117
+ "MCP_CREDENTIAL_ERROR",
118
+ f"DAS instance '{iid}' is not configured.",
119
+ hint=f"Configured instances: {', '.join(sorted(instances))}.",
120
+ )
121
+ def entry_pick(key: str, default: Any) -> Any:
122
+ value = entry.get(key)
123
+ return str(value) if value is not None else default
124
+ creds = cls(
125
+ instance_id=iid,
126
+ dbname=entry_pick("dbname", "postgres"),
127
+ user=entry_pick("user", ""),
128
+ password=entry_pick("password", ""),
129
+ das_connection_id=entry_pick("das_connection_id", ""),
130
+ das_ak=ak, das_sk=sk,
131
+ das_project_id=pick("project_id", "")
132
+ or env_or("GAUSSDB_DATA_MCP_CLOUD_PROJECT_ID"),
133
+ das_region=normalize_region(entry_pick("region", region)) or region,
134
+ das_schema=entry_pick("schema", "public"),
135
+ das_host=entry_pick("das_host", ""),
136
+ das_activated=bool(entry_pick("activated", False)),
137
+ )
138
+ else:
139
+ creds = cls(
140
+ instance_id=pick("instance_id", "") or "",
141
+ dbname=pick("dbname", "") or "postgres",
142
+ user=pick("user", ""),
143
+ password=pick("password", ""),
144
+ das_connection_id=pick("das_connection_id", "") or "",
145
+ das_ak=pick("ak", "") or env_or("GAUSSDB_DATA_MCP_CLOUD_AK"),
146
+ das_sk=pick("sk", "") or env_or("GAUSSDB_DATA_MCP_CLOUD_SK"),
147
+ das_project_id=pick("project_id", "")
148
+ or env_or("GAUSSDB_DATA_MCP_CLOUD_PROJECT_ID"),
149
+ das_region=normalize_region(
150
+ pick("region", "") or env_or("GAUSSDB_DATA_MCP_CLOUD_REGION")
151
+ ) or "cn-north-4",
152
+ das_schema=pick("schema", "") or "public",
153
+ das_host=pick("das_host", ""),
154
+ das_activated=bool(pick("activated", False)),
155
+ )
156
+ missing = [
157
+ k for k, v in (("ak", creds.das_ak), ("sk", creds.das_sk), ("region", creds.das_region),
158
+ ("password", creds.password))
159
+ if not v
160
+ ]
161
+ if missing:
162
+ raise McpToolError(
163
+ "MCP_CREDENTIAL_ERROR",
164
+ f"Missing DAS credentials: {', '.join(missing)}.",
165
+ hint="Set ak/sk/region in the credentials file "
166
+ "or GAUSSDB_DATA_MCP_CLOUD_* variables.",
167
+ )
168
+ canonical = json.dumps(
169
+ {"conn": creds.das_connection_id, "project": creds.das_project_id,
170
+ "region": creds.das_region, "db": creds.dbname, "schema": creds.das_schema,
171
+ "instance": creds.instance_id},
172
+ sort_keys=True,
173
+ )
174
+ return replace(creds, fingerprint=hashlib.sha256(canonical.encode()).hexdigest()[:16])
175
+
176
+ @classmethod
177
+ def load(cls, settings: DataMcpSettings, instance: str | None = None) -> "DbCredentials":
178
+ secret = _read_secret_file(settings.credentials_file) if settings.credentials_file else {}
179
+
180
+ def pick(file_key: str, env_value: Any) -> Any:
181
+ value = secret.get(file_key)
182
+ return str(value) if value is not None else env_value
183
+
184
+ return cls._load_das(pick, settings, instance)
185
+
186
+
187
+ def save_das_connection(path: str, instance_id: str, connection_id: str,
188
+ dbname: str | None = None, activated: bool | None = None) -> None:
189
+ """把 RegisterDbUser 产物原子写回 credentials.json(v2 instances 结构;0600 保持)。
190
+
191
+ v1 平铺结构遇到时升级为 v2(把平铺 das_connection_id 迁入 instances)。调用方负责
192
+ 处理并发(MCP 单进程内由调用点加锁);每次调用重读文件(与热轮换兼容)。
193
+ """
194
+ secret: dict[str, Any] = {}
195
+ try:
196
+ with open(path, encoding="utf-8") as f:
197
+ secret = json.load(f)
198
+ except FileNotFoundError:
199
+ pass
200
+ if not isinstance(secret.get("instances"), dict):
201
+ legacy_conn = secret.get("das_connection_id")
202
+ secret["instances"] = {}
203
+ if legacy_conn and secret.get("instance_id"):
204
+ secret["instances"][str(secret["instance_id"])] = {"das_connection_id": legacy_conn}
205
+ instances = secret.setdefault("instances", {})
206
+ entry = instances.setdefault(str(instance_id), {})
207
+ entry["das_connection_id"] = str(connection_id)
208
+ if dbname:
209
+ entry["dbname"] = dbname
210
+ if activated is not None:
211
+ entry["activated"] = bool(activated)
212
+ fd, tmp = tempfile.mkstemp(dir=os.path.dirname(os.path.abspath(path)) or ".", suffix=".tmp")
213
+ try:
214
+ with os.fdopen(fd, "w", encoding="utf-8") as f:
215
+ json.dump(secret, f, ensure_ascii=False, indent=1)
216
+ os.chmod(tmp, 0o600)
217
+ os.replace(tmp, path)
218
+ except BaseException:
219
+ with contextlib.suppress(OSError):
220
+ os.unlink(tmp)
221
+ raise
222
+
223
+
224
+ def load_tokens(path: str) -> dict[str, str]:
225
+ """读取 {"tokens": {client: token}};每次调用重读(热轮换)。
226
+
227
+ token 值仅支持 ASCII 可打印字符:HTTP 头是 latin-1/ASCII 语义,非 ASCII 或
228
+ 控制字符在加载层直接拒绝(fail-fast),好过请求期静默 401 或编码歧义。
229
+ """
230
+ value = _read_secret_file(path)
231
+ tokens = value.get("tokens")
232
+ if not isinstance(tokens, dict) or not all(
233
+ isinstance(k, str) and isinstance(v, str) and v for k, v in tokens.items()
234
+ ):
235
+ raise McpToolError("MCP_CREDENTIAL_ERROR", 'tokens.json must be {"tokens": {name: token}}.')
236
+ for name, token in tokens.items():
237
+ if not token.isascii() or not token.isprintable():
238
+ raise McpToolError(
239
+ "MCP_CREDENTIAL_ERROR",
240
+ f"Token '{name}' must be printable ASCII.",
241
+ hint="Generate tokens from [A-Za-z0-9._~-] (RFC 6750 b64token charset).",
242
+ )
243
+ return dict(tokens)