@voidh4x0r/slopgate 0.0.0-stage → 0.1.0
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.
- package/CHANGELOG.md +58 -0
- package/LICENSE +21 -0
- package/README.md +266 -2
- package/dist/ast.d.ts +29 -0
- package/dist/ast.js +3 -0
- package/dist/baseline.d.ts +33 -0
- package/dist/baseline.js +104 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +481 -0
- package/dist/config.d.ts +25 -0
- package/dist/config.js +90 -0
- package/dist/data/python-stdlib.d.ts +19 -0
- package/dist/data/python-stdlib.js +75 -0
- package/dist/deps.d.ts +8 -0
- package/dist/deps.js +379 -0
- package/dist/diff.d.ts +30 -0
- package/dist/diff.js +179 -0
- package/dist/engine.d.ts +15 -0
- package/dist/engine.js +179 -0
- package/dist/files.d.ts +32 -0
- package/dist/files.js +168 -0
- package/dist/mcp.d.ts +41 -0
- package/dist/mcp.js +226 -0
- package/dist/parser.d.ts +3 -0
- package/dist/parser.js +41 -0
- package/dist/reporters/github.d.ts +2 -0
- package/dist/reporters/github.js +44 -0
- package/dist/reporters/json.d.ts +10 -0
- package/dist/reporters/json.js +36 -0
- package/dist/reporters/pretty.d.ts +12 -0
- package/dist/reporters/pretty.js +103 -0
- package/dist/reporters/sarif.d.ts +2 -0
- package/dist/reporters/sarif.js +70 -0
- package/dist/rules/helpers.d.ts +43 -0
- package/dist/rules/helpers.js +163 -0
- package/dist/rules/index.d.ts +3 -0
- package/dist/rules/index.js +4 -0
- package/dist/rules/python.d.ts +2 -0
- package/dist/rules/python.js +591 -0
- package/dist/rules/typescript.d.ts +2 -0
- package/dist/rules/typescript.js +497 -0
- package/dist/suppress.d.ts +12 -0
- package/dist/suppress.js +52 -0
- package/dist/types.d.ts +88 -0
- package/dist/types.js +1 -0
- package/grammars/README.md +28 -0
- package/grammars/tree-sitter-python.wasm +0 -0
- package/grammars/tree-sitter-tsx.wasm +0 -0
- package/grammars/tree-sitter-typescript.wasm +0 -0
- package/package.json +61 -4
package/dist/engine.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { readFile, stat } from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
import { asAst } from "./ast.js";
|
|
4
|
+
import { loadProjectDeps } from "./deps.js";
|
|
5
|
+
import { discoverFiles } from "./files.js";
|
|
6
|
+
import { getParser } from "./parser.js";
|
|
7
|
+
import { ALL_RULES, RULE_BY_ID } from "./rules/index.js";
|
|
8
|
+
import { isSuppressed, readSuppressions } from "./suppress.js";
|
|
9
|
+
function collectLocalPythonModules(files, deps) {
|
|
10
|
+
const valid = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
11
|
+
for (const file of files) {
|
|
12
|
+
if (file.language !== 'python')
|
|
13
|
+
continue;
|
|
14
|
+
const parts = file.rel.split('/');
|
|
15
|
+
const fileName = parts.pop() ?? '';
|
|
16
|
+
for (const dir of parts) {
|
|
17
|
+
if (valid.test(dir))
|
|
18
|
+
deps.python.localModules.add(dir);
|
|
19
|
+
}
|
|
20
|
+
// Every module stem, not just top-level ones: packages import their
|
|
21
|
+
// siblings flat (`from util import x` inside `idlelib/`).
|
|
22
|
+
const stem = fileName.replace(/\.pyi?$/, '');
|
|
23
|
+
if (valid.test(stem))
|
|
24
|
+
deps.python.localModules.add(stem);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
function toFinding(ruleId, draft, defaults, file) {
|
|
28
|
+
return {
|
|
29
|
+
ruleId,
|
|
30
|
+
message: draft.message,
|
|
31
|
+
severity: draft.severity ?? defaults.severity,
|
|
32
|
+
confidence: draft.confidence ?? defaults.confidence,
|
|
33
|
+
file,
|
|
34
|
+
start: draft.start,
|
|
35
|
+
end: draft.end,
|
|
36
|
+
snippet: draft.snippet ?? '',
|
|
37
|
+
evidence: draft.evidence ?? [],
|
|
38
|
+
...(draft.help ? { help: draft.help } : {}),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
function commentLinesOf(root) {
|
|
42
|
+
const lines = new Set();
|
|
43
|
+
const stack = [root];
|
|
44
|
+
while (stack.length > 0) {
|
|
45
|
+
const node = stack.pop();
|
|
46
|
+
if (!node)
|
|
47
|
+
break;
|
|
48
|
+
if (node.type === 'comment' || node.type === 'line_comment' || node.type === 'block_comment') {
|
|
49
|
+
lines.add(node.startPosition.row + 1);
|
|
50
|
+
continue;
|
|
51
|
+
}
|
|
52
|
+
for (const child of node.namedChildren)
|
|
53
|
+
stack.push(child);
|
|
54
|
+
}
|
|
55
|
+
return lines;
|
|
56
|
+
}
|
|
57
|
+
export async function scanProject(options) {
|
|
58
|
+
const started = performance.now();
|
|
59
|
+
const target = path.resolve(options.root);
|
|
60
|
+
const targetInfo = await stat(target).catch(() => undefined);
|
|
61
|
+
// Scanning a single file still resolves manifests and local modules from the
|
|
62
|
+
// directory that contains it.
|
|
63
|
+
const root = targetInfo?.isFile() ? path.dirname(target) : target;
|
|
64
|
+
const warnings = [];
|
|
65
|
+
const { config } = options;
|
|
66
|
+
for (const ruleId of Object.keys(config.rules)) {
|
|
67
|
+
if (!RULE_BY_ID.has(ruleId))
|
|
68
|
+
warnings.push(`unknown rule in config: ${ruleId}`);
|
|
69
|
+
}
|
|
70
|
+
const deps = await loadProjectDeps(root);
|
|
71
|
+
deps.ignoredModules = new Set(config.ignoreModules);
|
|
72
|
+
const { files, skipped: skippedByDiscovery } = await discoverFiles({
|
|
73
|
+
root: target,
|
|
74
|
+
include: config.include,
|
|
75
|
+
exclude: config.exclude,
|
|
76
|
+
});
|
|
77
|
+
collectLocalPythonModules(files, deps);
|
|
78
|
+
const enabled = ALL_RULES.filter((rule) => {
|
|
79
|
+
const setting = config.rules[rule.meta.id];
|
|
80
|
+
if (setting === 'off')
|
|
81
|
+
return false;
|
|
82
|
+
if (options.onlyRules && !options.onlyRules.has(rule.meta.id))
|
|
83
|
+
return false;
|
|
84
|
+
return true;
|
|
85
|
+
});
|
|
86
|
+
const byLanguage = { python: 0, typescript: 0, tsx: 0 };
|
|
87
|
+
const findings = [];
|
|
88
|
+
const seen = new Set();
|
|
89
|
+
let suppressedCount = 0;
|
|
90
|
+
let parseErrors = 0;
|
|
91
|
+
let skipped = skippedByDiscovery;
|
|
92
|
+
for (const file of files) {
|
|
93
|
+
let buffer;
|
|
94
|
+
try {
|
|
95
|
+
buffer = await readFile(file.abs);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
skipped += 1;
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
if (buffer.includes(0)) {
|
|
102
|
+
skipped += 1;
|
|
103
|
+
continue;
|
|
104
|
+
}
|
|
105
|
+
const source = buffer.toString('utf8');
|
|
106
|
+
byLanguage[file.language] += 1;
|
|
107
|
+
const parser = await getParser(file.language);
|
|
108
|
+
const tree = parser.parse(source);
|
|
109
|
+
if (!tree) {
|
|
110
|
+
parseErrors += 1;
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const hadParseError = tree.rootNode.hasError;
|
|
114
|
+
if (hadParseError)
|
|
115
|
+
parseErrors += 1;
|
|
116
|
+
const ctx = {
|
|
117
|
+
file: file.rel,
|
|
118
|
+
lines: source.split(/\r?\n/),
|
|
119
|
+
root: asAst(tree.rootNode),
|
|
120
|
+
language: file.language,
|
|
121
|
+
deps,
|
|
122
|
+
};
|
|
123
|
+
const suppressions = readSuppressions(source, commentLinesOf(ctx.root));
|
|
124
|
+
for (const rule of enabled) {
|
|
125
|
+
if (!rule.meta.languages.includes(file.language))
|
|
126
|
+
continue;
|
|
127
|
+
let drafts;
|
|
128
|
+
try {
|
|
129
|
+
drafts = rule.run(ctx);
|
|
130
|
+
}
|
|
131
|
+
catch (error) {
|
|
132
|
+
warnings.push(`${rule.meta.id} crashed on ${file.rel}: ${error.message}`);
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
const configured = config.rules[rule.meta.id];
|
|
136
|
+
const severity = configured && configured !== 'off' ? configured : rule.meta.severity;
|
|
137
|
+
for (const draft of drafts) {
|
|
138
|
+
const finding = toFinding(rule.meta.id, draft, { severity, confidence: rule.meta.confidence }, file.rel);
|
|
139
|
+
// A file that did not parse cleanly has an unreliable structure: keep
|
|
140
|
+
// the finding, but never claim high confidence about it.
|
|
141
|
+
if (hadParseError && finding.confidence === 'high') {
|
|
142
|
+
finding.confidence = 'medium';
|
|
143
|
+
finding.evidence = [
|
|
144
|
+
...finding.evidence,
|
|
145
|
+
'the file has syntax errors, so its structure may be misread',
|
|
146
|
+
];
|
|
147
|
+
}
|
|
148
|
+
if (isSuppressed(finding, suppressions)) {
|
|
149
|
+
suppressedCount += 1;
|
|
150
|
+
continue;
|
|
151
|
+
}
|
|
152
|
+
const key = `${finding.ruleId}|${finding.file}|${finding.start.line}|${finding.start.column}|${finding.message}`;
|
|
153
|
+
if (seen.has(key))
|
|
154
|
+
continue;
|
|
155
|
+
seen.add(key);
|
|
156
|
+
findings.push(finding);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
const disposable = tree;
|
|
160
|
+
try {
|
|
161
|
+
disposable.delete?.();
|
|
162
|
+
}
|
|
163
|
+
catch (error) {
|
|
164
|
+
warnings.push(`could not free parse tree for ${file.rel}: ${error.message}`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
findings.sort((a, b) => a.file.localeCompare(b.file) ||
|
|
168
|
+
a.start.line - b.start.line ||
|
|
169
|
+
a.start.column - b.start.column ||
|
|
170
|
+
a.ruleId.localeCompare(b.ruleId));
|
|
171
|
+
const stats = {
|
|
172
|
+
files: byLanguage.python + byLanguage.typescript + byLanguage.tsx,
|
|
173
|
+
byLanguage,
|
|
174
|
+
skipped,
|
|
175
|
+
parseErrors,
|
|
176
|
+
durationMs: Math.round(performance.now() - started),
|
|
177
|
+
};
|
|
178
|
+
return { findings, suppressedCount, stats, warnings };
|
|
179
|
+
}
|
package/dist/files.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { LanguageId } from './types.ts';
|
|
2
|
+
/** Directories that never contain code we want to lint. */
|
|
3
|
+
export declare const DEFAULT_IGNORE_DIRS: ReadonlySet<string>;
|
|
4
|
+
export declare const DEFAULT_INCLUDE: readonly string[];
|
|
5
|
+
export interface SourceFile {
|
|
6
|
+
/** Absolute path on disk. */
|
|
7
|
+
abs: string;
|
|
8
|
+
/** Repository-relative path with forward slashes. */
|
|
9
|
+
rel: string;
|
|
10
|
+
language: LanguageId;
|
|
11
|
+
size: number;
|
|
12
|
+
}
|
|
13
|
+
export interface DiscoverOptions {
|
|
14
|
+
root: string;
|
|
15
|
+
include?: readonly string[];
|
|
16
|
+
exclude?: readonly string[];
|
|
17
|
+
ignoreDirs?: readonly string[];
|
|
18
|
+
maxBytes?: number;
|
|
19
|
+
}
|
|
20
|
+
export interface DiscoverResult {
|
|
21
|
+
files: SourceFile[];
|
|
22
|
+
skipped: number;
|
|
23
|
+
}
|
|
24
|
+
export declare function toPosix(p: string): string;
|
|
25
|
+
/**
|
|
26
|
+
* Translate a small glob dialect into a RegExp anchored at the whole path.
|
|
27
|
+
* Supported: `**` (any depth), `*` (within one segment), `?`.
|
|
28
|
+
*/
|
|
29
|
+
export declare function globToRegExp(glob: string): RegExp;
|
|
30
|
+
export declare function matchesAny(relPath: string, patterns: readonly RegExp[]): boolean;
|
|
31
|
+
export declare function languageFor(fileName: string): LanguageId | undefined;
|
|
32
|
+
export declare function discoverFiles(options: DiscoverOptions): Promise<DiscoverResult>;
|
package/dist/files.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
import { readdir, stat } from 'node:fs/promises';
|
|
2
|
+
import * as path from 'node:path';
|
|
3
|
+
/** Directories that never contain code we want to lint. */
|
|
4
|
+
export const DEFAULT_IGNORE_DIRS = new Set([
|
|
5
|
+
'.git', '.hg', '.svn', '.idea', '.vscode',
|
|
6
|
+
'node_modules', 'bower_components',
|
|
7
|
+
'dist', 'build', 'out', 'target', 'bin', 'obj',
|
|
8
|
+
'vendor', 'third_party', 'external',
|
|
9
|
+
'.venv', 'venv', 'env', 'virtualenv', '.tox', '.eggs',
|
|
10
|
+
'site-packages', 'dist-packages',
|
|
11
|
+
'__pycache__', '.mypy_cache', '.pytest_cache', '.ruff_cache', '.pytype',
|
|
12
|
+
'.next', '.nuxt', '.svelte-kit', '.turbo', '.cache', 'coverage',
|
|
13
|
+
'.slopgate-cache',
|
|
14
|
+
]);
|
|
15
|
+
export const DEFAULT_INCLUDE = [
|
|
16
|
+
'**/*.py', '**/*.pyi',
|
|
17
|
+
'**/*.ts', '**/*.mts', '**/*.cts', '**/*.tsx',
|
|
18
|
+
'**/*.js', '**/*.mjs', '**/*.cjs', '**/*.jsx',
|
|
19
|
+
];
|
|
20
|
+
const EXTENSION_LANGUAGE = {
|
|
21
|
+
'.py': 'python',
|
|
22
|
+
'.pyi': 'python',
|
|
23
|
+
'.ts': 'typescript',
|
|
24
|
+
'.mts': 'typescript',
|
|
25
|
+
'.cts': 'typescript',
|
|
26
|
+
'.tsx': 'tsx',
|
|
27
|
+
'.jsx': 'tsx',
|
|
28
|
+
'.js': 'typescript',
|
|
29
|
+
'.mjs': 'typescript',
|
|
30
|
+
'.cjs': 'typescript',
|
|
31
|
+
};
|
|
32
|
+
const MAX_FILE_BYTES = 1024 * 1024;
|
|
33
|
+
export function toPosix(p) {
|
|
34
|
+
return p.replace(/\\/g, '/');
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* Translate a small glob dialect into a RegExp anchored at the whole path.
|
|
38
|
+
* Supported: `**` (any depth), `*` (within one segment), `?`.
|
|
39
|
+
*/
|
|
40
|
+
export function globToRegExp(glob) {
|
|
41
|
+
const normalized = toPosix(glob).replace(/^\.\//, '');
|
|
42
|
+
let re = '';
|
|
43
|
+
for (let i = 0; i < normalized.length; i += 1) {
|
|
44
|
+
const ch = normalized[i] ?? '';
|
|
45
|
+
if (ch === '*') {
|
|
46
|
+
if (normalized[i + 1] === '*') {
|
|
47
|
+
i += 1;
|
|
48
|
+
if (normalized[i + 1] === '/') {
|
|
49
|
+
i += 1;
|
|
50
|
+
re += '(?:[^/]+/)*';
|
|
51
|
+
}
|
|
52
|
+
else {
|
|
53
|
+
re += '.*';
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
re += '[^/]*';
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
else if (ch === '?') {
|
|
61
|
+
re += '[^/]';
|
|
62
|
+
}
|
|
63
|
+
else if ('\\^$.|+()[]{}'.includes(ch)) {
|
|
64
|
+
re += '\\' + ch;
|
|
65
|
+
}
|
|
66
|
+
else {
|
|
67
|
+
re += ch;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
return new RegExp('^' + re + '$');
|
|
71
|
+
}
|
|
72
|
+
export function matchesAny(relPath, patterns) {
|
|
73
|
+
return patterns.some((re) => re.test(relPath));
|
|
74
|
+
}
|
|
75
|
+
export function languageFor(fileName) {
|
|
76
|
+
if (fileName.endsWith('.d.ts') || fileName.endsWith('.d.mts') || fileName.endsWith('.d.cts')) {
|
|
77
|
+
return undefined;
|
|
78
|
+
}
|
|
79
|
+
const ext = path.extname(fileName).toLowerCase();
|
|
80
|
+
return EXTENSION_LANGUAGE[ext];
|
|
81
|
+
}
|
|
82
|
+
export async function discoverFiles(options) {
|
|
83
|
+
const root = path.resolve(options.root);
|
|
84
|
+
const includeRe = (options.include ?? DEFAULT_INCLUDE).map(globToRegExp);
|
|
85
|
+
const excludeRe = (options.exclude ?? []).map(globToRegExp);
|
|
86
|
+
const ignoreDirs = new Set([...DEFAULT_IGNORE_DIRS, ...(options.ignoreDirs ?? [])]);
|
|
87
|
+
const maxBytes = options.maxBytes ?? MAX_FILE_BYTES;
|
|
88
|
+
const files = [];
|
|
89
|
+
let skipped = 0;
|
|
90
|
+
// `slopgate src/app.py` scans a single file, not an empty directory walk.
|
|
91
|
+
let rootInfo;
|
|
92
|
+
try {
|
|
93
|
+
rootInfo = await stat(root);
|
|
94
|
+
}
|
|
95
|
+
catch {
|
|
96
|
+
return { files, skipped: 1 };
|
|
97
|
+
}
|
|
98
|
+
if (rootInfo.isFile()) {
|
|
99
|
+
const name = path.basename(root);
|
|
100
|
+
const language = languageFor(name);
|
|
101
|
+
if (!language || !matchesAny(name, includeRe) || matchesAny(name, excludeRe)) {
|
|
102
|
+
return { files, skipped: 1 };
|
|
103
|
+
}
|
|
104
|
+
if (rootInfo.size > maxBytes || rootInfo.size === 0) {
|
|
105
|
+
return { files, skipped: 1 };
|
|
106
|
+
}
|
|
107
|
+
files.push({ abs: root, rel: name, language, size: rootInfo.size });
|
|
108
|
+
return { files, skipped };
|
|
109
|
+
}
|
|
110
|
+
async function walk(dir) {
|
|
111
|
+
let entries;
|
|
112
|
+
try {
|
|
113
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
entries.sort((a, b) => a.name.localeCompare(b.name));
|
|
119
|
+
for (const entry of entries) {
|
|
120
|
+
const abs = path.join(dir, entry.name);
|
|
121
|
+
const rel = toPosix(path.relative(root, abs));
|
|
122
|
+
if (entry.isSymbolicLink()) {
|
|
123
|
+
skipped += 1;
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
if (entry.isDirectory()) {
|
|
127
|
+
if (ignoreDirs.has(entry.name) || matchesAny(rel + '/', excludeRe)) {
|
|
128
|
+
skipped += 1;
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
await walk(abs);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
if (!entry.isFile()) {
|
|
135
|
+
skipped += 1;
|
|
136
|
+
continue;
|
|
137
|
+
}
|
|
138
|
+
if (matchesAny(rel, excludeRe)) {
|
|
139
|
+
skipped += 1;
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
const language = languageFor(entry.name);
|
|
143
|
+
if (!language || !matchesAny(rel, includeRe)) {
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (entry.name.endsWith('.min.js') || entry.name.endsWith('.min.mjs')) {
|
|
147
|
+
skipped += 1;
|
|
148
|
+
continue;
|
|
149
|
+
}
|
|
150
|
+
let info;
|
|
151
|
+
try {
|
|
152
|
+
info = await stat(abs);
|
|
153
|
+
}
|
|
154
|
+
catch {
|
|
155
|
+
skipped += 1;
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
if (info.size > maxBytes || info.size === 0) {
|
|
159
|
+
skipped += 1;
|
|
160
|
+
continue;
|
|
161
|
+
}
|
|
162
|
+
files.push({ abs, rel, language, size: info.size });
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
await walk(root);
|
|
166
|
+
files.sort((a, b) => a.rel.localeCompare(b.rel));
|
|
167
|
+
return { files, skipped };
|
|
168
|
+
}
|
package/dist/mcp.d.ts
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type Config } from './config.ts';
|
|
2
|
+
import { type DiffSet } from './diff.ts';
|
|
3
|
+
import { type ScanResult } from './engine.ts';
|
|
4
|
+
/**
|
|
5
|
+
* Minimal Model Context Protocol server over stdio.
|
|
6
|
+
*
|
|
7
|
+
* Transport: newline-delimited JSON-RPC 2.0 (MCP stdio transport). Nothing is
|
|
8
|
+
* ever written to stdout except protocol messages.
|
|
9
|
+
*/
|
|
10
|
+
export interface JsonRpcRequest {
|
|
11
|
+
jsonrpc?: string;
|
|
12
|
+
id?: string | number | null;
|
|
13
|
+
method?: string;
|
|
14
|
+
params?: unknown;
|
|
15
|
+
}
|
|
16
|
+
export interface JsonRpcError {
|
|
17
|
+
code: number;
|
|
18
|
+
message: string;
|
|
19
|
+
data?: unknown;
|
|
20
|
+
}
|
|
21
|
+
export interface JsonRpcResponse {
|
|
22
|
+
jsonrpc: '2.0';
|
|
23
|
+
id: string | number | null;
|
|
24
|
+
result?: unknown;
|
|
25
|
+
error?: JsonRpcError;
|
|
26
|
+
}
|
|
27
|
+
export interface McpDeps {
|
|
28
|
+
root: string;
|
|
29
|
+
version: string;
|
|
30
|
+
config: Config;
|
|
31
|
+
scan: (root: string) => Promise<ScanResult>;
|
|
32
|
+
diff: (root: string, base: string) => Promise<DiffSet>;
|
|
33
|
+
}
|
|
34
|
+
/** True when `candidate` is `root` itself or lives below it. */
|
|
35
|
+
export declare function isInsideRoot(realRoot: string, candidate: string): boolean;
|
|
36
|
+
export declare function createMcpServer(deps: McpDeps): {
|
|
37
|
+
handle(line: string): Promise<JsonRpcResponse | null>;
|
|
38
|
+
};
|
|
39
|
+
export declare function defaultMcpDeps(root: string, version: string): Omit<McpDeps, 'config'>;
|
|
40
|
+
/** Runs the stdio loop. Resolves when stdin closes. */
|
|
41
|
+
export declare function serveMcp(root: string, version: string): Promise<void>;
|
package/dist/mcp.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { realpath } from 'node:fs/promises';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import process from 'node:process';
|
|
4
|
+
import { createInterface } from 'node:readline';
|
|
5
|
+
import { loadBaseline, partitionByBaseline } from "./baseline.js";
|
|
6
|
+
import { loadConfig, meetsConfidence } from "./config.js";
|
|
7
|
+
import { diffSince, isInDiff } from "./diff.js";
|
|
8
|
+
import { scanProject } from "./engine.js";
|
|
9
|
+
import { ALL_RULES } from "./rules/index.js";
|
|
10
|
+
const PROTOCOL_FALLBACK = '2024-11-05';
|
|
11
|
+
const MAX_FINDINGS = 50;
|
|
12
|
+
const TOOLS = [
|
|
13
|
+
{
|
|
14
|
+
name: 'scan_diff',
|
|
15
|
+
description: 'Run slopgate on the lines changed since a git ref (default HEAD). Use this before finishing a task to check that the new code does not contain hallucinated imports, empty stubs, tests that cannot fail, swallowed errors or dead code.',
|
|
16
|
+
inputSchema: {
|
|
17
|
+
type: 'object',
|
|
18
|
+
properties: {
|
|
19
|
+
base: { type: 'string', description: 'Git ref to compare against (default: HEAD)' },
|
|
20
|
+
confidence: {
|
|
21
|
+
type: 'string',
|
|
22
|
+
enum: ['high', 'medium', 'low'],
|
|
23
|
+
description: 'Minimum confidence to report (default: high)',
|
|
24
|
+
},
|
|
25
|
+
maxFindings: { type: 'integer', description: 'Maximum findings to print (default: 50)' },
|
|
26
|
+
},
|
|
27
|
+
additionalProperties: false,
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: 'scan_path',
|
|
32
|
+
description: 'Run slopgate over a directory or file. Returns findings with rule id, confidence and evidence.',
|
|
33
|
+
inputSchema: {
|
|
34
|
+
type: 'object',
|
|
35
|
+
properties: {
|
|
36
|
+
path: { type: 'string', description: 'File or directory, relative to the repository root' },
|
|
37
|
+
confidence: {
|
|
38
|
+
type: 'string',
|
|
39
|
+
enum: ['high', 'medium', 'low'],
|
|
40
|
+
description: 'Minimum confidence to report (default: high)',
|
|
41
|
+
},
|
|
42
|
+
maxFindings: { type: 'integer', description: 'Maximum findings to print (default: 50)' },
|
|
43
|
+
},
|
|
44
|
+
additionalProperties: false,
|
|
45
|
+
},
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
name: 'list_rules',
|
|
49
|
+
description: 'List the rules slopgate can report, with their default severity and confidence.',
|
|
50
|
+
inputSchema: { type: 'object', properties: {}, additionalProperties: false },
|
|
51
|
+
},
|
|
52
|
+
];
|
|
53
|
+
function ok(id, result) {
|
|
54
|
+
return { jsonrpc: '2.0', id, result };
|
|
55
|
+
}
|
|
56
|
+
function fail(id, code, message) {
|
|
57
|
+
return { jsonrpc: '2.0', id, error: { code, message } };
|
|
58
|
+
}
|
|
59
|
+
/** True when `candidate` is `root` itself or lives below it. */
|
|
60
|
+
export function isInsideRoot(realRoot, candidate) {
|
|
61
|
+
const relative = path.relative(realRoot, candidate);
|
|
62
|
+
return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative));
|
|
63
|
+
}
|
|
64
|
+
function textResult(text, isError = false) {
|
|
65
|
+
return { content: [{ type: 'text', text }], ...(isError ? { isError: true } : {}) };
|
|
66
|
+
}
|
|
67
|
+
function coerceConfidence(value, fallback) {
|
|
68
|
+
if (value === 'high' || value === 'medium' || value === 'low')
|
|
69
|
+
return value;
|
|
70
|
+
return fallback;
|
|
71
|
+
}
|
|
72
|
+
function coerceNumber(value, fallback) {
|
|
73
|
+
return typeof value === 'number' && Number.isFinite(value) && value > 0
|
|
74
|
+
? Math.min(Math.floor(value), MAX_FINDINGS)
|
|
75
|
+
: fallback;
|
|
76
|
+
}
|
|
77
|
+
function formatFindings(findings, result, version, max, preamble) {
|
|
78
|
+
const shown = findings.slice(0, max);
|
|
79
|
+
const errors = findings.filter((finding) => finding.severity === 'error').length;
|
|
80
|
+
const lines = [];
|
|
81
|
+
if (preamble)
|
|
82
|
+
lines.push(preamble);
|
|
83
|
+
lines.push(`slopgate ${version} · ${findings.length} finding(s) (${errors} error) · ${result.stats.files} files scanned in ${result.stats.durationMs}ms`);
|
|
84
|
+
if (findings.length === 0) {
|
|
85
|
+
lines.push('No findings above the confidence threshold.');
|
|
86
|
+
return lines.join('\n');
|
|
87
|
+
}
|
|
88
|
+
if (findings.length > shown.length) {
|
|
89
|
+
lines.push(`Showing the first ${shown.length} of ${findings.length}.`);
|
|
90
|
+
}
|
|
91
|
+
for (const finding of shown) {
|
|
92
|
+
lines.push(`${finding.file}:${finding.start.line}:${finding.start.column} ${finding.severity} ${finding.confidence} ${finding.ruleId} ${finding.message}`);
|
|
93
|
+
if (finding.snippet)
|
|
94
|
+
lines.push(` ${finding.snippet}`);
|
|
95
|
+
for (const item of finding.evidence.slice(0, 2))
|
|
96
|
+
lines.push(` - ${item}`);
|
|
97
|
+
}
|
|
98
|
+
return lines.join('\n');
|
|
99
|
+
}
|
|
100
|
+
export function createMcpServer(deps) {
|
|
101
|
+
async function callTool(name, params) {
|
|
102
|
+
if (name === 'list_rules') {
|
|
103
|
+
const lines = ['id\tseverity\tconfidence\tlanguages\ttitle'];
|
|
104
|
+
for (const rule of ALL_RULES) {
|
|
105
|
+
lines.push(`${rule.meta.id}\t${rule.meta.severity}\t${rule.meta.confidence}\t${rule.meta.languages.join(',')}\t${rule.meta.title}`);
|
|
106
|
+
}
|
|
107
|
+
return textResult(lines.join('\n'));
|
|
108
|
+
}
|
|
109
|
+
const confidence = coerceConfidence(params.confidence, deps.config.confidence);
|
|
110
|
+
const max = coerceNumber(params.maxFindings, MAX_FINDINGS);
|
|
111
|
+
if (name === 'scan_path') {
|
|
112
|
+
const target = path.resolve(deps.root, typeof params.path === 'string' ? params.path : '.');
|
|
113
|
+
if (!isInsideRoot(deps.root, target)) {
|
|
114
|
+
return textResult(`Refusing to scan outside the repository root: ${target}`, true);
|
|
115
|
+
}
|
|
116
|
+
// `path.resolve` does not follow symlinks: a link inside the root could
|
|
117
|
+
// still point outside it, so compare real paths as well.
|
|
118
|
+
const realRoot = await realpath(deps.root).catch(() => deps.root);
|
|
119
|
+
const realTarget = await realpath(target).catch(() => target);
|
|
120
|
+
if (!isInsideRoot(realRoot, realTarget)) {
|
|
121
|
+
return textResult(`Refusing to scan outside the repository root: ${target}`, true);
|
|
122
|
+
}
|
|
123
|
+
const result = await deps.scan(target);
|
|
124
|
+
const visible = result.findings.filter((finding) => meetsConfidence(finding.confidence, confidence));
|
|
125
|
+
return textResult(formatFindings(visible, result, deps.version, max));
|
|
126
|
+
}
|
|
127
|
+
if (name === 'scan_diff') {
|
|
128
|
+
const base = typeof params.base === 'string' && params.base.length > 0 ? params.base : 'HEAD';
|
|
129
|
+
const result = await deps.scan(deps.root);
|
|
130
|
+
const set = await deps.diff(deps.root, base);
|
|
131
|
+
const inDiff = result.findings.filter((finding) => isInDiff(finding, set) && meetsConfidence(finding.confidence, confidence));
|
|
132
|
+
const preamble = `Diff since ${base}: ${inDiff.length} finding(s) on changed lines.`;
|
|
133
|
+
return textResult(formatFindings(inDiff, result, deps.version, max, preamble));
|
|
134
|
+
}
|
|
135
|
+
return textResult(`Unknown tool: ${name}`, true);
|
|
136
|
+
}
|
|
137
|
+
return {
|
|
138
|
+
async handle(line) {
|
|
139
|
+
let request;
|
|
140
|
+
try {
|
|
141
|
+
request = JSON.parse(line);
|
|
142
|
+
}
|
|
143
|
+
catch {
|
|
144
|
+
return fail(null, -32700, 'Parse error');
|
|
145
|
+
}
|
|
146
|
+
if (request === null || typeof request !== 'object' || typeof request.method !== 'string') {
|
|
147
|
+
return fail(null, -32600, 'Invalid request');
|
|
148
|
+
}
|
|
149
|
+
const isNotification = request.id === undefined || request.id === null;
|
|
150
|
+
const id = request.id ?? null;
|
|
151
|
+
try {
|
|
152
|
+
switch (request.method) {
|
|
153
|
+
case 'initialize': {
|
|
154
|
+
const requested = request.params?.protocolVersion;
|
|
155
|
+
return ok(id, {
|
|
156
|
+
protocolVersion: typeof requested === 'string' ? requested : PROTOCOL_FALLBACK,
|
|
157
|
+
capabilities: { tools: {} },
|
|
158
|
+
serverInfo: { name: 'slopgate', version: deps.version },
|
|
159
|
+
});
|
|
160
|
+
}
|
|
161
|
+
case 'notifications/initialized':
|
|
162
|
+
return null;
|
|
163
|
+
case 'ping':
|
|
164
|
+
return ok(id, {});
|
|
165
|
+
case 'tools/list':
|
|
166
|
+
return ok(id, { tools: TOOLS });
|
|
167
|
+
case 'tools/call': {
|
|
168
|
+
const params = (request.params ?? {});
|
|
169
|
+
if (typeof params.name !== 'string')
|
|
170
|
+
return fail(id, -32602, 'tools/call requires a tool name');
|
|
171
|
+
const args = params.arguments !== null && typeof params.arguments === 'object'
|
|
172
|
+
? params.arguments
|
|
173
|
+
: {};
|
|
174
|
+
const result = await callTool(params.name, args);
|
|
175
|
+
return ok(id, result);
|
|
176
|
+
}
|
|
177
|
+
default:
|
|
178
|
+
return isNotification ? null : fail(id, -32601, `Method not found: ${request.method}`);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
catch (error) {
|
|
182
|
+
const message = error.message;
|
|
183
|
+
if (request.method === 'tools/call') {
|
|
184
|
+
return ok(id, textResult(`slopgate error: ${message}`, true));
|
|
185
|
+
}
|
|
186
|
+
return fail(id, -32603, message);
|
|
187
|
+
}
|
|
188
|
+
},
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
export function defaultMcpDeps(root, version) {
|
|
192
|
+
let configPromise;
|
|
193
|
+
const getConfig = async () => {
|
|
194
|
+
configPromise ??= loadConfig(root).then((loaded) => loaded.config);
|
|
195
|
+
return configPromise;
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
root,
|
|
199
|
+
version,
|
|
200
|
+
async scan(scanRoot) {
|
|
201
|
+
const config = await getConfig();
|
|
202
|
+
const result = await scanProject({ root: scanRoot, config });
|
|
203
|
+
// Respect a baseline if one exists, so agents do not re-report known debt.
|
|
204
|
+
const baseline = await loadBaseline(path.join(root, '.slopgate-baseline.json'));
|
|
205
|
+
if (baseline)
|
|
206
|
+
return { ...result, findings: partitionByBaseline(result.findings, baseline).fresh };
|
|
207
|
+
return result;
|
|
208
|
+
},
|
|
209
|
+
diff: diffSince,
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
/** Runs the stdio loop. Resolves when stdin closes. */
|
|
213
|
+
export async function serveMcp(root, version) {
|
|
214
|
+
const config = (await loadConfig(root)).config;
|
|
215
|
+
const base = defaultMcpDeps(root, version);
|
|
216
|
+
const server = createMcpServer({ ...base, config });
|
|
217
|
+
process.stderr.write(`slopgate mcp ${version} ready (root: ${root})\n`);
|
|
218
|
+
const rl = createInterface({ input: process.stdin, crlfDelay: Infinity });
|
|
219
|
+
for await (const line of rl) {
|
|
220
|
+
if (line.trim().length === 0)
|
|
221
|
+
continue;
|
|
222
|
+
const response = await server.handle(line);
|
|
223
|
+
if (response !== null)
|
|
224
|
+
process.stdout.write(JSON.stringify(response) + '\n');
|
|
225
|
+
}
|
|
226
|
+
}
|
package/dist/parser.d.ts
ADDED