agent-checks-mcp 0.0.1__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agent_checks_mcp-0.0.1/.gitignore +6 -0
- agent_checks_mcp-0.0.1/PKG-INFO +48 -0
- agent_checks_mcp-0.0.1/README.md +37 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/checks/__init__.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/checks/core.py +15 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/checks/sources.py +173 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/checks/tools.py +47 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/checks_mcp/__init__.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/checks_mcp/core.py +84 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/checks_mcp/instructions.py +26 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/environment/__init__.py +4 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/environment/core.py +40 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/environment/tools.py +58 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/linter/__init__.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/linter/core.py +8 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/linter/tools.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/runner/__init__.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/runner/core.py +86 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/session/__init__.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/session/core.py +223 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/tester/__init__.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/tester/core.py +8 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/tester/tools.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/typechecker/__init__.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/typechecker/core.py +8 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/typechecker/tools.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/watcher/__init__.py +3 -0
- agent_checks_mcp-0.0.1/agent_checks_mcp/agenticpytools/watcher/core.py +94 -0
- agent_checks_mcp-0.0.1/pyproject.toml +37 -0
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: agent-checks-mcp
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: An MCP server that watches a project and serves cached lint, typecheck, and test results
|
|
5
|
+
Author: David Vujic
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Requires-Python: >=3.12
|
|
8
|
+
Requires-Dist: fastmcp
|
|
9
|
+
Requires-Dist: watchfiles
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
|
|
12
|
+
# Agent Checks MCP
|
|
13
|
+
|
|
14
|
+
Status: WIP, not ready for usage (yet)
|
|
15
|
+
|
|
16
|
+
An MCP server that watches a project and serves cached lint, typecheck, and test results.
|
|
17
|
+
|
|
18
|
+
The Checks MCP watches a project in the background and keeps lint, typecheck, and test results up to date, so your agent gets them instantly instead of waiting for each run. Each tool takes a `project_full_path` and a `session_id`:
|
|
19
|
+
|
|
20
|
+
- `start_watching` — start watching a project; returns at once with its detected commands, while the initial lint, typecheck, and test runs warm the cache in the background.
|
|
21
|
+
- `detected_commands` — the lint, typecheck, and test commands for a watched session, detected on demand otherwise.
|
|
22
|
+
- `lint` — latest cached lint results for the session; runs lint on demand if not ready.
|
|
23
|
+
- `typecheck` — latest cached typecheck results for the session; runs typecheck on demand if not ready.
|
|
24
|
+
- `test` — latest cached test results for the session; runs the tests on demand if not ready.
|
|
25
|
+
- `stop_watching` — stop watching a project session; the watcher thread exits.
|
|
26
|
+
|
|
27
|
+
Each `lint`, `typecheck`, and `test` result has a `running` flag that covers only that check kind. While a run of the kind is in progress, the tool returns the previous result (or a placeholder without results) with `running: true`, instead of waiting. A failed or cancelled run returns an entry without results and a `note`, and is not retried until files change or a new session starts.
|
|
28
|
+
|
|
29
|
+
## Setup
|
|
30
|
+
|
|
31
|
+
### Add the MCP server to your harness
|
|
32
|
+
|
|
33
|
+
#### Example: using `uvx`
|
|
34
|
+
``` json
|
|
35
|
+
{
|
|
36
|
+
"mcpServers": {
|
|
37
|
+
"agent-checks-mcp": {
|
|
38
|
+
"command": "uvx",
|
|
39
|
+
"args": ["agent-checks-mcp"]
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
```
|
|
44
|
+
|
|
45
|
+
or install it:
|
|
46
|
+
``` shell
|
|
47
|
+
pip install agent-checks-mcp
|
|
48
|
+
```
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# Agent Checks MCP
|
|
2
|
+
|
|
3
|
+
Status: WIP, not ready for usage (yet)
|
|
4
|
+
|
|
5
|
+
An MCP server that watches a project and serves cached lint, typecheck, and test results.
|
|
6
|
+
|
|
7
|
+
The Checks MCP watches a project in the background and keeps lint, typecheck, and test results up to date, so your agent gets them instantly instead of waiting for each run. Each tool takes a `project_full_path` and a `session_id`:
|
|
8
|
+
|
|
9
|
+
- `start_watching` — start watching a project; returns at once with its detected commands, while the initial lint, typecheck, and test runs warm the cache in the background.
|
|
10
|
+
- `detected_commands` — the lint, typecheck, and test commands for a watched session, detected on demand otherwise.
|
|
11
|
+
- `lint` — latest cached lint results for the session; runs lint on demand if not ready.
|
|
12
|
+
- `typecheck` — latest cached typecheck results for the session; runs typecheck on demand if not ready.
|
|
13
|
+
- `test` — latest cached test results for the session; runs the tests on demand if not ready.
|
|
14
|
+
- `stop_watching` — stop watching a project session; the watcher thread exits.
|
|
15
|
+
|
|
16
|
+
Each `lint`, `typecheck`, and `test` result has a `running` flag that covers only that check kind. While a run of the kind is in progress, the tool returns the previous result (or a placeholder without results) with `running: true`, instead of waiting. A failed or cancelled run returns an entry without results and a `note`, and is not retried until files change or a new session starts.
|
|
17
|
+
|
|
18
|
+
## Setup
|
|
19
|
+
|
|
20
|
+
### Add the MCP server to your harness
|
|
21
|
+
|
|
22
|
+
#### Example: using `uvx`
|
|
23
|
+
``` json
|
|
24
|
+
{
|
|
25
|
+
"mcpServers": {
|
|
26
|
+
"agent-checks-mcp": {
|
|
27
|
+
"command": "uvx",
|
|
28
|
+
"args": ["agent-checks-mcp"]
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
```
|
|
33
|
+
|
|
34
|
+
or install it:
|
|
35
|
+
``` shell
|
|
36
|
+
pip install agent-checks-mcp
|
|
37
|
+
```
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Command detection for a project, from justfile down to the venv."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from agent_checks_mcp.agenticpytools.checks.sources import justfile_commands, makefile_commands, pyproject_task_commands, pyproject_tool_commands, venv_commands
|
|
4
|
+
from agent_checks_mcp.agenticpytools.checks.tools import Tool
|
|
5
|
+
from agent_checks_mcp.agenticpytools.environment import project_tool
|
|
6
|
+
|
|
7
|
+
def detect_commands(project: Path, tools: dict[str, Tool], recipe_names: tuple[str, ...]) -> list[dict]:
|
|
8
|
+
"""Commands from the first source that finds any, in ladder order."""
|
|
9
|
+
path = Path(project).expanduser().resolve()
|
|
10
|
+
prefix = (project_tool(path) or {}).get('prefix', [])
|
|
11
|
+
for source in (lambda p: justfile_commands(p, recipe_names), lambda p: makefile_commands(p, recipe_names), lambda p: pyproject_task_commands(p, recipe_names), lambda p: pyproject_tool_commands(p, prefix, tools), lambda p: venv_commands(p, tools)):
|
|
12
|
+
commands = source(path)
|
|
13
|
+
if commands:
|
|
14
|
+
return [{**cmd, 'cwd': str(path)} for cmd in commands]
|
|
15
|
+
return []
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
"""Generic command sources: justfile, Makefile, pyproject tasks, pyproject tools, and venv."""
|
|
2
|
+
import configparser
|
|
3
|
+
import importlib.metadata
|
|
4
|
+
import re
|
|
5
|
+
import shutil
|
|
6
|
+
import tomllib
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from agent_checks_mcp.agenticpytools.checks.tools import Tool, dependency_names, normalize_dep_name
|
|
9
|
+
from agent_checks_mcp.agenticpytools.environment import dotted_keys, project_tool, venv_dir, venv_python
|
|
10
|
+
JUSTFILES = ('justfile', 'Justfile', '.justfile')
|
|
11
|
+
MAKEFILES = ('Makefile', 'GNUmakefile')
|
|
12
|
+
INI_FILES = ('setup.cfg', 'tox.ini')
|
|
13
|
+
|
|
14
|
+
def _command(argv: list[str], source: str, tool: str, spec: Tool | None=None) -> dict:
|
|
15
|
+
"""A detected command with the spec's file handling; detect_commands adds the cwd."""
|
|
16
|
+
command = {'argv': argv, 'source': source, 'tool': tool}
|
|
17
|
+
spec = spec or {}
|
|
18
|
+
if not spec.get('takes_files', False):
|
|
19
|
+
return command
|
|
20
|
+
command['takes_files'] = True
|
|
21
|
+
if spec.get('project_args'):
|
|
22
|
+
command['project_args'] = list(spec['project_args'])
|
|
23
|
+
return command
|
|
24
|
+
|
|
25
|
+
def _read_pyproject(project: Path) -> dict | None:
|
|
26
|
+
"""Parsed pyproject.toml, or None when missing or invalid."""
|
|
27
|
+
try:
|
|
28
|
+
with (project / 'pyproject.toml').open('rb') as file:
|
|
29
|
+
return tomllib.load(file)
|
|
30
|
+
except (FileNotFoundError, tomllib.TOMLDecodeError):
|
|
31
|
+
return None
|
|
32
|
+
|
|
33
|
+
def _first_file(project: Path, names: tuple[str, ...]) -> Path | None:
|
|
34
|
+
"""The first existing file among the given names."""
|
|
35
|
+
return next((project / name for name in names if (project / name).is_file()), None)
|
|
36
|
+
|
|
37
|
+
def _recipe_name(path: Path | None, pattern: str) -> str | None:
|
|
38
|
+
"""The first recipe name matching the pattern, or None."""
|
|
39
|
+
if path is None:
|
|
40
|
+
return None
|
|
41
|
+
return next((match.group(1) for line in path.read_text().splitlines() if (match := re.search(pattern, line)) is not None), None)
|
|
42
|
+
|
|
43
|
+
def _task_name(table: dict, names: tuple[str, ...]) -> str | None:
|
|
44
|
+
"""The first task name present in the table."""
|
|
45
|
+
return next((name for name in names if name in table), None)
|
|
46
|
+
|
|
47
|
+
def justfile_commands(project: Path, recipe_names: tuple[str, ...]) -> list[dict]:
|
|
48
|
+
"""Command from a justfile recipe matching the recipe names."""
|
|
49
|
+
if shutil.which('just') is None:
|
|
50
|
+
return []
|
|
51
|
+
pattern = '^(' + '|'.join(map(re.escape, recipe_names)) + ')\\b[^:]*:'
|
|
52
|
+
recipe = _recipe_name(_first_file(project, JUSTFILES), pattern)
|
|
53
|
+
if recipe is None:
|
|
54
|
+
return []
|
|
55
|
+
return [_command(['just', recipe], 'justfile', 'just')]
|
|
56
|
+
|
|
57
|
+
def makefile_commands(project: Path, recipe_names: tuple[str, ...]) -> list[dict]:
|
|
58
|
+
"""Command from a Makefile target matching the recipe names."""
|
|
59
|
+
if shutil.which('make') is None:
|
|
60
|
+
return []
|
|
61
|
+
pattern = '^(' + '|'.join(map(re.escape, recipe_names)) + '):'
|
|
62
|
+
target = _recipe_name(_first_file(project, MAKEFILES), pattern)
|
|
63
|
+
if target is None:
|
|
64
|
+
return []
|
|
65
|
+
return [_command(['make', target], 'makefile', 'make')]
|
|
66
|
+
|
|
67
|
+
def pyproject_task_commands(project: Path, recipe_names: tuple[str, ...]) -> list[dict]:
|
|
68
|
+
"""Commands from pyproject task runners: poe, pixi, and hatch."""
|
|
69
|
+
data = _read_pyproject(project)
|
|
70
|
+
if data is None:
|
|
71
|
+
return []
|
|
72
|
+
tables = data.get('tool', {})
|
|
73
|
+
manager = project_tool(project)
|
|
74
|
+
return [*_poe_commands(tables.get('poe', {}), manager, recipe_names), *_pixi_commands(tables.get('pixi', {}), recipe_names), *_hatch_commands(tables.get('hatch', {}), recipe_names)]
|
|
75
|
+
|
|
76
|
+
def _poe_commands(poe: dict, manager: dict | None, recipe_names: tuple[str, ...]) -> list[dict]:
|
|
77
|
+
"""Command from a poe task, via the project manager or a global poe."""
|
|
78
|
+
task = _task_name(poe.get('tasks', {}), recipe_names)
|
|
79
|
+
if task is None:
|
|
80
|
+
return []
|
|
81
|
+
if manager is None and shutil.which('poe') is None:
|
|
82
|
+
return []
|
|
83
|
+
prefix = manager['prefix'] if manager is not None else []
|
|
84
|
+
return [_command(prefix + ['poe', task], 'pyproject-task', 'poe')]
|
|
85
|
+
|
|
86
|
+
def _pixi_commands(pixi: dict, recipe_names: tuple[str, ...]) -> list[dict]:
|
|
87
|
+
"""Command from a pixi task, when pixi is installed."""
|
|
88
|
+
task = _task_name(pixi.get('tasks', {}), recipe_names)
|
|
89
|
+
if task is None or shutil.which('pixi') is None:
|
|
90
|
+
return []
|
|
91
|
+
return [_command(['pixi', 'run', task], 'pyproject-task', 'pixi')]
|
|
92
|
+
|
|
93
|
+
def _hatch_commands(hatch: dict, recipe_names: tuple[str, ...]) -> list[dict]:
|
|
94
|
+
"""Commands from hatch environment scripts."""
|
|
95
|
+
if shutil.which('hatch') is None:
|
|
96
|
+
return []
|
|
97
|
+
commands = []
|
|
98
|
+
for name, env in hatch.get('envs', {}).items():
|
|
99
|
+
task = _task_name(env.get('scripts', {}), recipe_names)
|
|
100
|
+
if task is not None:
|
|
101
|
+
script = task if name == 'default' else f'{name}:{task}'
|
|
102
|
+
commands.append(_command(['hatch', 'run', script], 'pyproject-task', 'hatch'))
|
|
103
|
+
return commands
|
|
104
|
+
|
|
105
|
+
def pyproject_tool_commands(project: Path, prefix: list[str], tools: dict[str, Tool]) -> list[dict]:
|
|
106
|
+
"""Commands for tools declared as dependencies or via config markers."""
|
|
107
|
+
data = _read_pyproject(project)
|
|
108
|
+
return [_command(prefix + [name] + args, source, name, tools[name]) for name, source in _detected_tools(project, data, tools) for args in tools[name]['argvs']]
|
|
109
|
+
|
|
110
|
+
def _detected_tools(project: Path, data: dict | None, tools: dict[str, Tool]) -> list[tuple[str, str]]:
|
|
111
|
+
"""Detected tools as (name, source) pairs in table order."""
|
|
112
|
+
sections = dotted_keys(data or {})
|
|
113
|
+
ini = _ini_section_names(project)
|
|
114
|
+
dep_tools = {name for name in dependency_names(data or {}) if name in tools}
|
|
115
|
+
configured = {name for name, tool in tools.items() if _is_configured(project, tool, sections, ini)}
|
|
116
|
+
return [(name, 'pyproject' if name in dep_tools else 'config-file') for name in tools if name in dep_tools or name in configured]
|
|
117
|
+
|
|
118
|
+
def _ini_section_names(project: Path) -> set[str]:
|
|
119
|
+
"""Section names present in setup.cfg or tox.ini."""
|
|
120
|
+
names = set()
|
|
121
|
+
for filename in INI_FILES:
|
|
122
|
+
parser = configparser.ConfigParser()
|
|
123
|
+
try:
|
|
124
|
+
parser.read(project / filename)
|
|
125
|
+
except configparser.Error:
|
|
126
|
+
continue
|
|
127
|
+
names |= set(parser.sections())
|
|
128
|
+
return names
|
|
129
|
+
|
|
130
|
+
def _is_configured(project: Path, tool: Tool, sections: set[str], ini: set[str]) -> bool:
|
|
131
|
+
"""Whether any of the tool's config markers exists in the project."""
|
|
132
|
+
return _has_pyproject_section(tool, sections) or _has_section_prefix(tool, sections) or _has_ini_section(tool, ini) or _has_marker_file(project, tool)
|
|
133
|
+
|
|
134
|
+
def _has_pyproject_section(tool: Tool, sections: set[str]) -> bool:
|
|
135
|
+
"""Whether a tool section exists in the pyproject tables."""
|
|
136
|
+
return any((section in sections for section in tool.get('sections', [])))
|
|
137
|
+
|
|
138
|
+
def _has_section_prefix(tool: Tool, sections: set[str]) -> bool:
|
|
139
|
+
"""Whether a pyproject section key matches a tool section prefix."""
|
|
140
|
+
return any((_key_matches_prefix(key, prefix) for prefix in tool.get('section_prefixes', []) for key in sections))
|
|
141
|
+
|
|
142
|
+
def _key_matches_prefix(key: str, prefix: str) -> bool:
|
|
143
|
+
"""Whether the section key is the prefix or nested under it."""
|
|
144
|
+
return key == prefix or key.startswith(f'{prefix}.')
|
|
145
|
+
|
|
146
|
+
def _has_ini_section(tool: Tool, ini: set[str]) -> bool:
|
|
147
|
+
"""Whether a tool section exists in setup.cfg or tox.ini."""
|
|
148
|
+
return any((section in ini for section in tool.get('ini_sections', [])))
|
|
149
|
+
|
|
150
|
+
def _has_marker_file(project: Path, tool: Tool) -> bool:
|
|
151
|
+
"""Whether one of the tool's marker files exists."""
|
|
152
|
+
return any(((project / filename).is_file() for filename in tool.get('files', [])))
|
|
153
|
+
|
|
154
|
+
def venv_commands(project: Path, tools: dict[str, Tool]) -> list[dict]:
|
|
155
|
+
"""Commands using the tools installed in the project venv."""
|
|
156
|
+
project = Path(project).expanduser().resolve()
|
|
157
|
+
venv = venv_dir(project)
|
|
158
|
+
if not venv.is_dir():
|
|
159
|
+
return []
|
|
160
|
+
try:
|
|
161
|
+
python = str(venv_python(project))
|
|
162
|
+
except FileNotFoundError:
|
|
163
|
+
return []
|
|
164
|
+
installed = _venv_packages(venv)
|
|
165
|
+
return [_command([python, '-m', tools[name].get('module', name)] + args, 'venv', name, tools[name]) for name in tools if name in installed for args in tools[name]['argvs']]
|
|
166
|
+
|
|
167
|
+
def _venv_packages(venv: Path) -> set[str]:
|
|
168
|
+
"""Normalized distribution names in the venv's site-packages."""
|
|
169
|
+
lib = next((d for d in venv.iterdir() if d.name.lower() == 'lib'), None)
|
|
170
|
+
if lib is None:
|
|
171
|
+
return set()
|
|
172
|
+
site_packages = [*lib.glob('*/site-packages'), lib / 'site-packages']
|
|
173
|
+
return {normalize_dep_name(dist.metadata['Name'] or '') for sp in site_packages if sp.is_dir() for dist in importlib.metadata.distributions(path=[str(sp)])}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Tool tables: the Tool shape and dependency-name helpers."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from typing import TypedDict
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
class Tool(TypedDict, total=False):
|
|
8
|
+
"""One tool's run args and config markers; every key has a default."""
|
|
9
|
+
|
|
10
|
+
module: str
|
|
11
|
+
argvs: list[list[str]]
|
|
12
|
+
sections: list[str]
|
|
13
|
+
section_prefixes: list[str]
|
|
14
|
+
ini_sections: list[str]
|
|
15
|
+
files: list[str]
|
|
16
|
+
takes_files: bool
|
|
17
|
+
project_args: list[str]
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def normalize_dep_name(dep: str) -> str:
|
|
21
|
+
"""PEP 503-normalized dependency name, without extras or specifiers."""
|
|
22
|
+
match = re.match(r"[A-Za-z0-9._-]+", dep.strip())
|
|
23
|
+
name = match.group(0) if match else ""
|
|
24
|
+
|
|
25
|
+
return re.sub(r"[-_.]+", "-", name.lower())
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def dependency_names(data: dict) -> list[str]:
|
|
29
|
+
"""PEP 503-normalized dependency names declared in a parsed pyproject."""
|
|
30
|
+
project = data.get("project", {})
|
|
31
|
+
poetry = data.get("tool", {}).get("poetry", {})
|
|
32
|
+
optional = project.get("optional-dependencies", {})
|
|
33
|
+
poetry_groups = poetry.get("group", {})
|
|
34
|
+
|
|
35
|
+
deps = [
|
|
36
|
+
*(dep for group in data.get("dependency-groups", {}).values() for dep in group),
|
|
37
|
+
*project.get("dependencies", []),
|
|
38
|
+
*(dep for group in optional.values() for dep in group),
|
|
39
|
+
*poetry.get("dependencies", {}),
|
|
40
|
+
*(
|
|
41
|
+
dep
|
|
42
|
+
for group in poetry_groups.values()
|
|
43
|
+
for dep in group.get("dependencies", {})
|
|
44
|
+
),
|
|
45
|
+
]
|
|
46
|
+
|
|
47
|
+
return [normalize_dep_name(dep) for dep in deps if isinstance(dep, str)]
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
"""MCP server: watch a project and serve cached lint, typecheck, and test results."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from agent_checks_mcp.agenticpytools import session as sessions
|
|
4
|
+
from agent_checks_mcp.agenticpytools.checks_mcp.instructions import summary
|
|
5
|
+
from agent_checks_mcp.agenticpytools.linter import detect_lint_commands
|
|
6
|
+
from agent_checks_mcp.agenticpytools.session import SESSION_ID_ERROR_MESSAGE
|
|
7
|
+
from agent_checks_mcp.agenticpytools.tester import detect_test_commands
|
|
8
|
+
from agent_checks_mcp.agenticpytools.typechecker import detect_typecheck_commands
|
|
9
|
+
from fastmcp import FastMCP
|
|
10
|
+
EMPTY_SESSION_ID_ERROR = {'error': SESSION_ID_ERROR_MESSAGE}
|
|
11
|
+
mcp = FastMCP(name='checks-mcp', instructions=summary)
|
|
12
|
+
|
|
13
|
+
@mcp.tool
|
|
14
|
+
def start_watching(project_full_path: str, session_id: str) -> dict:
|
|
15
|
+
"""Start watching a project without waiting for checks; returns its detected commands."""
|
|
16
|
+
if not session_id.strip():
|
|
17
|
+
return {**EMPTY_SESSION_ID_ERROR}
|
|
18
|
+
try:
|
|
19
|
+
session = sessions.start(Path(project_full_path), session_id)
|
|
20
|
+
return {'project': session['project'], 'session_id': session_id, 'watching': True, 'commands': sessions.commands(session)}
|
|
21
|
+
except (OSError, ValueError) as exc:
|
|
22
|
+
return {'error': f'failed to start watching: {exc}'}
|
|
23
|
+
|
|
24
|
+
@mcp.tool
|
|
25
|
+
def detected_commands(project_full_path: str, session_id: str) -> dict:
|
|
26
|
+
"""The lint, typecheck, and test commands for a watched session, detected on demand otherwise."""
|
|
27
|
+
if not session_id.strip():
|
|
28
|
+
return {**EMPTY_SESSION_ID_ERROR}
|
|
29
|
+
try:
|
|
30
|
+
session = sessions.get(Path(project_full_path), session_id)
|
|
31
|
+
if session is not None:
|
|
32
|
+
return sessions.commands(session)
|
|
33
|
+
path = Path(project_full_path)
|
|
34
|
+
return {'lint': detect_lint_commands(path), 'typecheck': detect_typecheck_commands(path), 'test': detect_test_commands(path)}
|
|
35
|
+
except (OSError, ValueError) as exc:
|
|
36
|
+
return {'error': f'failed to detect commands: {exc}'}
|
|
37
|
+
|
|
38
|
+
@mcp.tool
|
|
39
|
+
def lint(project_full_path: str, session_id: str) -> dict:
|
|
40
|
+
"""Latest cached lint results for the session; runs lint on demand if not ready."""
|
|
41
|
+
if not session_id.strip():
|
|
42
|
+
return {**EMPTY_SESSION_ID_ERROR}
|
|
43
|
+
try:
|
|
44
|
+
return sessions.lint(Path(project_full_path), session_id)
|
|
45
|
+
except (OSError, ValueError) as exc:
|
|
46
|
+
return {'error': f'failed to run lint: {exc}'}
|
|
47
|
+
|
|
48
|
+
@mcp.tool
|
|
49
|
+
def typecheck(project_full_path: str, session_id: str) -> dict:
|
|
50
|
+
"""Latest cached typecheck results for the session; runs typecheck on demand if not ready."""
|
|
51
|
+
if not session_id.strip():
|
|
52
|
+
return {**EMPTY_SESSION_ID_ERROR}
|
|
53
|
+
try:
|
|
54
|
+
return sessions.run_check(Path(project_full_path), session_id, 'typecheck')
|
|
55
|
+
except (OSError, ValueError) as exc:
|
|
56
|
+
return {'error': f'failed to run typecheck: {exc}'}
|
|
57
|
+
|
|
58
|
+
@mcp.tool
|
|
59
|
+
def test(project_full_path: str, session_id: str) -> dict:
|
|
60
|
+
"""Latest cached test results for the session; runs the tests on demand if not ready."""
|
|
61
|
+
if not session_id.strip():
|
|
62
|
+
return {**EMPTY_SESSION_ID_ERROR}
|
|
63
|
+
try:
|
|
64
|
+
return sessions.run_check(Path(project_full_path), session_id, 'test')
|
|
65
|
+
except (OSError, ValueError) as exc:
|
|
66
|
+
return {'error': f'failed to run tests: {exc}'}
|
|
67
|
+
|
|
68
|
+
@mcp.tool
|
|
69
|
+
def stop_watching(project_full_path: str, session_id: str) -> dict:
|
|
70
|
+
"""Stop watching a project session; the watcher thread exits."""
|
|
71
|
+
if not session_id.strip():
|
|
72
|
+
return {**EMPTY_SESSION_ID_ERROR}
|
|
73
|
+
try:
|
|
74
|
+
stopped = sessions.stop(Path(project_full_path), session_id)
|
|
75
|
+
except (OSError, ValueError) as exc:
|
|
76
|
+
return {'error': f'failed to stop watching: {exc}'}
|
|
77
|
+
if not stopped:
|
|
78
|
+
return {'error': 'no session for this project_full_path/session_id'}
|
|
79
|
+
return {'project': str(Path(project_full_path).expanduser().resolve()), 'session_id': session_id, 'stopped': True}
|
|
80
|
+
|
|
81
|
+
def main() -> None:
|
|
82
|
+
mcp.run()
|
|
83
|
+
if __name__ == '__main__':
|
|
84
|
+
main()
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
"""Instructions for the checks MCP server."""
|
|
2
|
+
|
|
3
|
+
summary = (
|
|
4
|
+
"An MCP server that watches a target project during an agent session. "
|
|
5
|
+
"Every tool takes project_full_path and session_id. "
|
|
6
|
+
"Call start_watching(project_full_path, session_id) once per session; it "
|
|
7
|
+
"returns at once with the detected commands, without check results, while "
|
|
8
|
+
"the initial lint, typecheck, and test runs continue in the background. "
|
|
9
|
+
"Then lint(project_full_path, session_id), typecheck(project_full_path, "
|
|
10
|
+
"session_id), and test(project_full_path, session_id) return the cached "
|
|
11
|
+
"lint, typecheck, and test results when a ready result exists, otherwise "
|
|
12
|
+
"run the commands on demand and return the result; no session required. "
|
|
13
|
+
'Each result\'s "running" flag covers only that check kind: while a run of '
|
|
14
|
+
"the kind is scheduled or in progress, they return the previous result, or "
|
|
15
|
+
'a placeholder without results, with "running": true; call again later. '
|
|
16
|
+
"A failed or cancelled run returns an entry without results and a note, "
|
|
17
|
+
"and is not retried until files change or a new session starts. "
|
|
18
|
+
'Results include an "origin" field: "watcher" | "initial" | "on-demand" '
|
|
19
|
+
'(| "none" when no commands of that kind were detected), indicating '
|
|
20
|
+
"whether the watcher already ran them or they ran on demand. "
|
|
21
|
+
"detected_commands(project_full_path, session_id) returns the watched "
|
|
22
|
+
"session's lint, typecheck, and test commands, or detects them on "
|
|
23
|
+
"demand without a watcher. "
|
|
24
|
+
"stop_watching(project_full_path, session_id) stops the watcher and "
|
|
25
|
+
"removes the session."
|
|
26
|
+
)
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
"""Project environment helpers: venv paths, interpreter lookup, tool detection, OS checks."""
|
|
2
|
+
from agent_checks_mcp.agenticpytools.environment.core import is_uv, is_windows, venv_dir, venv_python
|
|
3
|
+
from agent_checks_mcp.agenticpytools.environment.tools import dotted_keys, project_tool
|
|
4
|
+
__all__ = ['dotted_keys', 'is_uv', 'is_windows', 'project_tool', 'venv_dir', 'venv_python']
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import shutil
|
|
3
|
+
from pathlib import Path
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def is_windows() -> bool:
|
|
7
|
+
return os.name == "nt"
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def windows_venv(venv_dir: Path) -> Path:
|
|
11
|
+
return venv_dir / "Scripts" / "python.exe"
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def expected_venv_python(venv_dir: Path) -> Path:
|
|
15
|
+
return windows_venv(venv_dir) if is_windows() else venv_dir / "bin" / "python"
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def venv_dir(project: str | Path) -> Path:
|
|
19
|
+
"""The project's virtual environment directory."""
|
|
20
|
+
return Path(project) / ".venv"
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def venv_python(project_path: str | Path) -> Path:
|
|
24
|
+
"""Find the Python interpreter of the project's venv."""
|
|
25
|
+
project = Path(project_path).expanduser().resolve()
|
|
26
|
+
|
|
27
|
+
venv = venv_dir(project)
|
|
28
|
+
venv_python_candidate = expected_venv_python(venv)
|
|
29
|
+
|
|
30
|
+
if venv_python_candidate.exists():
|
|
31
|
+
return venv_python_candidate
|
|
32
|
+
|
|
33
|
+
raise FileNotFoundError(f"No virtual environment found in {project}")
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def is_uv(project: Path) -> bool:
|
|
37
|
+
has_uv = shutil.which("uv") is not None
|
|
38
|
+
lock_file = project / "uv.lock"
|
|
39
|
+
|
|
40
|
+
return has_uv and lock_file.exists()
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""Project package-manager detection: uv, pixi, pdm, poetry, hatch."""
|
|
2
|
+
|
|
3
|
+
import shutil
|
|
4
|
+
import tomllib
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
PROJECT_TOOLS = (
|
|
8
|
+
("uv", "uv.lock", "tool.uv", "uv", ["uv", "run"]),
|
|
9
|
+
("pixi", "pixi.lock", "tool.pixi", "pixi", ["pixi", "run"]),
|
|
10
|
+
("pdm", "pdm.lock", "tool.pdm", "pdm", ["pdm", "run"]),
|
|
11
|
+
("poetry", "poetry.lock", "tool.poetry", "poetry", ["poetry", "run"]),
|
|
12
|
+
("hatch", None, "tool.hatch", "hatch", ["hatch", "run"]),
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def dotted_keys(table: dict) -> set[str]:
|
|
17
|
+
"""Dotted keys of nested tables, e.g. 'tool.uv' for [tool.uv]."""
|
|
18
|
+
keys = set(table)
|
|
19
|
+
|
|
20
|
+
for key, value in table.items():
|
|
21
|
+
if isinstance(value, dict):
|
|
22
|
+
keys |= {f"{key}.{nested}" for nested in dotted_keys(value)}
|
|
23
|
+
|
|
24
|
+
return keys
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _pyproject_sections(project: Path) -> set[str]:
|
|
28
|
+
"""Dotted table keys in the project's pyproject.toml."""
|
|
29
|
+
try:
|
|
30
|
+
with (project / "pyproject.toml").open("rb") as file:
|
|
31
|
+
data = tomllib.load(file)
|
|
32
|
+
except (FileNotFoundError, tomllib.TOMLDecodeError):
|
|
33
|
+
return set()
|
|
34
|
+
|
|
35
|
+
return dotted_keys(data)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _tool_source(
|
|
39
|
+
project: Path, lock: str | None, section: str, sections: set[str]
|
|
40
|
+
) -> str | None:
|
|
41
|
+
"""The marker that makes a tool a candidate: its lockfile or pyproject section."""
|
|
42
|
+
if lock is not None and (project / lock).exists():
|
|
43
|
+
return lock
|
|
44
|
+
|
|
45
|
+
return section if section in sections else None
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def project_tool(project: Path) -> dict | None:
|
|
49
|
+
"""The project's package manager, from its lockfile or a pyproject section."""
|
|
50
|
+
sections = _pyproject_sections(project)
|
|
51
|
+
|
|
52
|
+
for name, lock, section, binary, prefix in PROJECT_TOOLS:
|
|
53
|
+
source = _tool_source(project, lock, section, sections)
|
|
54
|
+
|
|
55
|
+
if source is not None and shutil.which(binary) is not None:
|
|
56
|
+
return {"tool": name, "prefix": list(prefix), "source": source}
|
|
57
|
+
|
|
58
|
+
return None
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Lint command detection for a project, from justfile down to the venv."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from agent_checks_mcp.agenticpytools.checks import detect_commands
|
|
4
|
+
from .tools import LINTERS
|
|
5
|
+
|
|
6
|
+
def detect_lint_commands(project: Path) -> list[dict]:
|
|
7
|
+
"""Lint commands from the first source that finds any, in ladder order."""
|
|
8
|
+
return detect_commands(project, LINTERS, ('lint',))
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"""Linter tools: argvs and config markers."""
|
|
2
|
+
from agent_checks_mcp.agenticpytools.checks.tools import Tool
|
|
3
|
+
LINTERS: dict[str, Tool] = {'ruff': {'argvs': [['check'], ['format', '--check']], 'sections': ['tool.ruff'], 'files': ['ruff.toml', '.ruff.toml'], 'takes_files': True}, 'flake8': {'argvs': [[]], 'ini_sections': ['flake8'], 'files': ['.flake8'], 'takes_files': True}, 'pylint': {'argvs': [['.']], 'section_prefixes': ['tool.pylint'], 'files': ['.pylintrc', 'pylintrc'], 'takes_files': True, 'project_args': ['.']}, 'black': {'argvs': [['--check', '.']], 'sections': ['tool.black'], 'takes_files': True, 'project_args': ['.']}, 'isort': {'argvs': [['--check-only', '.']], 'sections': ['tool.isort'], 'takes_files': True, 'project_args': ['.']}}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Run detected command dicts as subprocesses."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
import subprocess
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def run_commands(
|
|
8
|
+
commands: list[dict], files: list[str] | None = None, timeout: float = 60.0
|
|
9
|
+
) -> list[dict]:
|
|
10
|
+
"""Run each command, appending changed files when the tool takes them."""
|
|
11
|
+
return [_run_one(cmd, files, timeout) for cmd in commands]
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def _argv(cmd: dict, files: list[str] | None) -> list[str]:
|
|
15
|
+
"""The command's argv, with changed files replacing its declared project args."""
|
|
16
|
+
argv = list(cmd["argv"])
|
|
17
|
+
|
|
18
|
+
if not (files and cmd.get("takes_files")):
|
|
19
|
+
return argv
|
|
20
|
+
|
|
21
|
+
project_args = list(cmd.get("project_args", []))
|
|
22
|
+
size = len(project_args)
|
|
23
|
+
|
|
24
|
+
if size and argv[-size:] == project_args:
|
|
25
|
+
argv = argv[:-size]
|
|
26
|
+
|
|
27
|
+
return argv + [str(f) for f in files]
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _run_one(cmd: dict, files: list[str] | None, timeout: float) -> dict:
|
|
31
|
+
"""One command's result: argv, returncode, stdout, and stderr."""
|
|
32
|
+
argv = _argv(cmd, files)
|
|
33
|
+
|
|
34
|
+
try:
|
|
35
|
+
proc = subprocess.run(
|
|
36
|
+
argv,
|
|
37
|
+
cwd=cmd.get("cwd"),
|
|
38
|
+
env=_child_env(),
|
|
39
|
+
capture_output=True,
|
|
40
|
+
check=False,
|
|
41
|
+
text=True,
|
|
42
|
+
timeout=timeout,
|
|
43
|
+
)
|
|
44
|
+
return _result(argv, proc.returncode, proc.stdout, proc.stderr)
|
|
45
|
+
except FileNotFoundError:
|
|
46
|
+
return _result(argv, 127, "", f"command not found: {argv[0]}")
|
|
47
|
+
except subprocess.TimeoutExpired as exc:
|
|
48
|
+
stderr = _decoded(exc.stderr) or f"timed out after {timeout}s"
|
|
49
|
+
|
|
50
|
+
return _result(argv, 124, _decoded(exc.stdout), stderr)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
STRIPPED_ENV_VARS = frozenset(
|
|
54
|
+
{
|
|
55
|
+
"VIRTUAL_ENV",
|
|
56
|
+
"CONDA_PREFIX",
|
|
57
|
+
"CONDA_DEFAULT_ENV",
|
|
58
|
+
"PYTHONHOME",
|
|
59
|
+
"PYTHONPATH",
|
|
60
|
+
"POETRY_VIRTUALENVS_PATH",
|
|
61
|
+
"UV_PROJECT_ENVIRONMENT",
|
|
62
|
+
}
|
|
63
|
+
)
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def _child_env() -> dict:
|
|
67
|
+
"""Environment for child tools: the caller's activated venv must not leak into the target project."""
|
|
68
|
+
return {k: v for k, v in os.environ.items() if k not in STRIPPED_ENV_VARS}
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _result(argv: list[str], returncode: int, stdout: str, stderr: str) -> dict:
|
|
72
|
+
"""A command's result dict."""
|
|
73
|
+
return {
|
|
74
|
+
"argv": argv,
|
|
75
|
+
"returncode": returncode,
|
|
76
|
+
"stdout": stdout,
|
|
77
|
+
"stderr": stderr,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def _decoded(output: str | bytes | None) -> str:
|
|
82
|
+
"""Partial timeout output as text; bytes are decoded, None is empty."""
|
|
83
|
+
if isinstance(output, bytes):
|
|
84
|
+
return output.decode()
|
|
85
|
+
|
|
86
|
+
return output or ""
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"""Session state for watching a project during an agent session."""
|
|
2
|
+
from agent_checks_mcp.agenticpytools.session.core import KINDS, SESSION_ID_ERROR_MESSAGE, commands, get, latest, lint, run_check, start, stop
|
|
3
|
+
__all__ = ['KINDS', 'SESSION_ID_ERROR_MESSAGE', 'commands', 'get', 'latest', 'lint', 'run_check', 'start', 'stop']
|
|
@@ -0,0 +1,223 @@
|
|
|
1
|
+
"""Session state: background watching of a project's check commands."""
|
|
2
|
+
import json
|
|
3
|
+
import threading
|
|
4
|
+
from collections.abc import Callable
|
|
5
|
+
from concurrent.futures import ThreadPoolExecutor
|
|
6
|
+
from datetime import UTC, datetime
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from agent_checks_mcp.agenticpytools.linter import detect_lint_commands
|
|
9
|
+
from agent_checks_mcp.agenticpytools.runner import run_commands
|
|
10
|
+
from agent_checks_mcp.agenticpytools.tester import detect_test_commands
|
|
11
|
+
from agent_checks_mcp.agenticpytools.typechecker import detect_typecheck_commands
|
|
12
|
+
from agent_checks_mcp.agenticpytools.watcher import changed_python_files
|
|
13
|
+
KINDS = ('lint', 'typecheck', 'test')
|
|
14
|
+
DETECTORS = {'lint': detect_lint_commands, 'typecheck': detect_typecheck_commands, 'test': detect_test_commands}
|
|
15
|
+
SESSION_ID_ERROR_MESSAGE = 'session_id must be a non-empty string'
|
|
16
|
+
_SESSIONS: dict[str, dict] = {}
|
|
17
|
+
_LOCK = threading.Lock()
|
|
18
|
+
|
|
19
|
+
def _session_key(project: Path, session_id: str) -> str:
|
|
20
|
+
"""Registry key of a session watching a project."""
|
|
21
|
+
if not session_id.strip():
|
|
22
|
+
raise ValueError(SESSION_ID_ERROR_MESSAGE)
|
|
23
|
+
return json.dumps([session_id, str(Path(project).expanduser().resolve())])
|
|
24
|
+
|
|
25
|
+
def start(project: Path, session_id: str, run: Callable[..., list[dict]] | None=None) -> dict:
|
|
26
|
+
"""Start watching a project without waiting for checks; idempotent per session."""
|
|
27
|
+
if run is None:
|
|
28
|
+
run = run_commands
|
|
29
|
+
path = Path(project).expanduser().resolve()
|
|
30
|
+
key = _session_key(project, session_id)
|
|
31
|
+
with _LOCK:
|
|
32
|
+
if key in _SESSIONS:
|
|
33
|
+
return _SESSIONS[key]
|
|
34
|
+
detected = {kind: DETECTORS[kind](path) for kind in KINDS}
|
|
35
|
+
kinds = tuple((kind for kind in KINDS if detected[kind]))
|
|
36
|
+
session = {'project': str(path), 'commands': detected, 'latest': {}, 'pending': {kind: int(kind in kinds) for kind in KINDS}, 'thread': None, 'stop': threading.Event()}
|
|
37
|
+
thread = threading.Thread(target=_run_in_background, args=(session, run, kinds), daemon=True)
|
|
38
|
+
session['thread'] = thread
|
|
39
|
+
thread.start()
|
|
40
|
+
_SESSIONS[key] = session
|
|
41
|
+
return session
|
|
42
|
+
|
|
43
|
+
def _run_in_background(session: dict, run: Callable[..., list[dict]], kinds: tuple[str, ...]) -> None:
|
|
44
|
+
"""Warm the caches with the initial runs, then rerun on file changes."""
|
|
45
|
+
_run_batch(session, run, None, kinds)
|
|
46
|
+
_watch(session, run)
|
|
47
|
+
|
|
48
|
+
def _default_entry(kind: str) -> dict:
|
|
49
|
+
"""Placeholder entry for a kind with no cached run yet."""
|
|
50
|
+
return {'kind': kind, 'results': None, 'ran_at': None, 'changed_files': [], 'ok': None, 'origin': None}
|
|
51
|
+
|
|
52
|
+
def _latest_entry(kind: str, results: list[dict] | None, files: list[str], origin: str) -> dict:
|
|
53
|
+
"""One cache entry for a finished run of a command kind."""
|
|
54
|
+
ok = all((r['returncode'] == 0 for r in results)) if results is not None else None
|
|
55
|
+
return {'kind': kind, 'results': results, 'ran_at': datetime.now(UTC).isoformat(), 'changed_files': list(files), 'ok': ok, 'origin': origin}
|
|
56
|
+
|
|
57
|
+
def _outcome_entry(job: dict, ok: bool | None, note: str) -> dict:
|
|
58
|
+
"""Cache entry for a run without results, such as a failed or cancelled one."""
|
|
59
|
+
entry = _latest_entry(job['kind'], None, job['changed_files'], job['origin'])
|
|
60
|
+
return {**entry, 'ok': ok, 'note': note}
|
|
61
|
+
|
|
62
|
+
def _run_job(run: Callable[..., list[dict]], cmds: list[dict], files: list[str] | None, job: dict) -> dict:
|
|
63
|
+
"""Run a kind's commands into a cache entry; a raising run becomes a failed entry."""
|
|
64
|
+
try:
|
|
65
|
+
results = run(cmds, files=files)
|
|
66
|
+
except Exception as exc:
|
|
67
|
+
return _outcome_entry(job, False, f"{job['kind']} run failed: {exc}")
|
|
68
|
+
return _latest_entry(job['kind'], results, job['changed_files'], job['origin'])
|
|
69
|
+
|
|
70
|
+
def _is_newer(entry: dict, existing: dict) -> bool:
|
|
71
|
+
"""True when the given entry ran at or after the cached one."""
|
|
72
|
+
return (existing.get('ran_at') or '') <= (entry.get('ran_at') or '')
|
|
73
|
+
|
|
74
|
+
def _is_running(session: dict, kind: str) -> bool:
|
|
75
|
+
"""True while a run of the kind is scheduled or in progress; call under _LOCK."""
|
|
76
|
+
return session['pending'][kind] > 0
|
|
77
|
+
|
|
78
|
+
def _mark_pending(session: dict) -> tuple[str, ...]:
|
|
79
|
+
"""Mark every kind with commands as pending, unless the session is stopping."""
|
|
80
|
+
with _LOCK:
|
|
81
|
+
if session['stop'].is_set():
|
|
82
|
+
return ()
|
|
83
|
+
kinds = tuple((kind for kind in KINDS if session['commands'][kind]))
|
|
84
|
+
for kind in kinds:
|
|
85
|
+
session['pending'][kind] += 1
|
|
86
|
+
return kinds
|
|
87
|
+
|
|
88
|
+
def _publish(session: dict, entry: dict) -> None:
|
|
89
|
+
"""Cache the newer entry per kind and release one pending run of that kind."""
|
|
90
|
+
kind = entry['kind']
|
|
91
|
+
with _LOCK:
|
|
92
|
+
existing = session['latest'].get(kind)
|
|
93
|
+
if existing is None or _is_newer(entry, existing):
|
|
94
|
+
session['latest'][kind] = entry
|
|
95
|
+
session['pending'][kind] = max(session['pending'][kind] - 1, 0)
|
|
96
|
+
|
|
97
|
+
def _watch(session: dict, run: Callable[..., list[dict]]) -> None:
|
|
98
|
+
"""Rerun the check commands whenever watched Python files change."""
|
|
99
|
+
for batch in changed_python_files(Path(session['project']), stop_event=session['stop']):
|
|
100
|
+
if session['stop'].is_set():
|
|
101
|
+
break
|
|
102
|
+
_run_batch(session, run, batch, _mark_pending(session))
|
|
103
|
+
|
|
104
|
+
def _existing_files(project: str, batch: list[str]) -> list[str] | None:
|
|
105
|
+
"""The batch's files that still exist; None runs on the whole project."""
|
|
106
|
+
existing = [f for f in batch if (Path(project) / f).is_file()]
|
|
107
|
+
return existing or None
|
|
108
|
+
|
|
109
|
+
def _run_batch(session: dict, run: Callable[..., list[dict]], batch: list[str] | None, kinds: tuple[str, ...]) -> None:
|
|
110
|
+
"""Run the pending kinds once, publishing each outcome as it finishes.
|
|
111
|
+
|
|
112
|
+
A watcher batch runs on its changed files; a None batch is the initial run.
|
|
113
|
+
"""
|
|
114
|
+
files = _existing_files(session['project'], batch) if batch else None
|
|
115
|
+
origin = 'watcher' if batch else 'initial'
|
|
116
|
+
|
|
117
|
+
def run_kind(kind: str) -> None:
|
|
118
|
+
job = {'kind': kind, 'changed_files': batch or [], 'origin': origin}
|
|
119
|
+
if session['stop'].is_set():
|
|
120
|
+
entry = _outcome_entry(job, None, f'{kind} run cancelled: session stopped')
|
|
121
|
+
else:
|
|
122
|
+
entry = _run_job(run, session['commands'][kind], files, job)
|
|
123
|
+
_publish(session, entry)
|
|
124
|
+
with ThreadPoolExecutor(max_workers=len(KINDS)) as executor:
|
|
125
|
+
list(executor.map(run_kind, kinds))
|
|
126
|
+
|
|
127
|
+
def latest(session: dict, kind: str='lint') -> dict:
|
|
128
|
+
"""The latest cached entry for a kind, with that kind's running flag."""
|
|
129
|
+
with _LOCK:
|
|
130
|
+
entry = session['latest'].get(kind) or _default_entry(kind)
|
|
131
|
+
return {**entry, 'running': _is_running(session, kind)}
|
|
132
|
+
|
|
133
|
+
def _served_entry(session: dict, kind: str) -> dict | None:
|
|
134
|
+
"""The response to serve now, or None when nothing is cached or in flight.
|
|
135
|
+
|
|
136
|
+
A completed run is served as is, including a failed or cancelled one, so it is
|
|
137
|
+
never retried on demand. Call under _LOCK.
|
|
138
|
+
"""
|
|
139
|
+
entry = session['latest'].get(kind)
|
|
140
|
+
running = _is_running(session, kind)
|
|
141
|
+
if entry is not None:
|
|
142
|
+
return {**entry, 'running': running}
|
|
143
|
+
if running:
|
|
144
|
+
return {**_default_entry(kind), 'running': True}
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
def _serve(session: dict, kind: str) -> dict | None:
|
|
148
|
+
"""The response to serve now, or None when nothing is cached or in flight."""
|
|
149
|
+
with _LOCK:
|
|
150
|
+
return _served_entry(session, kind)
|
|
151
|
+
|
|
152
|
+
def _claim(key: str, session: dict, kind: str) -> tuple[dict | None, bool]:
|
|
153
|
+
"""The response to serve now, and whether a new on-demand run was claimed.
|
|
154
|
+
|
|
155
|
+
A stopped or replaced session serves nothing and claims nothing.
|
|
156
|
+
"""
|
|
157
|
+
with _LOCK:
|
|
158
|
+
if _SESSIONS.get(key) is not session or session['stop'].is_set():
|
|
159
|
+
return (None, False)
|
|
160
|
+
served = _served_entry(session, kind)
|
|
161
|
+
if served is None:
|
|
162
|
+
session['pending'][kind] += 1
|
|
163
|
+
return (served, served is None)
|
|
164
|
+
|
|
165
|
+
def _detect(path: Path, kind: str) -> list[dict]:
|
|
166
|
+
"""The kind's commands detected for a project."""
|
|
167
|
+
return DETECTORS.get(kind, lambda p: [])(path)
|
|
168
|
+
|
|
169
|
+
def _run_unclaimed(run: Callable[..., list[dict]], cmds: list[dict], job: dict) -> dict:
|
|
170
|
+
"""Run commands outside any session, or note that none were detected."""
|
|
171
|
+
if not cmds:
|
|
172
|
+
return {**_default_entry(job['kind']), 'origin': 'none', 'running': False, 'note': f"no {job['kind']} commands detected for project"}
|
|
173
|
+
return {**_run_job(run, cmds, None, job), 'running': False}
|
|
174
|
+
|
|
175
|
+
def run_check(project: Path, session_id: str, kind: str, run: Callable[..., list[dict]] | None=None) -> dict:
|
|
176
|
+
"""Latest cached entry for a kind if ready; otherwise detect and run now."""
|
|
177
|
+
if run is None:
|
|
178
|
+
run = run_commands
|
|
179
|
+
path = Path(project).expanduser().resolve()
|
|
180
|
+
key = _session_key(project, session_id)
|
|
181
|
+
with _LOCK:
|
|
182
|
+
session = _SESSIONS.get(key)
|
|
183
|
+
served = _serve(session, kind) if session else None
|
|
184
|
+
if served is not None:
|
|
185
|
+
return served
|
|
186
|
+
session_cmds = session['commands'].get(kind) if session else []
|
|
187
|
+
cmds = session_cmds or _detect(path, kind)
|
|
188
|
+
job = {'kind': kind, 'changed_files': [], 'origin': 'on-demand'}
|
|
189
|
+
if session is None or not cmds:
|
|
190
|
+
return _run_unclaimed(run, cmds, job)
|
|
191
|
+
served, claimed = _claim(key, session, kind)
|
|
192
|
+
if served is not None:
|
|
193
|
+
return served
|
|
194
|
+
if not claimed:
|
|
195
|
+
return _run_unclaimed(run, _detect(path, kind), job)
|
|
196
|
+
_publish(session, _run_job(run, cmds, None, job))
|
|
197
|
+
return latest(session, kind)
|
|
198
|
+
|
|
199
|
+
def lint(project: Path, session_id: str, run: Callable[..., list[dict]] | None=None) -> dict:
|
|
200
|
+
"""Latest cached lint entry if ready; otherwise detect and run lint now."""
|
|
201
|
+
return run_check(project, session_id, 'lint', run)
|
|
202
|
+
|
|
203
|
+
def commands(session: dict) -> dict:
|
|
204
|
+
"""The commands detected for the session's project."""
|
|
205
|
+
return session['commands']
|
|
206
|
+
|
|
207
|
+
def get(project: Path, session_id: str) -> dict | None:
|
|
208
|
+
"""The session watching a project for a session_id, if any."""
|
|
209
|
+
with _LOCK:
|
|
210
|
+
return _SESSIONS.get(_session_key(project, session_id))
|
|
211
|
+
|
|
212
|
+
def stop(project: Path, session_id: str) -> bool:
|
|
213
|
+
"""Stop a session's background runs and watcher and remove it; False when no session exists."""
|
|
214
|
+
key = _session_key(project, session_id)
|
|
215
|
+
with _LOCK:
|
|
216
|
+
session = _SESSIONS.pop(key, None)
|
|
217
|
+
if session is None:
|
|
218
|
+
return False
|
|
219
|
+
session['stop'].set()
|
|
220
|
+
thread = session['thread']
|
|
221
|
+
if thread is not None:
|
|
222
|
+
thread.join(timeout=5)
|
|
223
|
+
return True
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Test command detection for a project, from justfile down to the venv."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from agent_checks_mcp.agenticpytools.checks import detect_commands
|
|
4
|
+
from .tools import TEST_TOOLS
|
|
5
|
+
|
|
6
|
+
def detect_test_commands(project: Path) -> list[dict]:
|
|
7
|
+
"""Test commands from the first source that finds any, in ladder order."""
|
|
8
|
+
return detect_commands(project, TEST_TOOLS, ('test', 'tests'))
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"""Test tools: argvs and config markers."""
|
|
2
|
+
from agent_checks_mcp.agenticpytools.checks.tools import Tool
|
|
3
|
+
TEST_TOOLS: dict[str, Tool] = {'pytest': {'argvs': [[]], 'sections': ['tool.pytest.ini_options'], 'ini_sections': ['pytest', 'tool:pytest'], 'files': ['pytest.ini']}, 'tox': {'argvs': [[]], 'ini_sections': ['testenv'], 'files': ['tox.ini']}, 'nox': {'argvs': [[]], 'files': ['noxfile.py']}}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
"""Type check command detection for a project, from justfile down to the venv."""
|
|
2
|
+
from pathlib import Path
|
|
3
|
+
from agent_checks_mcp.agenticpytools.checks import detect_commands
|
|
4
|
+
from .tools import TYPE_CHECKERS
|
|
5
|
+
|
|
6
|
+
def detect_typecheck_commands(project: Path) -> list[dict]:
|
|
7
|
+
"""Type check commands from the first source that finds any, in ladder order."""
|
|
8
|
+
return detect_commands(project, TYPE_CHECKERS, ('typecheck', 'type-check', 'types'))
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
"""Type checker tools: argvs and config markers."""
|
|
2
|
+
from agent_checks_mcp.agenticpytools.checks.tools import Tool
|
|
3
|
+
TYPE_CHECKERS: dict[str, Tool] = {'mypy': {'argvs': [['.']], 'sections': ['tool.mypy'], 'ini_sections': ['mypy'], 'files': ['mypy.ini', '.mypy.ini'], 'takes_files': True, 'project_args': ['.']}, 'ty': {'argvs': [['check']], 'sections': ['tool.ty'], 'takes_files': True}, 'pyright': {'argvs': [[]], 'sections': ['tool.pyright'], 'takes_files': True}}
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""Debounced batches of changed Python files in a project."""
|
|
2
|
+
|
|
3
|
+
import threading
|
|
4
|
+
import time
|
|
5
|
+
from collections.abc import Iterable, Iterator
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
IGNORED_DIR_NAMES = {
|
|
9
|
+
".venv",
|
|
10
|
+
".git",
|
|
11
|
+
"__pycache__",
|
|
12
|
+
".ruff_cache",
|
|
13
|
+
".pytest_cache",
|
|
14
|
+
".mypy_cache",
|
|
15
|
+
".tox",
|
|
16
|
+
".nox",
|
|
17
|
+
"node_modules",
|
|
18
|
+
"dist",
|
|
19
|
+
"build",
|
|
20
|
+
".eggs",
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def changed_python_files(
|
|
25
|
+
project: Path, debounce: float = 0.5, stop_event: threading.Event | None = None
|
|
26
|
+
) -> Iterator[list[str]]:
|
|
27
|
+
"""Yield debounced batches of changed .py paths until stop_event is set."""
|
|
28
|
+
path = Path(project).expanduser().resolve()
|
|
29
|
+
|
|
30
|
+
return _watchfiles_events(path, debounce, stop_event)
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _ignored_dir(name: str) -> bool:
|
|
34
|
+
"""True for directory names that are never watched."""
|
|
35
|
+
return name in IGNORED_DIR_NAMES or name.endswith(".egg-info")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _is_ignored(path: Path, project: Path) -> bool:
|
|
39
|
+
"""True when any part of the path below the project is an ignored directory."""
|
|
40
|
+
try:
|
|
41
|
+
parts = path.relative_to(project).parts
|
|
42
|
+
except ValueError:
|
|
43
|
+
return False
|
|
44
|
+
|
|
45
|
+
return any(_ignored_dir(part) for part in parts)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _relative(path: Path, project: Path) -> str | None:
|
|
49
|
+
"""Relative posix path for a watched .py file, else None."""
|
|
50
|
+
if path.name.endswith(".py") and not _is_ignored(path, project):
|
|
51
|
+
return path.relative_to(project).as_posix()
|
|
52
|
+
|
|
53
|
+
return None
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _watched_paths(
|
|
57
|
+
events: Iterable[Iterable[tuple[int, str]]], project: Path
|
|
58
|
+
) -> Iterator[set[str]]:
|
|
59
|
+
"""Each watchfiles event batch as a set of relative watched .py paths."""
|
|
60
|
+
for changes in events:
|
|
61
|
+
yield {
|
|
62
|
+
relative
|
|
63
|
+
for _, changed in changes
|
|
64
|
+
if (relative := _relative(Path(changed), project)) is not None
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _watchfiles_events(
|
|
69
|
+
project: Path, debounce: float, stop_event: threading.Event | None = None
|
|
70
|
+
) -> Iterator[list[str]]:
|
|
71
|
+
"""Yield sorted batches of changed .py paths after events stay quiet."""
|
|
72
|
+
from watchfiles import watch
|
|
73
|
+
|
|
74
|
+
events = watch(
|
|
75
|
+
str(project),
|
|
76
|
+
watch_filter=None,
|
|
77
|
+
debounce=50,
|
|
78
|
+
step=50,
|
|
79
|
+
rust_timeout=100,
|
|
80
|
+
yield_on_timeout=True,
|
|
81
|
+
stop_event=stop_event,
|
|
82
|
+
)
|
|
83
|
+
batch: set[str] = set()
|
|
84
|
+
deadline = 0.0
|
|
85
|
+
|
|
86
|
+
for paths in _watched_paths(events, project):
|
|
87
|
+
now = time.monotonic()
|
|
88
|
+
|
|
89
|
+
if batch and now >= deadline:
|
|
90
|
+
yield sorted(batch)
|
|
91
|
+
batch = set()
|
|
92
|
+
|
|
93
|
+
batch |= paths
|
|
94
|
+
deadline = now + debounce if paths else deadline
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling", "hatch-polylith-bricks"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "agent-checks-mcp"
|
|
7
|
+
version = "0.0.1"
|
|
8
|
+
description = "An MCP server that watches a project and serves cached lint, typecheck, and test results"
|
|
9
|
+
authors = [{ name = "David Vujic" }]
|
|
10
|
+
repository = "https://github.com/DavidVujic/agentic-python-tools"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
readme = "README.md"
|
|
13
|
+
|
|
14
|
+
requires-python = ">=3.12"
|
|
15
|
+
dependencies = ["fastmcp", "watchfiles"]
|
|
16
|
+
|
|
17
|
+
[project.scripts]
|
|
18
|
+
agent-checks-mcp = "agent_checks_mcp.agenticpytools.checks_mcp.core:main"
|
|
19
|
+
|
|
20
|
+
[tool.hatch.build.hooks.polylith-bricks]
|
|
21
|
+
|
|
22
|
+
[tool.hatch.build.targets.wheel]
|
|
23
|
+
packages = ["agent_checks_mcp"]
|
|
24
|
+
|
|
25
|
+
[tool.polylith.build]
|
|
26
|
+
top-namespace = "agent_checks_mcp"
|
|
27
|
+
|
|
28
|
+
[tool.polylith.bricks]
|
|
29
|
+
"../../bases/agenticpytools/checks_mcp" = "agenticpytools/checks_mcp"
|
|
30
|
+
"../../components/agenticpytools/checks" = "agenticpytools/checks"
|
|
31
|
+
"../../components/agenticpytools/environment" = "agenticpytools/environment"
|
|
32
|
+
"../../components/agenticpytools/linter" = "agenticpytools/linter"
|
|
33
|
+
"../../components/agenticpytools/runner" = "agenticpytools/runner"
|
|
34
|
+
"../../components/agenticpytools/session" = "agenticpytools/session"
|
|
35
|
+
"../../components/agenticpytools/tester" = "agenticpytools/tester"
|
|
36
|
+
"../../components/agenticpytools/typechecker" = "agenticpytools/typechecker"
|
|
37
|
+
"../../components/agenticpytools/watcher" = "agenticpytools/watcher"
|