patchpilot-mcp 0.4.1__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.
- patchpilot/__init__.py +3 -0
- patchpilot/__main__.py +246 -0
- patchpilot/analysis.py +20 -0
- patchpilot/changed.py +464 -0
- patchpilot/common.py +75 -0
- patchpilot/compact.py +292 -0
- patchpilot/config.py +217 -0
- patchpilot/diff.py +581 -0
- patchpilot/external_sarif.py +219 -0
- patchpilot/formatting.py +175 -0
- patchpilot/js_review.py +253 -0
- patchpilot/json_review.py +177 -0
- patchpilot/python_review.py +316 -0
- patchpilot/python_rules.py +216 -0
- patchpilot/sarif.py +59 -0
- patchpilot/server.py +274 -0
- patchpilot/signatures.py +224 -0
- patchpilot/snapshot.py +572 -0
- patchpilot_mcp-0.4.1.dist-info/METADATA +381 -0
- patchpilot_mcp-0.4.1.dist-info/RECORD +24 -0
- patchpilot_mcp-0.4.1.dist-info/WHEEL +5 -0
- patchpilot_mcp-0.4.1.dist-info/entry_points.txt +3 -0
- patchpilot_mcp-0.4.1.dist-info/licenses/LICENSE +21 -0
- patchpilot_mcp-0.4.1.dist-info/top_level.txt +1 -0
patchpilot/sarif.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""Export ordinary review findings as SARIF 2.1.0 without file or network I/O."""
|
|
2
|
+
|
|
3
|
+
from urllib.parse import quote
|
|
4
|
+
from .analysis import InputError, MAX_FINDINGS
|
|
5
|
+
from .snapshot import normalize_finding, attach_ids
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def export_sarif(findings: list[dict]) -> dict:
|
|
9
|
+
if not isinstance(findings, list) or len(findings) > MAX_FINDINGS:
|
|
10
|
+
raise InputError(f"SARIF accepts at most {MAX_FINDINGS} findings")
|
|
11
|
+
records = attach_ids([normalize_finding(f) for f in findings])
|
|
12
|
+
rules = {}
|
|
13
|
+
results = []
|
|
14
|
+
levels = {"error": "error", "warning": "warning", "info": "note"}
|
|
15
|
+
for f in records:
|
|
16
|
+
code = f["code"]
|
|
17
|
+
rules.setdefault(
|
|
18
|
+
code,
|
|
19
|
+
{
|
|
20
|
+
"id": code,
|
|
21
|
+
"shortDescription": {"text": code.replace("_", " ").title()},
|
|
22
|
+
"defaultConfiguration": {"level": levels[f["severity"]]},
|
|
23
|
+
},
|
|
24
|
+
)
|
|
25
|
+
item = dict(
|
|
26
|
+
ruleId=code,
|
|
27
|
+
level=levels[f["severity"]],
|
|
28
|
+
message={"text": f["message"]},
|
|
29
|
+
partialFingerprints={"patchpilotIdentity/v1": f["id"]},
|
|
30
|
+
properties={
|
|
31
|
+
"evidence": f["evidence"],
|
|
32
|
+
"recommendation": f["recommendation"],
|
|
33
|
+
},
|
|
34
|
+
)
|
|
35
|
+
if f["path"]:
|
|
36
|
+
physical = {"artifactLocation": {"uri": quote(f["path"], safe="/")}}
|
|
37
|
+
if f["line"] is not None:
|
|
38
|
+
physical["region"] = {"startLine": f["line"]}
|
|
39
|
+
if "column" in f:
|
|
40
|
+
physical["region"]["startColumn"] = f["column"]
|
|
41
|
+
item["locations"] = [{"physicalLocation": physical}]
|
|
42
|
+
results.append(item)
|
|
43
|
+
return {
|
|
44
|
+
"$schema": "https://json.schemastore.org/sarif-2.1.0.json",
|
|
45
|
+
"version": "2.1.0",
|
|
46
|
+
"runs": [
|
|
47
|
+
{
|
|
48
|
+
"tool": {
|
|
49
|
+
"driver": {
|
|
50
|
+
"name": "PatchPilot MCP",
|
|
51
|
+
"version": "0.4.1",
|
|
52
|
+
"informationUri": "https://github.com/ahmedsaeed1-eng/patchpilot-mcp",
|
|
53
|
+
"rules": [rules[k] for k in sorted(rules)],
|
|
54
|
+
}
|
|
55
|
+
},
|
|
56
|
+
"results": results,
|
|
57
|
+
}
|
|
58
|
+
],
|
|
59
|
+
}
|
patchpilot/server.py
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
"""Official MCP stdio server, no filesystem or shell tools."""
|
|
2
|
+
|
|
3
|
+
from typing import Any, Literal
|
|
4
|
+
from pydantic import BaseModel, ConfigDict, Field
|
|
5
|
+
from mcp.server.fastmcp import FastMCP
|
|
6
|
+
from mcp.types import ToolAnnotations
|
|
7
|
+
from .analysis import review_diff as _review_diff, review_python as _review_python
|
|
8
|
+
from .json_review import review_json as _review_json
|
|
9
|
+
from .js_review import review_javascript as _review_js
|
|
10
|
+
from .sarif import export_sarif as _export_sarif
|
|
11
|
+
from .snapshot import review_snapshot as _review_snapshot, attach_ids
|
|
12
|
+
from .changed import review_source as _review_source, review_changed as _review_changed
|
|
13
|
+
from .signatures import compare_call_signature as _compare_signature
|
|
14
|
+
from .external_sarif import import_external_sarif as _import_external
|
|
15
|
+
from .compact import compact_report as _compact_report
|
|
16
|
+
from .formatting import suggest_formatting_patch as _suggest_formatting
|
|
17
|
+
|
|
18
|
+
mcp = FastMCP(
|
|
19
|
+
"patchpilot-mcp",
|
|
20
|
+
instructions="Review only supplied unified diff, source, JSON and manifests. Findings are bounded facts or maintainability heuristics; no repository access, security analysis, test execution, or edits.",
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class SnapshotEntry(BaseModel):
|
|
25
|
+
model_config = ConfigDict(extra="forbid", strict=True)
|
|
26
|
+
path: str = Field(
|
|
27
|
+
min_length=1, max_length=1024, description="Display label only; never opened"
|
|
28
|
+
)
|
|
29
|
+
source: str | None = Field(
|
|
30
|
+
default=None, description="Complete source or explicit fragment text"
|
|
31
|
+
)
|
|
32
|
+
digest: str | None = Field(
|
|
33
|
+
default=None, description="Optional lowercase SHA-256 hex of UTF-8 source"
|
|
34
|
+
)
|
|
35
|
+
language: (
|
|
36
|
+
Literal[
|
|
37
|
+
"python",
|
|
38
|
+
"json",
|
|
39
|
+
"javascript",
|
|
40
|
+
"jsx",
|
|
41
|
+
"typescript",
|
|
42
|
+
"tsx",
|
|
43
|
+
"go",
|
|
44
|
+
"java",
|
|
45
|
+
"csharp",
|
|
46
|
+
"dart",
|
|
47
|
+
"unknown",
|
|
48
|
+
]
|
|
49
|
+
| None
|
|
50
|
+
) = None
|
|
51
|
+
complete: bool = True
|
|
52
|
+
start_line: int = Field(default=1, ge=1, le=100000000)
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ManifestEntry(BaseModel):
|
|
56
|
+
model_config = ConfigDict(extra="forbid", strict=True)
|
|
57
|
+
path: str = Field(min_length=1, max_length=1024)
|
|
58
|
+
digest: str
|
|
59
|
+
language: (
|
|
60
|
+
Literal[
|
|
61
|
+
"python",
|
|
62
|
+
"json",
|
|
63
|
+
"javascript",
|
|
64
|
+
"jsx",
|
|
65
|
+
"typescript",
|
|
66
|
+
"tsx",
|
|
67
|
+
"go",
|
|
68
|
+
"java",
|
|
69
|
+
"csharp",
|
|
70
|
+
"dart",
|
|
71
|
+
"unknown",
|
|
72
|
+
]
|
|
73
|
+
| None
|
|
74
|
+
) = None
|
|
75
|
+
complete: bool = True
|
|
76
|
+
start_line: int = Field(default=1, ge=1, le=100000000)
|
|
77
|
+
reviewed: bool = False
|
|
78
|
+
review_profile: str = ""
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
READ_ONLY = ToolAnnotations(
|
|
82
|
+
readOnlyHint=True, destructiveHint=False, idempotentHint=True, openWorldHint=False
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
87
|
+
def review_diff(
|
|
88
|
+
diff: str, change_budget: int = 300, file_budget: int = 10
|
|
89
|
+
) -> dict[str, Any]:
|
|
90
|
+
"""Count changed lines, report budget, and plan focused tests from supplied unified diff. No tests run."""
|
|
91
|
+
result = _review_diff(diff, change_budget, file_budget)
|
|
92
|
+
result["findings"] = attach_ids(result["findings"])
|
|
93
|
+
return result
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
97
|
+
def review_python(
|
|
98
|
+
source: str,
|
|
99
|
+
path: str = "snippet.py",
|
|
100
|
+
start_line: int = 1,
|
|
101
|
+
complexity_threshold: int = 10,
|
|
102
|
+
complete_module: bool = False,
|
|
103
|
+
) -> dict[str, Any]:
|
|
104
|
+
"""Analyze supplied Python text for syntax and maintainability. Set complete_module only for a full module. Path is a label only."""
|
|
105
|
+
result = _review_python(
|
|
106
|
+
source, path, start_line, complexity_threshold, complete_module
|
|
107
|
+
)
|
|
108
|
+
result["findings"] = attach_ids(result["findings"])
|
|
109
|
+
return result
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
113
|
+
def review_json(
|
|
114
|
+
source: str, path: str = "document.json", start_line: int = 1
|
|
115
|
+
) -> dict[str, Any]:
|
|
116
|
+
"""Inspect strict JSON syntax and repeated object keys, with exact source coordinates."""
|
|
117
|
+
result = _review_json(source, path, start_line)
|
|
118
|
+
result["findings"] = attach_ids(result["findings"])
|
|
119
|
+
return result
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
123
|
+
def review_snapshot(
|
|
124
|
+
entries: list[SnapshotEntry],
|
|
125
|
+
previous_manifest: list[ManifestEntry] | None = None,
|
|
126
|
+
complete_snapshot: bool = False,
|
|
127
|
+
complexity_threshold: int = 10,
|
|
128
|
+
recheck_unchanged: bool = False,
|
|
129
|
+
previous_findings: list[dict[str, Any]] | None = None,
|
|
130
|
+
config_toml: str | None = None,
|
|
131
|
+
) -> dict[str, Any]:
|
|
132
|
+
"""Review added, changed and previously unchecked supplied source; return a metadata-only manifest for next time. Paths are labels. Missing paths are unknown unless complete_snapshot is true."""
|
|
133
|
+
return _review_snapshot(
|
|
134
|
+
[e.model_dump(exclude_none=True) for e in entries],
|
|
135
|
+
[e.model_dump(exclude_none=True) for e in previous_manifest or []],
|
|
136
|
+
complete_snapshot,
|
|
137
|
+
complexity_threshold,
|
|
138
|
+
recheck_unchanged,
|
|
139
|
+
previous_findings,
|
|
140
|
+
config_toml,
|
|
141
|
+
)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
145
|
+
def review_javascript(
|
|
146
|
+
source: str,
|
|
147
|
+
path: str = "snippet.js",
|
|
148
|
+
start_line: int = 1,
|
|
149
|
+
language: Literal["javascript", "jsx", "typescript", "tsx"] = "javascript",
|
|
150
|
+
) -> dict[str, Any]:
|
|
151
|
+
"""Static JS/JSX/TS/TSX grammar diagnostics; no type check or execution; unavailable parser yields unknown."""
|
|
152
|
+
result = _review_js(source, path, start_line, language)
|
|
153
|
+
result["findings"] = attach_ids(result["findings"])
|
|
154
|
+
return result
|
|
155
|
+
|
|
156
|
+
|
|
157
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
158
|
+
def export_sarif(findings: list[dict[str, Any]]) -> dict[str, Any]:
|
|
159
|
+
"""Convert explicit ordinary correctness and maintainability findings into SARIF 2.1.0."""
|
|
160
|
+
return _export_sarif(findings)
|
|
161
|
+
|
|
162
|
+
|
|
163
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
164
|
+
def review_source(
|
|
165
|
+
source: str,
|
|
166
|
+
path: str = "snippet.py",
|
|
167
|
+
language: (
|
|
168
|
+
Literal[
|
|
169
|
+
"python",
|
|
170
|
+
"json",
|
|
171
|
+
"javascript",
|
|
172
|
+
"jsx",
|
|
173
|
+
"typescript",
|
|
174
|
+
"tsx",
|
|
175
|
+
"go",
|
|
176
|
+
"java",
|
|
177
|
+
"csharp",
|
|
178
|
+
"dart",
|
|
179
|
+
"unknown",
|
|
180
|
+
]
|
|
181
|
+
| None
|
|
182
|
+
) = None,
|
|
183
|
+
config_toml: str | None = None,
|
|
184
|
+
start_line: int = 1,
|
|
185
|
+
complete: bool | None = None,
|
|
186
|
+
complexity_threshold: int = 10,
|
|
187
|
+
) -> dict[str, Any]:
|
|
188
|
+
"""Review explicit source with optional supplied TOML policy, immutable syntax diagnostics and reported heuristic suppressions."""
|
|
189
|
+
return _review_source(
|
|
190
|
+
source, path, language, config_toml, start_line, complete, complexity_threshold
|
|
191
|
+
)
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class ChangedEntry(BaseModel):
|
|
195
|
+
model_config = ConfigDict(extra="forbid", strict=True)
|
|
196
|
+
path: str = Field(min_length=1, max_length=1024)
|
|
197
|
+
source: str
|
|
198
|
+
previous_source: str | None = None
|
|
199
|
+
language: (
|
|
200
|
+
Literal[
|
|
201
|
+
"python",
|
|
202
|
+
"json",
|
|
203
|
+
"javascript",
|
|
204
|
+
"jsx",
|
|
205
|
+
"typescript",
|
|
206
|
+
"tsx",
|
|
207
|
+
"go",
|
|
208
|
+
"java",
|
|
209
|
+
"csharp",
|
|
210
|
+
"dart",
|
|
211
|
+
"unknown",
|
|
212
|
+
]
|
|
213
|
+
| None
|
|
214
|
+
) = None
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
218
|
+
def review_changed(
|
|
219
|
+
diff: str, entries: list[ChangedEntry], config_toml: str | None = None
|
|
220
|
+
) -> dict[str, Any]:
|
|
221
|
+
"""Verify full supplied post-source against diff context. Separate added-line findings, immutable file syntax errors, verified preexisting and unverified outside-line findings."""
|
|
222
|
+
return _review_changed(
|
|
223
|
+
diff, [entry.model_dump(exclude_none=True) for entry in entries], config_toml
|
|
224
|
+
)
|
|
225
|
+
|
|
226
|
+
|
|
227
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
228
|
+
def compare_call_signature(
|
|
229
|
+
call_source: str,
|
|
230
|
+
signature: dict[str, Any],
|
|
231
|
+
language: Literal["python", "javascript", "jsx", "typescript", "tsx"] = "python",
|
|
232
|
+
) -> dict[str, Any]:
|
|
233
|
+
"""Verify only a direct call's argument shape against the explicitly provided parameter contract. Dynamic calls and argument expansion are unknown."""
|
|
234
|
+
return _compare_signature(call_source, signature, language)
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
238
|
+
def import_external_sarif(sarif_text: str, diff: str | None = None) -> dict[str, Any]:
|
|
239
|
+
"""Normalize already-generated SARIF metadata and correlate only exact relative paths and lines with supplied diff; no scanner or embedded code execution."""
|
|
240
|
+
return _import_external(sarif_text, diff)
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
244
|
+
def compact_report(report: dict[str, Any], max_findings: int = 20) -> dict[str, Any]:
|
|
245
|
+
"""Compact a supplied bounded review report while preserving known hidden errors/warnings and unknown coverage counts."""
|
|
246
|
+
return _compact_report(report, max_findings)
|
|
247
|
+
|
|
248
|
+
|
|
249
|
+
@mcp.tool(annotations=READ_ONLY, structured_output=True)
|
|
250
|
+
def suggest_formatting_patch(
|
|
251
|
+
diff: str, entries: list[dict[str, Any]]
|
|
252
|
+
) -> dict[str, Any]:
|
|
253
|
+
"""Suggest only context-verified trailing whitespace changes for valid Python or JSON; never modify files."""
|
|
254
|
+
return _suggest_formatting(diff, entries)
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
@mcp.prompt()
|
|
258
|
+
def bounded_review() -> str:
|
|
259
|
+
"""A caller-selected review convention; not automatically applied."""
|
|
260
|
+
return (
|
|
261
|
+
"Review only the explicit supplied diff and affected source. Use review_changed with matching full post-change text and optional baseline. "
|
|
262
|
+
"Report file-level syntax errors even outside changed lines, and keep unknown/omitted coverage visible. "
|
|
263
|
+
"Use only scoped provided policy; list heuristic suppressions and reasons. Distinguish outside-line findings from proven preexisting findings. "
|
|
264
|
+
"If more context is needed, request only that bounded source. Any formatting patch is merely a suggestion; do not apply it automatically. "
|
|
265
|
+
"Do not claim whole-project correctness or executed tests; describe the smallest relevant existing test scope."
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def main() -> None:
|
|
270
|
+
mcp.run(transport="stdio")
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
if __name__ == "__main__":
|
|
274
|
+
main()
|
patchpilot/signatures.py
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
"""Explicit signature contract checks; no project discovery or execution."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import inspect
|
|
5
|
+
import re
|
|
6
|
+
from .analysis import InputError, bounded
|
|
7
|
+
from .js_review import parse_tree
|
|
8
|
+
|
|
9
|
+
KINDS = {
|
|
10
|
+
"positional_only": inspect.Parameter.POSITIONAL_ONLY,
|
|
11
|
+
"positional_or_keyword": inspect.Parameter.POSITIONAL_OR_KEYWORD,
|
|
12
|
+
"keyword_only": inspect.Parameter.KEYWORD_ONLY,
|
|
13
|
+
"var_positional": inspect.Parameter.VAR_POSITIONAL,
|
|
14
|
+
"var_keyword": inspect.Parameter.VAR_KEYWORD,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def _parameter(p):
|
|
19
|
+
if not isinstance(p, dict) or set(p) - {"name", "kind", "required"}:
|
|
20
|
+
raise InputError("Invalid signature parameter")
|
|
21
|
+
n, kind, required = (
|
|
22
|
+
p.get("name"),
|
|
23
|
+
p.get("kind", "positional_or_keyword"),
|
|
24
|
+
p.get("required", True),
|
|
25
|
+
)
|
|
26
|
+
_validate_parameter(n, kind, required)
|
|
27
|
+
try:
|
|
28
|
+
default = (
|
|
29
|
+
inspect.Parameter.empty
|
|
30
|
+
if required or kind in {"var_positional", "var_keyword"}
|
|
31
|
+
else None
|
|
32
|
+
)
|
|
33
|
+
return inspect.Parameter(n, KINDS[kind], default=default)
|
|
34
|
+
except (TypeError, ValueError) as exc:
|
|
35
|
+
raise InputError("Invalid signature parameter shape") from exc
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _validate_parameter(n, kind, required):
|
|
39
|
+
if (
|
|
40
|
+
not isinstance(n, str)
|
|
41
|
+
or not n.isidentifier()
|
|
42
|
+
or len(n) > 100
|
|
43
|
+
or not isinstance(kind, str)
|
|
44
|
+
or kind not in KINDS
|
|
45
|
+
or type(required) is not bool
|
|
46
|
+
):
|
|
47
|
+
raise InputError("Invalid name, kind or required flag")
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _python_shape(signature):
|
|
51
|
+
if set(signature) - {"name", "parameters"}:
|
|
52
|
+
raise InputError("Unexpected Python signature field")
|
|
53
|
+
params = signature.get("parameters")
|
|
54
|
+
if not isinstance(params, list) or len(params) > 100:
|
|
55
|
+
raise InputError("Signature parameters must be a bounded list")
|
|
56
|
+
descriptors = [_parameter(p) for p in params]
|
|
57
|
+
try:
|
|
58
|
+
return inspect.Signature(descriptors)
|
|
59
|
+
except (TypeError, ValueError) as exc:
|
|
60
|
+
raise InputError("Invalid parameter ordering or duplicate names") from exc
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _python_call(call_source, name, signature, result):
|
|
64
|
+
shape = _python_shape(signature)
|
|
65
|
+
try:
|
|
66
|
+
node = ast.parse(call_source.strip(), mode="eval").body
|
|
67
|
+
except (SyntaxError, ValueError, RecursionError):
|
|
68
|
+
return result(
|
|
69
|
+
"unknown", "Call source is not a valid isolated Python expression."
|
|
70
|
+
)
|
|
71
|
+
if not _matching_python_name(node, name):
|
|
72
|
+
return result("unknown", "Call is not a direct matching identifier.")
|
|
73
|
+
if _expanded_python_args(node):
|
|
74
|
+
return result("unknown", "Argument expansion requires runtime values.")
|
|
75
|
+
return _bind_python(shape, node, result)
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _matching_python_name(node, name):
|
|
79
|
+
return (
|
|
80
|
+
isinstance(node, ast.Call)
|
|
81
|
+
and isinstance(node.func, ast.Name)
|
|
82
|
+
and node.func.id == name
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _expanded_python_args(node):
|
|
87
|
+
return any(isinstance(n, ast.Starred) for n in node.args) or any(
|
|
88
|
+
k.arg is None for k in node.keywords
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def _bind_python(shape, node, result):
|
|
93
|
+
names = [k.arg for k in node.keywords]
|
|
94
|
+
if len(set(names)) != len(names):
|
|
95
|
+
return result("mismatch", "Duplicate keyword names in supplied call.")
|
|
96
|
+
try:
|
|
97
|
+
shape.bind(*([None] * len(node.args)), **dict.fromkeys(names))
|
|
98
|
+
except TypeError as exc:
|
|
99
|
+
return result(
|
|
100
|
+
"mismatch", str(exc), positional_count=len(node.args), keywords=names
|
|
101
|
+
)
|
|
102
|
+
return result(
|
|
103
|
+
"matches_supplied_signature",
|
|
104
|
+
"Argument shape matches the supplied parameter contract.",
|
|
105
|
+
positional_count=len(node.args),
|
|
106
|
+
keywords=names,
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _javascript_contract(signature, language):
|
|
111
|
+
if language not in {"javascript", "jsx", "typescript", "tsx"}:
|
|
112
|
+
raise InputError("Unsupported call language")
|
|
113
|
+
if set(signature) - {"name", "min_positional", "max_positional"}:
|
|
114
|
+
raise InputError("Unexpected JavaScript signature field")
|
|
115
|
+
minimum, maximum = signature.get("min_positional"), signature.get("max_positional")
|
|
116
|
+
if (
|
|
117
|
+
type(minimum) is not int
|
|
118
|
+
or not 0 <= minimum <= 100
|
|
119
|
+
or not _valid_maximum(minimum, maximum)
|
|
120
|
+
):
|
|
121
|
+
raise InputError("Invalid supplied positional contract")
|
|
122
|
+
return minimum, maximum
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def _valid_maximum(minimum, maximum):
|
|
126
|
+
return maximum is None or (type(maximum) is int and minimum <= maximum <= 100)
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _direct_expression(root):
|
|
130
|
+
statements = [n for n in root.named_children if n.type != "comment"]
|
|
131
|
+
if len(statements) != 1 or statements[0].type != "expression_statement":
|
|
132
|
+
return None
|
|
133
|
+
expression = statements[0].named_children
|
|
134
|
+
if len(expression) != 1 or expression[0].type != "call_expression":
|
|
135
|
+
return None
|
|
136
|
+
return expression[0]
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _matching_js_name(raw, call, name):
|
|
140
|
+
fn = call.child_by_field_name("function")
|
|
141
|
+
args = call.child_by_field_name("arguments")
|
|
142
|
+
if (
|
|
143
|
+
fn is None
|
|
144
|
+
or fn.type != "identifier"
|
|
145
|
+
or raw[fn.start_byte : fn.end_byte].decode() != name
|
|
146
|
+
or args is None
|
|
147
|
+
):
|
|
148
|
+
return None
|
|
149
|
+
return args
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _js_arguments(call, args, result):
|
|
153
|
+
if any(n.type == "optional_chain" for n in call.children):
|
|
154
|
+
return None, result("unknown", "Optional call is dynamic.")
|
|
155
|
+
values = [n for n in args.named_children if n.type != "comment"]
|
|
156
|
+
if any(n.type == "spread_element" for n in values):
|
|
157
|
+
return None, result("unknown", "Spread arguments require runtime values.")
|
|
158
|
+
return len(values), None
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _js_call(call_source, name, signature, language, result):
|
|
162
|
+
minimum, maximum = _javascript_contract(signature, language)
|
|
163
|
+
parsed = parse_tree(call_source, language)
|
|
164
|
+
if parsed is None:
|
|
165
|
+
return result("unknown", "Static parser unavailable.")
|
|
166
|
+
raw, root = parsed
|
|
167
|
+
if root.has_error:
|
|
168
|
+
return result("unknown", "Call source does not match the selected grammar.")
|
|
169
|
+
call = _direct_expression(root)
|
|
170
|
+
if call is None:
|
|
171
|
+
return result("unknown", "Supply a single direct call expression.")
|
|
172
|
+
args = _matching_js_name(raw, call, name)
|
|
173
|
+
if args is None:
|
|
174
|
+
return result("unknown", "Call is not a direct matching identifier.")
|
|
175
|
+
count, error = _js_arguments(call, args, result)
|
|
176
|
+
if error is not None:
|
|
177
|
+
return error
|
|
178
|
+
return _compare_count(count, minimum, maximum, result)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _compare_count(count, minimum, maximum, result):
|
|
182
|
+
if count < minimum or maximum is not None and count > maximum:
|
|
183
|
+
return result(
|
|
184
|
+
"mismatch",
|
|
185
|
+
"Argument count differs from supplied contract (not a JavaScript runtime syntax error).",
|
|
186
|
+
positional_count=count,
|
|
187
|
+
)
|
|
188
|
+
return result(
|
|
189
|
+
"matches_supplied_signature",
|
|
190
|
+
"Argument count matches the supplied contract.",
|
|
191
|
+
positional_count=count,
|
|
192
|
+
)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _valid_name(name, language):
|
|
196
|
+
if not isinstance(name, str) or len(name) > 100:
|
|
197
|
+
return False
|
|
198
|
+
if language == "python":
|
|
199
|
+
return name.isidentifier()
|
|
200
|
+
return re.fullmatch(r"[$A-Za-z_][$A-Za-z_0-9]*", name) is not None
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def compare_call_signature(call_source, signature, language="python"):
|
|
204
|
+
bounded(call_source, name="call")
|
|
205
|
+
if len(call_source) > 4096 or not isinstance(signature, dict):
|
|
206
|
+
raise InputError("Call/signature input exceeds supported limits")
|
|
207
|
+
|
|
208
|
+
def result(status, reason, **detail):
|
|
209
|
+
return dict(
|
|
210
|
+
status=status,
|
|
211
|
+
reason=reason,
|
|
212
|
+
language=language,
|
|
213
|
+
detail=detail,
|
|
214
|
+
limitations=[
|
|
215
|
+
"Compares only the caller-provided signature against a supplied direct call shape; no runtime, type inference, overload or import resolution."
|
|
216
|
+
],
|
|
217
|
+
)
|
|
218
|
+
|
|
219
|
+
name = signature.get("name")
|
|
220
|
+
if not _valid_name(name, language):
|
|
221
|
+
raise InputError("Signature requires a simple identifier name")
|
|
222
|
+
if language == "python":
|
|
223
|
+
return _python_call(call_source, name, signature, result)
|
|
224
|
+
return _js_call(call_source, name, signature, language, result)
|