pystepmap 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.
- pystepmap-0.1.0.dist-info/METADATA +54 -0
- pystepmap-0.1.0.dist-info/RECORD +26 -0
- pystepmap-0.1.0.dist-info/WHEEL +4 -0
- pystepmap-0.1.0.dist-info/entry_points.txt +2 -0
- pystepmap-0.1.0.dist-info/licenses/LICENSE +21 -0
- pystepmap_server/__init__.py +3 -0
- pystepmap_server/api.py +890 -0
- pystepmap_server/app.py +151 -0
- pystepmap_server/cli.py +138 -0
- pystepmap_server/flows.py +542 -0
- pystepmap_server/live.py +151 -0
- pystepmap_server/locks.py +139 -0
- pystepmap_server/mcp_server.py +216 -0
- pystepmap_server/mcp_tools.py +1901 -0
- pystepmap_server/procinfo.py +61 -0
- pystepmap_server/requirements_view.py +63 -0
- pystepmap_server/runner.py +673 -0
- pystepmap_server/shared.py +198 -0
- pystepmap_server/sources.py +126 -0
- pystepmap_server/status.py +116 -0
- pystepmap_server/store.py +1091 -0
- pystepmap_server/testflows.py +648 -0
- pystepmap_server/web/assets/index-CkPpOJq9.js +1748 -0
- pystepmap_server/web/assets/index-NTWdqvqI.css +1 -0
- pystepmap_server/web/index.html +14 -0
- pystepmap_server/worker.py +303 -0
pystepmap_server/live.py
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
"""运行中的进度:测试命令跑着的时候(运行的阶段 testing),GET /api/projects/{id}/runs 的 running 里多一个 progress,
|
|
2
|
+
让界面边跑边看到跑完了几个测试、正在跑哪个、最近跑完的几个,以及哪些功能线、节点已经走到过。
|
|
3
|
+
|
|
4
|
+
每次运行一个 LiveRun(testflows.run_test_command 在测试命令开始前建、结束后丢,挂在 runner 的运行表上;不入库、不写
|
|
5
|
+
文件)。它读记录插件正在写的记录文件(core 的 pystepmap.progress.TraceProgress:每次只读新追加的部分),按这次运行用的
|
|
6
|
+
那次分析(准备运行时放在临时目录里的图的副本)算:
|
|
7
|
+
- 功能线:每条线涉及的函数(core 的 query.line_functions,同 GET /runs/{id}?line= 和界面的功能线)里有几个执行过;
|
|
8
|
+
- 节点(?live_line=<功能线 sid>):这条线涉及的每个执行过的函数里,哪些节点"走到过"——节点语句头部的行(line 到
|
|
9
|
+
end_line)执行过。开始节点在函数执行过时算。光看执行过的行分不清的不给:捕获节点(except 那一行在异常只是经过、
|
|
10
|
+
没被它接住时也执行)、和别的节点写在同一行的结局(return f(x):f 抛出时这一行也执行过)、行号为 0 的结局(执行到
|
|
11
|
+
函数末尾、未捕获异常退出)。
|
|
12
|
+
图第一次要用时才读(读一次,只留每条线的函数 key 和每个函数可以判断的节点,图本身丢掉);读不了时只给计数。
|
|
13
|
+
读记录文件在一把锁里,最多每秒一次(POLL_EVERY),不管同时来多少个请求:一秒之内的请求用上次读到的。
|
|
14
|
+
插件每个测试结束时才写出执行记录,所以"走到过"说的是已经跑完的测试(加上跨测试结束才结束的执行)。
|
|
15
|
+
|
|
16
|
+
返回给界面的只有标识(测试 id、功能线 sid、函数 key、节点 sid)、计数、秒数、结果种类。
|
|
17
|
+
这里不是流程代码,不加 pystepkit 标记。只有 testflows(建)和 api(经 runner 读)用它;pystepmap mcp、分析子进程都不导入。
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import logging
|
|
23
|
+
import math
|
|
24
|
+
import threading
|
|
25
|
+
import time
|
|
26
|
+
from collections.abc import Callable
|
|
27
|
+
from dataclasses import dataclass
|
|
28
|
+
from pathlib import Path
|
|
29
|
+
|
|
30
|
+
from pystepmap.model import ProjectGraph, from_json
|
|
31
|
+
from pystepmap.progress import TraceProgress
|
|
32
|
+
from pystepmap.query import line_functions
|
|
33
|
+
|
|
34
|
+
logger = logging.getLogger(__name__)
|
|
35
|
+
|
|
36
|
+
POLL_EVERY = 1.0 # 最多每隔几秒读一次记录文件
|
|
37
|
+
RUNNING_SHOWN = 3 # running 里最多列几个正在跑的测试(其余的只给个数)
|
|
38
|
+
_START = "start"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@dataclass(frozen=True)
|
|
42
|
+
class _Graph:
|
|
43
|
+
"""这次运行用的图里要用的那一点:每条功能线涉及的函数 key,每个函数可以判断走没走到的节点。"""
|
|
44
|
+
|
|
45
|
+
lines: dict[str, tuple[str, ...]]
|
|
46
|
+
# 函数 key -> [(节点 sid, 头部的行;开始节点为 None)],按图里节点的顺序
|
|
47
|
+
nodes: dict[str, tuple[tuple[str, range | None], ...]]
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _graph_of(graph: ProjectGraph) -> _Graph:
|
|
51
|
+
lines = {(ln.sid or ln.id): tuple(line_functions(graph, ln)) for ln in graph.lines}
|
|
52
|
+
nodes: dict[str, tuple[tuple[str, range | None], ...]] = {}
|
|
53
|
+
for key, fg in graph.functions.items():
|
|
54
|
+
heads = [range(n.line, max(n.line, n.end_line) + 1) if n.line > 0 else range(0) for n in fg.nodes]
|
|
55
|
+
taken = {ln for n, h in zip(fg.nodes, heads) if n.type != "end" for ln in h}
|
|
56
|
+
out: list[tuple[str, range | None]] = []
|
|
57
|
+
for n, head in zip(fg.nodes, heads):
|
|
58
|
+
if n.type == "start":
|
|
59
|
+
out.append((n.sid or n.id, None))
|
|
60
|
+
elif n.type == "catch" or not head or (n.type == "end" and any(ln in taken for ln in head)):
|
|
61
|
+
continue # 光看执行过的行分不清(见模块说明)
|
|
62
|
+
else:
|
|
63
|
+
out.append((n.sid or n.id, head))
|
|
64
|
+
nodes[key] = tuple(out)
|
|
65
|
+
return _Graph(lines, nodes)
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
class LiveRun:
|
|
69
|
+
"""一次运行的进度。view() 可以从多个线程同时调用。"""
|
|
70
|
+
|
|
71
|
+
def __init__(self, trace_path: Path, graph_path: Path, *, clock: Callable[[], float] = time.monotonic,
|
|
72
|
+
every: float = POLL_EVERY) -> None:
|
|
73
|
+
self._trace_path = Path(trace_path)
|
|
74
|
+
self._graph_path = Path(graph_path)
|
|
75
|
+
self._clock = clock
|
|
76
|
+
self._every = every
|
|
77
|
+
self._lock = threading.Lock()
|
|
78
|
+
self._graph: _Graph | None = None
|
|
79
|
+
self._progress: TraceProgress | None = None
|
|
80
|
+
self._snap: dict | None = None
|
|
81
|
+
self._at = -math.inf
|
|
82
|
+
self._lines: dict[str, dict] | None = None # 按上次读到的算好的功能线
|
|
83
|
+
self._nodes: dict[str, dict[str, list[str]]] = {} # 同上,按功能线算好的节点
|
|
84
|
+
|
|
85
|
+
def view(self, live_line: str | None = None) -> dict | None:
|
|
86
|
+
"""{"collected", "done", "passed", "failed", "skipped", "errors", "running": [最多 3 个测试 id], "running_more",
|
|
87
|
+
"recent": [{test, outcome, seconds}], "lines": {功能线 sid: {"functions": 执行过的, "total": 涉及的}}(只列有
|
|
88
|
+
函数执行过的线)};给了 live_line 并且图里有这条线时多 "nodes": {函数 key: [节点 sid]}。读的时候出了意外(引擎
|
|
89
|
+
的缺陷等)时记下来、返回 None(界面就不显示进度)。"""
|
|
90
|
+
try:
|
|
91
|
+
with self._lock:
|
|
92
|
+
return self._view(live_line)
|
|
93
|
+
except Exception:
|
|
94
|
+
logger.exception("读运行中的进度时出错(%s)", self._trace_path)
|
|
95
|
+
return None
|
|
96
|
+
|
|
97
|
+
def _view(self, live_line: str | None) -> dict:
|
|
98
|
+
if self._progress is None:
|
|
99
|
+
self._graph = self._load_graph()
|
|
100
|
+
self._progress = TraceProgress(self._trace_path,
|
|
101
|
+
functions=None if self._graph is None else frozenset(self._graph.nodes))
|
|
102
|
+
now = self._clock()
|
|
103
|
+
if self._snap is None or now - self._at >= self._every:
|
|
104
|
+
self._snap = self._progress.poll()
|
|
105
|
+
self._at = now
|
|
106
|
+
self._lines = None
|
|
107
|
+
self._nodes = {}
|
|
108
|
+
snap = self._snap
|
|
109
|
+
out = {k: snap[k] for k in ("collected", "done", "passed", "failed", "skipped", "errors")}
|
|
110
|
+
out["running"] = snap["running"][:RUNNING_SHOWN]
|
|
111
|
+
out["running_more"] = max(0, len(snap["running"]) - RUNNING_SHOWN)
|
|
112
|
+
out["recent"] = snap["recent"]
|
|
113
|
+
out["lines"] = self._lines_reached(snap["functions"])
|
|
114
|
+
if live_line is not None:
|
|
115
|
+
nodes = self._nodes_reached(live_line, snap["functions"])
|
|
116
|
+
if nodes is not None:
|
|
117
|
+
out["nodes"] = nodes
|
|
118
|
+
return out
|
|
119
|
+
|
|
120
|
+
def _load_graph(self) -> _Graph | None:
|
|
121
|
+
try:
|
|
122
|
+
return _graph_of(from_json(self._graph_path.read_text(encoding="utf-8")))
|
|
123
|
+
except Exception as e: # noqa: BLE001 —— 图的副本读不了、不是图:只给计数
|
|
124
|
+
logger.warning("读不了这次运行的图(%s),运行中的进度只给计数:%s", self._graph_path, type(e).__name__)
|
|
125
|
+
return None
|
|
126
|
+
|
|
127
|
+
def _lines_reached(self, functions: dict) -> dict[str, dict]:
|
|
128
|
+
if self._lines is None:
|
|
129
|
+
self._lines = {}
|
|
130
|
+
for sid, keys in (self._graph.lines.items() if self._graph is not None else ()):
|
|
131
|
+
reached = sum(1 for k in keys if k in functions)
|
|
132
|
+
if reached:
|
|
133
|
+
self._lines[sid] = {"functions": reached, "total": len(keys)}
|
|
134
|
+
return self._lines
|
|
135
|
+
|
|
136
|
+
def _nodes_reached(self, line: str, functions: dict) -> dict[str, list[str]] | None:
|
|
137
|
+
g = self._graph
|
|
138
|
+
if g is None or line not in g.lines:
|
|
139
|
+
return None
|
|
140
|
+
found = self._nodes.get(line)
|
|
141
|
+
if found is None:
|
|
142
|
+
found = {}
|
|
143
|
+
for key in g.lines[line]:
|
|
144
|
+
run = functions.get(key)
|
|
145
|
+
if run is None:
|
|
146
|
+
continue
|
|
147
|
+
executed = run["lines"]
|
|
148
|
+
found[key] = [sid for sid, head in g.nodes.get(key, ())
|
|
149
|
+
if head is None or any(ln in executed for ln in head)]
|
|
150
|
+
self._nodes[line] = found
|
|
151
|
+
return found
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""项目级的分析锁:同一个项目的分析在进程之间互斥。平台服务(pystepmap serve)和 MCP(pystepmap mcp)是两个进程,读写
|
|
2
|
+
同一个数据目录,都走 flows 里的流程;两边同时分析同一个项目时,后来的那个得到"正在分析"。
|
|
3
|
+
|
|
4
|
+
锁是 <数据目录>/locks/<项目 id>.lock 上的 flock(独占、不阻塞)。flock 跟着打开的文件走:同一进程里另开一次也拿不到;
|
|
5
|
+
进程退出(包括被杀掉)时系统自动释放,不会留下"永远在分析"。锁文件用完不删(删了再建,两个进程可能各锁一个不同的
|
|
6
|
+
文件);只在删除项目时删(remove_lock:自己先拿到锁再删,有人拿着时留着)。测试运行(flows.run_project_tests)拿的
|
|
7
|
+
也是这把锁。locks 目录 0700、锁文件 0600,和数据目录里别的东西一样只有本人能读写。没有 fcntl 的系统(Windows)不加锁:
|
|
8
|
+
try_lock_project 返回 -1,project_locked 总是 False(那里只有进程内的互斥)。数据目录所在的文件系统不支持 flock
|
|
9
|
+
(某些网络盘:ENOTSUP、ENOLCK 等)时一样:加锁返回 -1、查询算没人拿着,不抛错(列项目的接口不能因此失败)。
|
|
10
|
+
|
|
11
|
+
project_locked 查询时会短暂拿一下共享锁;正好撞上的 try_lock_project 等一小会儿(最多 _RETRY_SECONDS)再试,不把这
|
|
12
|
+
一瞬当成"正在分析"。这里不是流程代码,不加 pystepkit 标记。
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
import logging
|
|
18
|
+
import os
|
|
19
|
+
import re
|
|
20
|
+
import stat
|
|
21
|
+
import time
|
|
22
|
+
from pathlib import Path
|
|
23
|
+
|
|
24
|
+
from .store import private_dir
|
|
25
|
+
|
|
26
|
+
try:
|
|
27
|
+
import fcntl
|
|
28
|
+
except ImportError: # Windows
|
|
29
|
+
fcntl = None
|
|
30
|
+
|
|
31
|
+
logger = logging.getLogger(__name__)
|
|
32
|
+
|
|
33
|
+
LOCKS_DIR = "locks"
|
|
34
|
+
_PROJECT_ID = re.compile(r"[A-Za-z0-9_-]{1,64}")
|
|
35
|
+
_RETRY_SECONDS = 0.1
|
|
36
|
+
_RETRY_STEP = 0.01
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def lock_path(home: Path, project_id: str) -> Path:
|
|
40
|
+
"""项目的锁文件。项目 id 只能是字母、数字、_、-(库里的 id 都是这样):不让它拼出 locks 目录之外的路径。"""
|
|
41
|
+
if not isinstance(project_id, str) or not _PROJECT_ID.fullmatch(project_id):
|
|
42
|
+
raise ValueError(f"项目 id 不合法:{project_id!r}")
|
|
43
|
+
return Path(home) / LOCKS_DIR / f"{project_id}.lock"
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def try_lock_project(home: Path, project_id: str) -> int | None:
|
|
47
|
+
"""拿项目的分析锁(不阻塞):拿到时返回锁文件的描述符(用 unlock_project 释放),被别人拿着时 None,没有 fcntl 或
|
|
48
|
+
文件系统不支持 flock 时 -1(只有进程内的互斥)。建不了 locks 目录、锁文件时抛 OSError。"""
|
|
49
|
+
path = lock_path(home, project_id)
|
|
50
|
+
if fcntl is None:
|
|
51
|
+
return -1
|
|
52
|
+
private_dir(path.parent)
|
|
53
|
+
fd = os.open(path, os.O_RDWR | os.O_CREAT, 0o600)
|
|
54
|
+
locked = False
|
|
55
|
+
try:
|
|
56
|
+
if os.name == "posix" and stat.S_IMODE(os.fstat(fd).st_mode) != 0o600: # 以前建的、比这宽的
|
|
57
|
+
os.fchmod(fd, 0o600)
|
|
58
|
+
deadline = time.monotonic() + _RETRY_SECONDS
|
|
59
|
+
while True:
|
|
60
|
+
try:
|
|
61
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
62
|
+
locked = True
|
|
63
|
+
return fd
|
|
64
|
+
except BlockingIOError:
|
|
65
|
+
if time.monotonic() >= deadline:
|
|
66
|
+
return None
|
|
67
|
+
time.sleep(_RETRY_STEP)
|
|
68
|
+
except OSError as e: # 文件系统不支持 flock
|
|
69
|
+
logger.warning("数据目录所在的文件系统不支持文件锁(%s),项目 %s 的分析只在本进程内互斥",
|
|
70
|
+
e.strerror or e, project_id)
|
|
71
|
+
return -1
|
|
72
|
+
finally:
|
|
73
|
+
if not locked:
|
|
74
|
+
os.close(fd)
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def unlock_project(fd: int | None) -> None:
|
|
78
|
+
"""释放 try_lock_project 拿到的锁(None、-1 什么都不做)。"""
|
|
79
|
+
if fd is None or fd < 0:
|
|
80
|
+
return
|
|
81
|
+
try:
|
|
82
|
+
if fcntl is not None:
|
|
83
|
+
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
84
|
+
except OSError: # 关掉描述符就放开了,这一步出错不要紧
|
|
85
|
+
pass
|
|
86
|
+
finally:
|
|
87
|
+
os.close(fd)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def remove_lock(home: Path, project_id: str) -> bool:
|
|
91
|
+
"""删除项目时删掉它的锁文件。先拿锁(不阻塞)再删:拿得到说明没人在用,删掉;有人拿着(另一个进程还在分析、
|
|
92
|
+
本进程还在跑测试)时留着,返回 False(删了再建,两个进程会各锁一个不同的文件;留下一个空文件不碍事)。没有锁文件
|
|
93
|
+
时 False。没有 fcntl 时直接删。删不了(权限等)时记一条日志,返回 False。"""
|
|
94
|
+
path = lock_path(home, project_id)
|
|
95
|
+
try:
|
|
96
|
+
if fcntl is None:
|
|
97
|
+
path.unlink()
|
|
98
|
+
return True
|
|
99
|
+
fd = os.open(path, os.O_RDWR)
|
|
100
|
+
except FileNotFoundError:
|
|
101
|
+
return False
|
|
102
|
+
except OSError as e:
|
|
103
|
+
logger.warning("没能删掉项目 %s 的锁文件:%s", project_id, e.strerror or e)
|
|
104
|
+
return False
|
|
105
|
+
try:
|
|
106
|
+
try:
|
|
107
|
+
fcntl.flock(fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
108
|
+
except BlockingIOError:
|
|
109
|
+
return False
|
|
110
|
+
except OSError: # 文件系统不支持 flock:没有跨进程的锁,直接删
|
|
111
|
+
pass
|
|
112
|
+
try:
|
|
113
|
+
path.unlink() # 拿着锁删:之后来拿锁的会新建一个文件
|
|
114
|
+
except OSError as e:
|
|
115
|
+
logger.warning("没能删掉项目 %s 的锁文件:%s", project_id, e.strerror or e)
|
|
116
|
+
return False
|
|
117
|
+
return True
|
|
118
|
+
finally:
|
|
119
|
+
os.close(fd)
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def project_locked(home: Path, project_id: str) -> bool:
|
|
123
|
+
"""这个项目的分析锁此刻有没有被拿着(别的进程,或者本进程)。不建任何文件;锁文件打不开时算没有。"""
|
|
124
|
+
path = lock_path(home, project_id)
|
|
125
|
+
if fcntl is None:
|
|
126
|
+
return False
|
|
127
|
+
try:
|
|
128
|
+
fd = os.open(path, os.O_RDONLY)
|
|
129
|
+
except OSError: # 还没有锁文件(从没分析过),或者打不开
|
|
130
|
+
return False
|
|
131
|
+
try:
|
|
132
|
+
fcntl.flock(fd, fcntl.LOCK_SH | fcntl.LOCK_NB)
|
|
133
|
+
except BlockingIOError:
|
|
134
|
+
return True
|
|
135
|
+
except OSError: # 文件系统不支持 flock:没有跨进程的锁,算没人拿着
|
|
136
|
+
return False
|
|
137
|
+
finally:
|
|
138
|
+
os.close(fd) # 拿到的共享锁随之释放
|
|
139
|
+
return False
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""pystepmap mcp:标准输入输出方式的 MCP 服务,给 Claude Code 查项目的流程。工具在 mcp_tools.py。
|
|
2
|
+
|
|
3
|
+
协议层用官方 mcp Python SDK 的低层 Server(mcp.server.lowlevel)和 stdio_server:标准输入一行一条 JSON-RPC 消息,
|
|
4
|
+
标准输出只写协议消息。SDK 的 stdio_server 在服务期间把文件描述符 1 指到标准错误、0 指到空设备,协议走它自己复制出来
|
|
5
|
+
的描述符,所以直接写描述符 1 的和子进程的输出到不了协议上;sys.stdout 在服务期间另外换成标准错误(print 留在缓冲区
|
|
6
|
+
里的字不会在退出时冲到协议上);日志在导入别的模块之前就配到标准错误。
|
|
7
|
+
关掉标准输入时服务结束,退出码 0;数据目录打不开时标准错误写中文原因,退出码 2。
|
|
8
|
+
|
|
9
|
+
和 pystepmap serve 用同一个数据目录(PYSTEPMAP_HOME,默认 ~/.pystepmap),但不拿 pystepmap.lock:可以和服务同时开,也可以
|
|
10
|
+
开多个。同一项目的分析靠项目级的锁互斥(locks.py),库的写入靠 SQLite 的写锁。
|
|
11
|
+
|
|
12
|
+
工具调用在工作线程里跑(分析要几秒,不挡住 ping 等别的消息);Tools 可以在多个线程里同时调用。分析和约束检查都在
|
|
13
|
+
子进程里跑(worker.py,带超时)。退出不等还在跑的工具调用:标准输入关了,服务结束后杀掉还在跑的分析 / 检查子进程
|
|
14
|
+
(worker.kill_running),再最多等 EXIT_GRACE 秒让工作线程收尾,还没完就直接退出;收到 SIGTERM 时杀掉子进程、立刻
|
|
15
|
+
退出(退出码都是 0)。
|
|
16
|
+
|
|
17
|
+
不导入、不执行被分析项目的代码:Claude Code 通常在被分析的项目里启动它(当前目录就是项目),控制台脚本 pystepmap
|
|
18
|
+
不把当前目录放进模块搜索路径(用 python -m 启动时要加 -P);分析在子进程里跑,子进程的当前目录是数据目录。
|
|
19
|
+
也不导入平台的接口和运行测试的代码:这里只导入 store(库、DB_NAME、default_home)和 mcp_tools(以及它们用到的 flows、
|
|
20
|
+
worker、shared 等),不导入 app、api、testflows、runner——pystepmap mcp 的进程里没有能执行项目测试的代码(测试真的
|
|
21
|
+
走一遍 pystepmap mcp 的入口,再查 sys.modules)。
|
|
22
|
+
这里不是流程代码,不加 pystepkit 标记。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import contextlib
|
|
28
|
+
import logging
|
|
29
|
+
import os
|
|
30
|
+
import signal
|
|
31
|
+
import sys
|
|
32
|
+
import threading
|
|
33
|
+
import time
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
|
|
36
|
+
logger = logging.getLogger(__name__)
|
|
37
|
+
|
|
38
|
+
EXIT_GRACE = 3.0 # 标准输入关了以后,最多等还在跑的工具调用收尾几秒
|
|
39
|
+
_SDK_HINT = ("没有安装 MCP SDK(缺少 {name}):重新安装 pystepmap 把依赖装全(pip install -U pystepmap);"
|
|
40
|
+
"从源码仓库运行时在仓库根目录运行 uv sync,再用 uv run pystepmap mcp 启动")
|
|
41
|
+
|
|
42
|
+
_busy = 0 # 正在工作线程里跑的工具调用
|
|
43
|
+
_busy_lock = threading.Lock()
|
|
44
|
+
|
|
45
|
+
SERVER_NAME = "pystepmap"
|
|
46
|
+
_BASE = (
|
|
47
|
+
"pystepmap 把 Python 后端静态分析成业务流程图:每条功能线是一个入口(接口、后台任务、工作流)的流程,节点是一次步骤调用、"
|
|
48
|
+
"一个判断、一个循环或一个结局。改带流程的代码之前,先用 find_nodes(文件 + 行号)和 get_flow 看清要改的位置在哪条"
|
|
49
|
+
"功能线的哪个节点;改完调用 analyze_project 重新分析,再用 diff_flows 把流程的变化告诉用户。结果开头出现"
|
|
50
|
+
"\"⚠ 代码已变更\"时图可能过期,先 analyze_project。不给 project 时用当前目录所在的项目。"
|
|
51
|
+
"代码不需要任何标记就能分析:接口(FastAPI、Flask)、后台任务(taskiq、Celery、DBOS)、命令行子命令、"
|
|
52
|
+
"`if __name__ == \"__main__\":` 里调用的函数都会各成一条功能线。新写了一个业务入口之后,analyze_project 再用 "
|
|
53
|
+
"list_flows 确认它在列表里;不在时(analyze_project 的结果会列出\"不在任何功能线上的函数\"),在它的 def 上面"
|
|
54
|
+
"(有装饰器时是第一个装饰器上面)加一行注释 `# pystepmap: 入口 <中文标题>` 再重新分析,这样写一定成线,不用装任何包。"
|
|
55
|
+
"不在功能线上的函数也能看流程:get_flow 只给 function。"
|
|
56
|
+
)
|
|
57
|
+
_OWN_REQUIREMENTS = (
|
|
58
|
+
"接到业务需求时:先 list_requirements 看有没有对应的需求;没有就用 save_requirement 把改完之后的流程写成一条需求"
|
|
59
|
+
"(状态草稿),把返回里的流程图地址给用户看图确认,确认后再实现;实现并 analyze_project 之后用 get_requirement "
|
|
60
|
+
"把设计和实现的差异告诉用户。"
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
_OPENSPEC_REQUIREMENTS = (
|
|
65
|
+
"这个项目用 OpenSpec 管需求:需求、变更和任务照 OpenSpec 的流程走,不要用 save_requirement。涉及流程变化时,把改完之后"
|
|
66
|
+
"的流程写成 OpenSpec 变更的 design.md 里的一个 ```flow 代码块(块里第一行 `功能线:<功能线的标题>`,写法见 "
|
|
67
|
+
"save_requirement 的说明);写好后用 get_requirement(编号就是变更名)取这份设计的流程图地址,给用户看图确认;"
|
|
68
|
+
"实现并 analyze_project 之后再用 get_requirement 把设计和实现的差异告诉用户。"
|
|
69
|
+
)
|
|
70
|
+
INSTRUCTIONS = _BASE + _OWN_REQUIREMENTS # 不知道当前目录是什么项目时的说明
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _project_root(cwd: Path | None) -> Path | None:
|
|
74
|
+
"""当前目录所在的项目根:从当前目录往上,第一个有 openspec/、.pystepmap/ 或 .git 的目录;找不到时 None。"""
|
|
75
|
+
if cwd is None:
|
|
76
|
+
return None
|
|
77
|
+
for folder in (cwd, *cwd.parents):
|
|
78
|
+
if any((folder / name).exists() for name in ("openspec", ".pystepmap", ".git")):
|
|
79
|
+
return folder
|
|
80
|
+
return None
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def instructions_for(cwd: Path | None) -> str:
|
|
84
|
+
"""给 AI 的服务说明。需求那一段看当前目录所在的项目:用 OpenSpec(有 openspec/ 目录)的让需求走 OpenSpec、
|
|
85
|
+
设计的流程写在它的文件里;其余的用 pystepmap 自己的需求文件。两段不会同时出现——同一件事只有一个入口。"""
|
|
86
|
+
root = _project_root(cwd)
|
|
87
|
+
if root is not None and (root / "openspec").is_dir():
|
|
88
|
+
return _BASE + _OPENSPEC_REQUIREMENTS
|
|
89
|
+
return INSTRUCTIONS
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _cwd() -> Path | None:
|
|
93
|
+
try:
|
|
94
|
+
return Path(os.getcwd())
|
|
95
|
+
except OSError: # 当前目录被删掉了
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _call(tools, name: str, arguments: dict | None) -> tuple[str, bool]:
|
|
100
|
+
"""调用一个工具:(文本, 是否出错)。ToolError 的信息原样给 AI;别的异常记日志(标准错误),给一句中文。"""
|
|
101
|
+
from .mcp_tools import ToolError
|
|
102
|
+
|
|
103
|
+
global _busy
|
|
104
|
+
with _busy_lock:
|
|
105
|
+
_busy += 1
|
|
106
|
+
try:
|
|
107
|
+
return tools.call(name, arguments), False
|
|
108
|
+
except ToolError as e:
|
|
109
|
+
return str(e), True
|
|
110
|
+
except Exception as e: # 不让一个工具的错误带走整个服务
|
|
111
|
+
logger.exception("工具 %s 出错", name)
|
|
112
|
+
return f"pystepmap 内部错误({name}):{type(e).__name__}: {e}", True
|
|
113
|
+
finally:
|
|
114
|
+
with _busy_lock:
|
|
115
|
+
_busy -= 1
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _busy_calls() -> int:
|
|
119
|
+
with _busy_lock:
|
|
120
|
+
return _busy
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def _terminate(signum, frame) -> None:
|
|
124
|
+
"""SIGTERM:杀掉还在跑的分析 / 检查子进程,立刻退出(不等工作线程,也不等标准输入)。"""
|
|
125
|
+
from .worker import kill_running
|
|
126
|
+
|
|
127
|
+
kill_running()
|
|
128
|
+
sys.stderr.flush()
|
|
129
|
+
os._exit(0)
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _finish_calls() -> None:
|
|
133
|
+
"""服务结束以后:杀掉还在跑的子进程,最多等 EXIT_GRACE 秒让工具调用收尾;还没完就直接退出。"""
|
|
134
|
+
from .worker import kill_running
|
|
135
|
+
|
|
136
|
+
kill_running()
|
|
137
|
+
deadline = time.monotonic() + EXIT_GRACE
|
|
138
|
+
while _busy_calls() and time.monotonic() < deadline:
|
|
139
|
+
time.sleep(0.05)
|
|
140
|
+
if _busy_calls():
|
|
141
|
+
logger.warning("还有 %d 个工具调用没做完,不等了", _busy_calls())
|
|
142
|
+
sys.stderr.flush()
|
|
143
|
+
os._exit(0)
|
|
144
|
+
|
|
145
|
+
|
|
146
|
+
def build_server(tools, instructions: str = INSTRUCTIONS):
|
|
147
|
+
"""把 Tools 包成 SDK 的低层 Server:tools/list 来自 TOOL_SPECS,tools/call 在工作线程里调 Tools.call。"""
|
|
148
|
+
import anyio
|
|
149
|
+
import mcp_types as types
|
|
150
|
+
from mcp.server.lowlevel import Server
|
|
151
|
+
|
|
152
|
+
from . import __version__
|
|
153
|
+
from .mcp_tools import TOOL_SPECS
|
|
154
|
+
|
|
155
|
+
listed = [types.Tool(name=s["name"], description=s["description"], input_schema=s["inputSchema"]) for s in TOOL_SPECS]
|
|
156
|
+
|
|
157
|
+
async def list_tools(ctx, params) -> types.ListToolsResult:
|
|
158
|
+
return types.ListToolsResult(tools=listed)
|
|
159
|
+
|
|
160
|
+
async def call_tool(ctx, params: types.CallToolRequestParams) -> types.CallToolResult:
|
|
161
|
+
# abandon_on_cancel:客户端断开(标准输入关了)时不等这个线程,退出时由 _finish_calls 收尾
|
|
162
|
+
text, failed = await anyio.to_thread.run_sync(_call, tools, params.name, params.arguments,
|
|
163
|
+
abandon_on_cancel=True)
|
|
164
|
+
return types.CallToolResult(content=[types.TextContent(type="text", text=text)], is_error=failed)
|
|
165
|
+
|
|
166
|
+
return Server(SERVER_NAME, version=__version__, instructions=instructions,
|
|
167
|
+
on_list_tools=list_tools, on_call_tool=call_tool)
|
|
168
|
+
|
|
169
|
+
|
|
170
|
+
def run(home: Path | None = None) -> int:
|
|
171
|
+
"""pystepmap mcp 的入口:打开数据目录,在标准输入输出上提供工具,直到标准输入关闭。返回退出码。"""
|
|
172
|
+
logging.basicConfig(stream=sys.stderr, level=logging.WARNING,
|
|
173
|
+
format="pystepmap mcp %(levelname)s %(name)s: %(message)s")
|
|
174
|
+
try: # 先看 SDK 在不在:缺了给一句中文,不是一大段 traceback
|
|
175
|
+
import anyio
|
|
176
|
+
import mcp_types # noqa: F401
|
|
177
|
+
from mcp.server.lowlevel import Server # noqa: F401
|
|
178
|
+
from mcp.server.stdio import stdio_server
|
|
179
|
+
except ModuleNotFoundError as e:
|
|
180
|
+
print(_SDK_HINT.format(name=e.name or "mcp"), file=sys.stderr)
|
|
181
|
+
return 2
|
|
182
|
+
from .store import DB_NAME, Store, StoreError, default_home
|
|
183
|
+
|
|
184
|
+
home = Path(home) if home is not None else default_home()
|
|
185
|
+
try:
|
|
186
|
+
store = Store(home / DB_NAME)
|
|
187
|
+
except StoreError as e:
|
|
188
|
+
print(f"无法打开平台数据目录:{e}", file=sys.stderr)
|
|
189
|
+
return 2
|
|
190
|
+
|
|
191
|
+
from .mcp_tools import Tools
|
|
192
|
+
|
|
193
|
+
server = build_server(Tools(store, _cwd()), instructions_for(_cwd()))
|
|
194
|
+
|
|
195
|
+
async def serve() -> None:
|
|
196
|
+
# stdio_server 先认领描述符 1(要求这时 sys.stdout 还是它),之后 Python 层面的 print 也改去标准错误:
|
|
197
|
+
# 只靠描述符改道不够,留在 sys.stdout 缓冲区里的字会在退出时(描述符已经还原)冲到协议上
|
|
198
|
+
async with stdio_server() as (read_stream, write_stream):
|
|
199
|
+
try:
|
|
200
|
+
with contextlib.redirect_stdout(sys.stderr):
|
|
201
|
+
await server.run(read_stream, write_stream, server.create_initialization_options())
|
|
202
|
+
finally:
|
|
203
|
+
if sys.__stdout__ is not None: # 万一有人写了原来的 sys.stdout:趁描述符 1 还指着标准错误冲掉
|
|
204
|
+
sys.__stdout__.flush()
|
|
205
|
+
|
|
206
|
+
in_main = threading.current_thread() is threading.main_thread()
|
|
207
|
+
previous = signal.signal(signal.SIGTERM, _terminate) if in_main else None
|
|
208
|
+
try:
|
|
209
|
+
anyio.run(serve)
|
|
210
|
+
except KeyboardInterrupt: # 终端里 Ctrl+C:用户要停,不是出错
|
|
211
|
+
pass
|
|
212
|
+
finally:
|
|
213
|
+
if in_main:
|
|
214
|
+
signal.signal(signal.SIGTERM, previous)
|
|
215
|
+
_finish_calls()
|
|
216
|
+
return 0
|