pindrift 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.
pindrift/__init__.py ADDED
@@ -0,0 +1,6 @@
1
+ """pindrift - continuous drift monitoring for MCP servers and agent skills."""
2
+
3
+ from __future__ import annotations
4
+
5
+ __version__ = "0.1.0"
6
+ __all__ = ["__version__"]
pindrift/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ sys.exit(main())
pindrift/capability.py ADDED
@@ -0,0 +1,337 @@
1
+ """Capability inference.
2
+
3
+ The point of this module is to answer a question that a plain text diff cannot:
4
+ *what can this tool now do that it could not do before?*
5
+
6
+ A five-line description edit that turns a read-only file viewer into something that
7
+ writes files and reads ``~/.ssh`` is a far more serious event than a fifty-line
8
+ refactor. Diff size is a bad proxy for risk; capability delta is a good one.
9
+
10
+ Inference is heuristic by construction. Every facet carries the evidence that
11
+ triggered it so a human can audit the call rather than trust it.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+ from collections.abc import Iterable
18
+ from dataclasses import dataclass, field
19
+
20
+ from .models import Severity, ToolManifest
21
+
22
+ # Threshold on the weighted score before a facet is considered present.
23
+ # Tool-name matches weigh 3, descriptive phrase matches weigh 2 when the phrase is
24
+ # specific (multi-word, underscored, or a CJK term), 1 when it is a single generic
25
+ # word, and schema parameter names weigh 1.
26
+ ACTIVATION_THRESHOLD = 2
27
+
28
+ NAME_WEIGHT = 3
29
+ STRONG_DESCRIPTION_WEIGHT = 2
30
+ WEAK_DESCRIPTION_WEIGHT = 1
31
+ SCHEMA_WEIGHT = 1
32
+
33
+
34
+ def _is_specific(phrase: str) -> bool:
35
+ """A phrase is specific if it is unlikely to appear by accident.
36
+
37
+ Single English words like ``overwrite`` fire on unrelated descriptions; phrases
38
+ like ``write file`` or ``读取文件`` do not. Only the latter earn the higher weight.
39
+ """
40
+ if " " in phrase or "_" in phrase:
41
+ return True
42
+ return len(phrase) >= 3 and any(ord(char) > 0x2E80 for char in phrase)
43
+
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Facet:
48
+ name: str
49
+ risk: Severity
50
+ label: str
51
+ phrases: tuple[str, ...]
52
+ schema_keys: tuple[str, ...] = ()
53
+
54
+
55
+ FACETS: tuple[Facet, ...] = (
56
+ Facet(
57
+ name="exec.shell",
58
+ risk=Severity.CRITICAL,
59
+ label="execute shell commands",
60
+ phrases=(
61
+ "shell command", "shell_command", "shell script", "shell_script", "bash script",
62
+ "run command", "run_command", "run a command", "run the command",
63
+ "execute command", "execute a command", "execute the command", "execute shell",
64
+ "system shell", "powershell", "subprocess", "cmd.exe", "command line",
65
+ "terminal", "执行命令", "运行命令", "命令行", "终端", "脚本执行",
66
+ ),
67
+ schema_keys=("command", "cmd", "script", "shell"),
68
+ ),
69
+ Facet(
70
+ name="cred.read",
71
+ risk=Severity.CRITICAL,
72
+ label="read credentials or secrets",
73
+ phrases=(
74
+ "environment variable", "env var", "credential", "credentials", "credential store",
75
+ "api key", "api_key", "apikey", "access token", "access key", "secret key",
76
+ "secret value", "secret manager", "private key", "keychain", "stored password",
77
+ "password store", "password manager", "look up a password", "look up the password",
78
+ "retrieve a password", "retrieve the password", "get the password",
79
+ "read the password", "show the password", ".env", "ssh key",
80
+ "密钥", "凭据", "凭证", "环境变量", "访问令牌",
81
+ ),
82
+ schema_keys=("token", "api_key", "apikey", "secret", "credential"),
83
+ ),
84
+ Facet(
85
+ name="cloud.control",
86
+ risk=Severity.CRITICAL,
87
+ label="control cloud or cluster resources",
88
+ phrases=(
89
+ "amazon web services", "aws s3", "aws_s3", "amazon s3", "s3 bucket", "aws lambda",
90
+ "aws_lambda", "aws ec2", "aws_ec2", "ec2 instance", "aws iam", "iam role",
91
+ "iam policy", "iam user", "google cloud", "gcp_", "compute instance", "azure_",
92
+ "virtual machine", "kubernetes cluster", "k8s cluster", "kubectl", "helm",
93
+ "terraform", "cloudformation", "cloud resource",
94
+ "云服务", "集群", "容器编排",
95
+ ),
96
+ schema_keys=("instance", "bucket", "cluster", "namespace"),
97
+ ),
98
+ Facet(
99
+ name="fs.write",
100
+ risk=Severity.HIGH,
101
+ label="write or modify files",
102
+ phrases=(
103
+ "write file", "write_file", "writefile", "write a file", "write to a file",
104
+ "write to file", "write the file", "writes the file", "create file", "create_file",
105
+ "create a file", "create a new file", "save file", "save the file", "save to disk",
106
+ "edit file", "edit_file", "modify file", "modify the file", "update the file",
107
+ "append to", "append text", "append content", "overwrite", "overwrite the file",
108
+ "patch file", "apply patch", "apply a patch", "create directory", "create a directory",
109
+ "mkdir", "写入文件", "保存文件", "修改文件", "创建文件", "覆盖写入",
110
+ ),
111
+ schema_keys=("content", "new_content", "new_string", "text"),
112
+ ),
113
+ Facet(
114
+ name="fs.delete",
115
+ risk=Severity.HIGH,
116
+ label="delete files or directories",
117
+ phrases=(
118
+ "delete file", "delete_file", "delete a file", "delete the file", "remove file",
119
+ "remove_file", "remove a file", "remove files", "remove the file", "delete directory",
120
+ "delete_directory", "delete a directory", "remove directory", "remove_directory",
121
+ "remove a directory", "unlink", "rm -rf", "rmdir",
122
+ "删除文件", "删除目录", "移除",
123
+ ),
124
+ schema_keys=("delete", "force", "recursive"),
125
+ ),
126
+ Facet(
127
+ name="db.write",
128
+ risk=Severity.HIGH,
129
+ label="modify database state",
130
+ phrases=(
131
+ "insert into", "insert a row", "insert row", "insert_row", "insert_record",
132
+ "update record", "update_record", "update a record", "update the record",
133
+ "update a row", "delete from", "delete_from", "delete row", "delete a row",
134
+ "delete record", "execute sql", "execute_sql", "run sql", "run_sql", "write query",
135
+ "sql statement", "alter table", "create table", "drop table", "truncate table",
136
+ "database migration", "schema migration",
137
+ "数据库", "写入表", "更新记录",
138
+ ),
139
+ schema_keys=("sql", "statement", "query"),
140
+ ),
141
+ Facet(
142
+ name="repo.push",
143
+ risk=Severity.HIGH,
144
+ label="push code or change repositories",
145
+ phrases=(
146
+ "git push", "git_push", "push commit", "push commits", "push local commits",
147
+ "push changes", "push the changes", "git commit", "git_commit", "create commit",
148
+ "commit changes",
149
+ "merge branch", "merge_branch", "merge pull request", "merge_pull_request",
150
+ "create pull request", "create_pull_request", "open a pull request",
151
+ "create branch", "create_branch", "create a branch",
152
+ "推送代码", "提交代码", "合并分支",
153
+ ),
154
+ schema_keys=("branch", "commit_message", "pull_number"),
155
+ ),
156
+ Facet(
157
+ name="ci.trigger",
158
+ risk=Severity.HIGH,
159
+ label="trigger deployments or pipelines",
160
+ phrases=(
161
+ "deploy to", "deploy the", "deploy a", "deploying", "deployed",
162
+ "deployment pipeline", "release pipeline", "run workflow", "run a workflow",
163
+ "run the workflow", "trigger workflow", "trigger a workflow", "trigger_workflow",
164
+ "actions workflow", "run the ci pipeline", "ci pipeline run", "start a rollout",
165
+ "canary rollout", "rollout to", "rollback", "roll back", "helm upgrade",
166
+ "部署", "发布流程", "触发流水线",
167
+ ),
168
+ schema_keys=("workflow_id",),
169
+ ),
170
+ Facet(
171
+ name="msg.send",
172
+ risk=Severity.HIGH,
173
+ label="send messages or email externally",
174
+ phrases=(
175
+ "send message", "send_message", "send a message", "send the message", "post message",
176
+ "post_message", "post a message", "send email", "send_email", "send an email",
177
+ "send notification", "send a notification", "post notification", "notify user",
178
+ "notify a user", "notify the user", "send webhook", "send a webhook", "post to slack",
179
+ "send to slack",
180
+ "发送消息", "发送邮件", "推送通知",
181
+ ),
182
+ schema_keys=("recipient", "channel"),
183
+ ),
184
+ Facet(
185
+ name="net.listen",
186
+ risk=Severity.HIGH,
187
+ label="listen on the network",
188
+ phrases=(
189
+ "listen on", "listen port", "listen_port", "bind port", "bind a socket", "http server",
190
+ "web server", "start server", "start_server", "start a server", "accept connection",
191
+ "websocket server", "监听端口", "启动服务",
192
+ ),
193
+ schema_keys=("port", "bind"),
194
+ ),
195
+ Facet(
196
+ name="net.egress",
197
+ risk=Severity.MEDIUM,
198
+ label="make outbound network requests",
199
+ phrases=(
200
+ "http request", "http get", "http post", "https request", "make an http request",
201
+ "fetch url", "fetch_url", "fetch a url", "api call", "api_call", "call an api",
202
+ "rest api", "external api", "web request", "download file", "download a file",
203
+ "download_file", "upload file", "upload a file", "upload_file", "web search",
204
+ "search the web", "curl", "网络请求", "下载文件", "上传文件",
205
+ ),
206
+ schema_keys=("url", "uri", "endpoint", "host", "domain"),
207
+ ),
208
+ Facet(
209
+ name="browser.control",
210
+ risk=Severity.MEDIUM,
211
+ label="drive a browser",
212
+ phrases=(
213
+ "control a browser", "drive a browser", "browser automation", "headless browser",
214
+ "navigate to", "click element", "click an element", "take screenshot",
215
+ "take a screenshot", "playwright", "puppeteer", "selenium",
216
+ "浏览器", "截图", "点击元素",
217
+ ),
218
+ schema_keys=("selector", "screenshot", "tab_id"),
219
+ ),
220
+ Facet(
221
+ name="clipboard",
222
+ risk=Severity.MEDIUM,
223
+ label="read or write the clipboard",
224
+ phrases=(
225
+ "clipboard", "copy to clipboard", "copy_to_clipboard", "system clipboard", "paste",
226
+ "剪贴板", "复制粘贴",
227
+ ),
228
+ schema_keys=("clipboard",),
229
+ ),
230
+ Facet(
231
+ name="fs.read",
232
+ risk=Severity.LOW,
233
+ label="read files or directories",
234
+ phrases=(
235
+ "read file", "read_file", "readfile", "read a file", "read the file", "read files",
236
+ "view file", "view a file", "view the file", "open file", "open a file",
237
+ "list directory", "list_directory", "list files", "list the files",
238
+ "directory listing", "show the directory tree", "glob pattern", "file contents",
239
+ "contents of a file", "file metadata",
240
+ "读取文件", "查看文件", "列出目录", "文件内容",
241
+ ),
242
+ schema_keys=("path", "file_path", "directory", "pattern"),
243
+ ),
244
+ )
245
+
246
+ FACET_BY_NAME: dict[str, Facet] = {f.name: f for f in FACETS}
247
+
248
+
249
+ @dataclass
250
+ class CapabilityHit:
251
+ facet: str
252
+ score: int
253
+ evidence: list[str] = field(default_factory=list)
254
+
255
+ @property
256
+ def risk(self) -> Severity:
257
+ return FACET_BY_NAME[self.facet].risk
258
+
259
+ @property
260
+ def label(self) -> str:
261
+ return FACET_BY_NAME[self.facet].label
262
+
263
+
264
+ def _schema_blob(schema: object) -> str:
265
+ if not isinstance(schema, dict):
266
+ return ""
267
+ parts: list[str] = []
268
+ props = schema.get("properties")
269
+ if isinstance(props, dict):
270
+ for key, value in props.items():
271
+ parts.append(str(key))
272
+ if isinstance(value, dict):
273
+ parts.append(str(value.get("description") or ""))
274
+ enum = value.get("enum")
275
+ if isinstance(enum, list):
276
+ parts.extend(str(e) for e in enum)
277
+ elif isinstance(value, str):
278
+ parts.append(value)
279
+ parts.append(str(schema.get("description") or ""))
280
+ return " \n ".join(parts).lower()
281
+
282
+
283
+ def infer_capabilities(tool: ToolManifest) -> dict[str, CapabilityHit]:
284
+ """Infer the capability facets of a single tool.
285
+
286
+ Returns facets that reached :data:`ACTIVATION_THRESHOLD`, with the matched
287
+ phrases recorded as evidence.
288
+ """
289
+ name_blob = tool.name.lower()
290
+ desc_blob = tool.description.lower()
291
+ schema_blob = _schema_blob(tool.input_schema)
292
+
293
+ annotation_blob = " ".join(
294
+ f"{k}={v}" for k, v in sorted(tool.annotations.items())
295
+ ).lower()
296
+
297
+ hits: dict[str, CapabilityHit] = {}
298
+ for facet in FACETS:
299
+ score = 0
300
+ evidence: list[str] = []
301
+ for phrase in facet.phrases:
302
+ weight = (
303
+ STRONG_DESCRIPTION_WEIGHT if _is_specific(phrase) else WEAK_DESCRIPTION_WEIGHT
304
+ )
305
+ if phrase in name_blob:
306
+ score += NAME_WEIGHT
307
+ evidence.append(f"name contains {phrase!r}")
308
+ elif phrase in desc_blob:
309
+ score += weight
310
+ evidence.append(f"description contains {phrase!r}")
311
+ elif phrase in schema_blob:
312
+ score += SCHEMA_WEIGHT
313
+ evidence.append(f"schema contains {phrase!r}")
314
+ for key in facet.schema_keys:
315
+ if re.search(rf"\b{re.escape(key)}\b", schema_blob):
316
+ score += SCHEMA_WEIGHT
317
+ evidence.append(f"schema parameter {key!r}")
318
+
319
+ if facet.name == "fs.delete" and "destructivehint=true" in annotation_blob:
320
+ score += 2
321
+ evidence.append("annotation destructiveHint=true")
322
+ if facet.name in ("fs.write", "db.write") and "readonlyhint=false" in annotation_blob:
323
+ score += 1
324
+ evidence.append("annotation readOnlyHint=false")
325
+
326
+ if score >= ACTIVATION_THRESHOLD:
327
+ hits[facet.name] = CapabilityHit(facet=facet.name, score=score, evidence=evidence[:4])
328
+ return hits
329
+
330
+
331
+ def server_capabilities(tools: Iterable[ToolManifest]) -> dict[str, list[str]]:
332
+ """Map facet name -> sorted tool names that expose it."""
333
+ aggregate: dict[str, list[str]] = {}
334
+ for tool in tools:
335
+ for facet in infer_capabilities(tool):
336
+ aggregate.setdefault(facet, []).append(tool.name)
337
+ return {k: sorted(v) for k, v in sorted(aggregate.items())}