apiverify 0.1.0__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.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kumar Miskin
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: apiverify
3
+ Version: 0.1.0
4
+ Summary: Source-backed check of whether a Python API exists in an exact package version. Answers verified, not_found, or cannot_verify.
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/kumar-miskin/apiverify
7
+ Project-URL: Source, https://github.com/kumar-miskin/apiverify
8
+ Project-URL: Issues, https://github.com/kumar-miskin/apiverify/issues
9
+ Keywords: mcp,ai-agents,api-verification,hallucination,pypi
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Quality Assurance
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ <!-- mcp-name: io.github.kumar-miskin/apiverify -->
19
+ # apiverify
20
+
21
+ Does this Python API exist in this exact package version? apiverify answers from the
22
+ published source of that version, not from docs or model memory.
23
+
24
+ Three answers only:
25
+
26
+ - `verified`: found. Returns file, line, signature, and deprecation signals.
27
+ - `not_found`: every lookup path was followed and the name is absent.
28
+ - `cannot_verify`: the answer depends on something static analysis cannot settle
29
+ (module-level `__getattr__`, a base class or re-export from outside the package,
30
+ a file that will not parse). The agent should not assume either way.
31
+
32
+ It downloads the release from PyPI, checks the sha256 PyPI lists for it, unpacks it
33
+ safely, and reads it with `ast`. It never imports or runs package code. No dependencies.
34
+
35
+ ## Use
36
+
37
+ ```
38
+ python -m apiverify.cli requests.Session.get --version 2.31.0
39
+ python -m apiverify.cli requests.exceptions.JSONDecodeError -v 2.26.0 # not_found
40
+ python -m apiverify.cli requests.exceptions.JSONDecodeError -v 2.27.0 # verified
41
+ python -m apiverify.cli PIL.Image.open -v 10.0.0 --package pillow -k mode
42
+ ```
43
+
44
+ Exit code: 0 verified, 1 not_found, 2 cannot_verify.
45
+
46
+ ## Install
47
+
48
+ ```
49
+ pip install apiverify # or: uvx apiverify-mcp (MCP server)
50
+ ```
51
+
52
+ ## As an MCP server (stdio)
53
+
54
+ Tool: `verify_python_api` with `symbol`, `version`, optional `package`, `kwargs`.
55
+
56
+ ```json
57
+ { "mcpServers": { "apiverify": { "command": "uvx", "args": ["--from", "apiverify", "apiverify-mcp"] } } }
58
+ ```
59
+
60
+ (From a clone you can also use `python -m apiverify.mcp_server`.)
61
+
62
+ Suggested line for an agent's instructions file (AGENTS.md / CLAUDE.md):
63
+ "Before calling a library API you are not certain exists in the project's pinned
64
+ version, call verify_python_api. Treat cannot_verify as unknown, not as yes."
65
+
66
+ ## Tested scope (see `eval/`)
67
+
68
+ Unit tests: `python -m unittest discover -s tests` (offline fixtures, 14 tests).
69
+
70
+ Runtime comparison: `python eval/run_eval.py` installs exact versions of requests (4),
71
+ click (3) and flask (3), asks Python itself whether each candidate symbol exists, and
72
+ compares. Candidates are all public names found across the tested versions plus invented
73
+ decoys. Result of the last run is in `eval/last_run.txt`: 2,411 correct, 0 false
74
+ positives, 0 false negatives, 442 abstentions (all flask, mostly names re-exported
75
+ from werkzeug/jinja2, which live outside the flask artifact), 2 instance attributes
76
+ not scored.
77
+
78
+ ## Limits
79
+
80
+ - Python on PyPI only. No JavaScript, Rust or Go yet.
81
+ - Static analysis. Names created at runtime are reported as `cannot_verify`, not guessed.
82
+ - Not scored in the eval: keyword-argument checks, deprecation signals, and
83
+ `instance attribute` results.
84
+ - The eval's candidates mostly come from names that exist in some version, with only a
85
+ few decoys per library, so it measures version differences well and hallucinated
86
+ names weakly. It is three libraries, not a benchmark.
87
+ - It has not been compared against Context7 or any retrieval tool. That comparison
88
+ needs an agent harness and model spend, and is not done.
89
+ - No evidence yet that developers would pay for it or that agents call it unprompted.
90
+ - Needs network access to pypi.org and files.pythonhosted.org. Artifacts are cached in
91
+ `$APIVERIFY_CACHE`.
92
+
93
+ ## Reaching agents
94
+
95
+ See `DISTRIBUTION.md`.
@@ -0,0 +1,78 @@
1
+ <!-- mcp-name: io.github.kumar-miskin/apiverify -->
2
+ # apiverify
3
+
4
+ Does this Python API exist in this exact package version? apiverify answers from the
5
+ published source of that version, not from docs or model memory.
6
+
7
+ Three answers only:
8
+
9
+ - `verified`: found. Returns file, line, signature, and deprecation signals.
10
+ - `not_found`: every lookup path was followed and the name is absent.
11
+ - `cannot_verify`: the answer depends on something static analysis cannot settle
12
+ (module-level `__getattr__`, a base class or re-export from outside the package,
13
+ a file that will not parse). The agent should not assume either way.
14
+
15
+ It downloads the release from PyPI, checks the sha256 PyPI lists for it, unpacks it
16
+ safely, and reads it with `ast`. It never imports or runs package code. No dependencies.
17
+
18
+ ## Use
19
+
20
+ ```
21
+ python -m apiverify.cli requests.Session.get --version 2.31.0
22
+ python -m apiverify.cli requests.exceptions.JSONDecodeError -v 2.26.0 # not_found
23
+ python -m apiverify.cli requests.exceptions.JSONDecodeError -v 2.27.0 # verified
24
+ python -m apiverify.cli PIL.Image.open -v 10.0.0 --package pillow -k mode
25
+ ```
26
+
27
+ Exit code: 0 verified, 1 not_found, 2 cannot_verify.
28
+
29
+ ## Install
30
+
31
+ ```
32
+ pip install apiverify # or: uvx apiverify-mcp (MCP server)
33
+ ```
34
+
35
+ ## As an MCP server (stdio)
36
+
37
+ Tool: `verify_python_api` with `symbol`, `version`, optional `package`, `kwargs`.
38
+
39
+ ```json
40
+ { "mcpServers": { "apiverify": { "command": "uvx", "args": ["--from", "apiverify", "apiverify-mcp"] } } }
41
+ ```
42
+
43
+ (From a clone you can also use `python -m apiverify.mcp_server`.)
44
+
45
+ Suggested line for an agent's instructions file (AGENTS.md / CLAUDE.md):
46
+ "Before calling a library API you are not certain exists in the project's pinned
47
+ version, call verify_python_api. Treat cannot_verify as unknown, not as yes."
48
+
49
+ ## Tested scope (see `eval/`)
50
+
51
+ Unit tests: `python -m unittest discover -s tests` (offline fixtures, 14 tests).
52
+
53
+ Runtime comparison: `python eval/run_eval.py` installs exact versions of requests (4),
54
+ click (3) and flask (3), asks Python itself whether each candidate symbol exists, and
55
+ compares. Candidates are all public names found across the tested versions plus invented
56
+ decoys. Result of the last run is in `eval/last_run.txt`: 2,411 correct, 0 false
57
+ positives, 0 false negatives, 442 abstentions (all flask, mostly names re-exported
58
+ from werkzeug/jinja2, which live outside the flask artifact), 2 instance attributes
59
+ not scored.
60
+
61
+ ## Limits
62
+
63
+ - Python on PyPI only. No JavaScript, Rust or Go yet.
64
+ - Static analysis. Names created at runtime are reported as `cannot_verify`, not guessed.
65
+ - Not scored in the eval: keyword-argument checks, deprecation signals, and
66
+ `instance attribute` results.
67
+ - The eval's candidates mostly come from names that exist in some version, with only a
68
+ few decoys per library, so it measures version differences well and hallucinated
69
+ names weakly. It is three libraries, not a benchmark.
70
+ - It has not been compared against Context7 or any retrieval tool. That comparison
71
+ needs an agent harness and model spend, and is not done.
72
+ - No evidence yet that developers would pay for it or that agents call it unprompted.
73
+ - Needs network access to pypi.org and files.pythonhosted.org. Artifacts are cached in
74
+ `$APIVERIFY_CACHE`.
75
+
76
+ ## Reaching agents
77
+
78
+ See `DISTRIBUTION.md`.
@@ -0,0 +1,4 @@
1
+ from .resolve import verify_symbol, Result # noqa: F401
2
+ from .fetch import fetch_source # noqa: F401
3
+
4
+ __version__ = "0.1.0"
@@ -0,0 +1,21 @@
1
+ import argparse
2
+ import json
3
+ import sys
4
+
5
+ from .resolve import verify_symbol
6
+
7
+
8
+ def main(argv=None):
9
+ p = argparse.ArgumentParser(prog="apiverify", description="Does this Python API exist in this exact package version?")
10
+ p.add_argument("symbol", help="dotted path, e.g. requests.Session.get")
11
+ p.add_argument("--version", "-v", default="latest", help="exact version on PyPI (default: latest)")
12
+ p.add_argument("--package", "-p", help="PyPI name if it differs from the import name (e.g. pillow for PIL)")
13
+ p.add_argument("--kwarg", "-k", action="append", default=[], help="keyword argument to check (repeatable)")
14
+ a = p.parse_args(argv)
15
+ r = verify_symbol(a.symbol, a.version, a.package, a.kwarg or None)
16
+ print(json.dumps(r.to_dict(), indent=2))
17
+ return {"verified": 0, "not_found": 1, "cannot_verify": 2}[r.status]
18
+
19
+
20
+ if __name__ == "__main__":
21
+ sys.exit(main())
@@ -0,0 +1,128 @@
1
+ """Download the exact released artifact from PyPI and unpack it.
2
+
3
+ Evidence comes from the published package itself, verified against the
4
+ sha256 PyPI lists for that file. Nothing is guessed from docs or memory.
5
+ """
6
+ import hashlib
7
+ import json
8
+ import os
9
+ import re
10
+ import tarfile
11
+ import tempfile
12
+ import urllib.error
13
+ import urllib.request
14
+ import zipfile
15
+
16
+ CACHE = os.environ.get("APIVERIFY_CACHE", os.path.join(tempfile.gettempdir(), "apiverify-cache"))
17
+ PYPI = os.environ.get("APIVERIFY_PYPI", "https://pypi.org/pypi")
18
+ MAX_BYTES = 80 * 1024 * 1024
19
+
20
+
21
+ class FetchError(Exception):
22
+ pass
23
+
24
+
25
+ def _get(url, timeout=30):
26
+ req = urllib.request.Request(url, headers={"User-Agent": "apiverify/0.1"})
27
+ try:
28
+ with urllib.request.urlopen(req, timeout=timeout) as r:
29
+ data = r.read(MAX_BYTES + 1)
30
+ except urllib.error.HTTPError as e:
31
+ raise FetchError(f"HTTP {e.code} for {url}")
32
+ except Exception as e: # network, DNS, timeout
33
+ raise FetchError(f"network error for {url}: {e}")
34
+ if len(data) > MAX_BYTES:
35
+ raise FetchError("artifact too large")
36
+ return data
37
+
38
+
39
+ def _safe_name(s):
40
+ return re.sub(r"[^A-Za-z0-9._-]", "_", s)
41
+
42
+
43
+ def _pick_file(files):
44
+ """Prefer a pure-python wheel, then an sdist. Never run setup code."""
45
+ wheels = [f for f in files if f["packagetype"] == "bdist_wheel" and not f.get("yanked")]
46
+ pure = [f for f in wheels if f["filename"].endswith("-none-any.whl")]
47
+ if pure:
48
+ return pure[0]
49
+ sdists = [f for f in files if f["packagetype"] == "sdist" and not f.get("yanked")]
50
+ if sdists:
51
+ return sdists[0]
52
+ if wheels:
53
+ return wheels[0]
54
+ return None
55
+
56
+
57
+ def _safe_extract_zip(zf, dest):
58
+ base = os.path.realpath(dest)
59
+ for m in zf.namelist():
60
+ p = os.path.realpath(os.path.join(dest, m))
61
+ if not p.startswith(base + os.sep) and p != base:
62
+ raise FetchError("unsafe path in archive")
63
+ zf.extractall(dest)
64
+
65
+
66
+ def _safe_extract_tar(tf, dest):
67
+ base = os.path.realpath(dest)
68
+ for m in tf.getmembers():
69
+ p = os.path.realpath(os.path.join(dest, m.name))
70
+ if not p.startswith(base + os.sep) and p != base:
71
+ raise FetchError("unsafe path in archive")
72
+ if m.issym() or m.islnk() or m.isdev():
73
+ continue
74
+ tf.extract(m, dest)
75
+
76
+
77
+ _MEMO = {}
78
+
79
+
80
+ def fetch_source(package, version):
81
+ k = (package, version)
82
+ if k not in _MEMO:
83
+ _MEMO[k] = _fetch_source(package, version)
84
+ return _MEMO[k]
85
+
86
+
87
+ def _fetch_source(package, version):
88
+ """Return dict(root, filename, sha256, url, version). Raises FetchError."""
89
+ if version in (None, "", "latest"):
90
+ meta_url = f"{PYPI}/{package}/json"
91
+ else:
92
+ meta_url = f"{PYPI}/{package}/{version}/json"
93
+ try:
94
+ meta = json.loads(_get(meta_url))
95
+ except json.JSONDecodeError:
96
+ raise FetchError("bad metadata from index")
97
+ files = meta.get("urls") or []
98
+ f = _pick_file(files)
99
+ if not f:
100
+ raise FetchError(f"no downloadable non-yanked file for {package}=={version}")
101
+ sha = f["digests"]["sha256"]
102
+ resolved = meta["info"]["version"]
103
+ dest = os.path.join(CACHE, _safe_name(package), _safe_name(resolved), sha[:16])
104
+ marker = os.path.join(dest, ".ok")
105
+ info = {"filename": f["filename"], "sha256": sha, "url": f["url"], "version": meta["info"]["version"]}
106
+ if os.path.exists(marker):
107
+ info["root"] = os.path.join(dest, "src")
108
+ return info
109
+ data = _get(f["url"], timeout=60)
110
+ if hashlib.sha256(data).hexdigest() != sha:
111
+ raise FetchError("sha256 mismatch against index metadata")
112
+ src = os.path.join(dest, "src")
113
+ os.makedirs(src, exist_ok=True)
114
+ tmp = os.path.join(dest, f["filename"])
115
+ with open(tmp, "wb") as fh:
116
+ fh.write(data)
117
+ try:
118
+ if f["filename"].endswith((".whl", ".zip")):
119
+ with zipfile.ZipFile(tmp) as zf:
120
+ _safe_extract_zip(zf, src)
121
+ else:
122
+ with tarfile.open(tmp) as tf:
123
+ _safe_extract_tar(tf, src)
124
+ except (zipfile.BadZipFile, tarfile.TarError) as e:
125
+ raise FetchError(f"cannot unpack artifact: {e}")
126
+ open(marker, "w").close()
127
+ info["root"] = src
128
+ return info
@@ -0,0 +1,69 @@
1
+ """Minimal MCP server over stdio (JSON-RPC 2.0, newline-delimited). No dependencies."""
2
+ import json
3
+ import sys
4
+
5
+ from .resolve import verify_symbol
6
+
7
+ PROTOCOL = "2024-11-05"
8
+ TOOL = {
9
+ "name": "verify_python_api",
10
+ "description": (
11
+ "Check whether a Python class, function, method or attribute exists in an EXACT released version of a PyPI package, "
12
+ "by reading that version's published source. Returns status verified (with file, line, signature, deprecation signals), "
13
+ "not_found (only when every lookup path was followed), or cannot_verify (dynamic or external code; do not assume either way). "
14
+ "Use before writing code that calls a library API you are not certain about for the project's pinned version."
15
+ ),
16
+ "inputSchema": {
17
+ "type": "object",
18
+ "properties": {
19
+ "symbol": {"type": "string", "description": "Dotted path, e.g. requests.Session.get"},
20
+ "version": {"type": "string", "description": "Exact version (e.g. 2.31.0) or 'latest'"},
21
+ "package": {"type": "string", "description": "PyPI name if different from the import name"},
22
+ "kwargs": {"type": "array", "items": {"type": "string"}, "description": "Keyword arguments to check against the signature"},
23
+ },
24
+ "required": ["symbol", "version"],
25
+ },
26
+ }
27
+
28
+
29
+ def handle(msg):
30
+ m, i = msg.get("method"), msg.get("id")
31
+ if m == "initialize":
32
+ return {"jsonrpc": "2.0", "id": i, "result": {"protocolVersion": PROTOCOL, "capabilities": {"tools": {}},
33
+ "serverInfo": {"name": "apiverify", "version": "0.1.0"}}}
34
+ if m == "tools/list":
35
+ return {"jsonrpc": "2.0", "id": i, "result": {"tools": [TOOL]}}
36
+ if m == "tools/call":
37
+ p = msg.get("params", {})
38
+ if p.get("name") != TOOL["name"]:
39
+ return {"jsonrpc": "2.0", "id": i, "error": {"code": -32602, "message": "unknown tool"}}
40
+ a = p.get("arguments") or {}
41
+ try:
42
+ r = verify_symbol(a["symbol"], a.get("version", "latest"), a.get("package"), a.get("kwargs"))
43
+ out, err = r.to_dict(), False
44
+ except Exception as e: # never crash the server
45
+ out, err = {"status": "cannot_verify", "reason": f"internal error: {e.__class__.__name__}"}, True
46
+ return {"jsonrpc": "2.0", "id": i, "result": {"content": [{"type": "text", "text": json.dumps(out, indent=2)}], "isError": err}}
47
+ if m == "ping":
48
+ return {"jsonrpc": "2.0", "id": i, "result": {}}
49
+ if i is None:
50
+ return None # notification
51
+ return {"jsonrpc": "2.0", "id": i, "error": {"code": -32601, "message": "method not found"}}
52
+
53
+
54
+ def main():
55
+ for line in sys.stdin:
56
+ line = line.strip()
57
+ if not line:
58
+ continue
59
+ try:
60
+ resp = handle(json.loads(line))
61
+ except json.JSONDecodeError:
62
+ resp = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": "parse error"}}
63
+ if resp is not None:
64
+ sys.stdout.write(json.dumps(resp) + "\n")
65
+ sys.stdout.flush()
66
+
67
+
68
+ if __name__ == "__main__":
69
+ main()
@@ -0,0 +1,456 @@
1
+ """Static, evidence-first resolution of a dotted Python symbol inside an unpacked
2
+ package. It never imports or executes package code.
3
+
4
+ Three outcomes, by design:
5
+ verified the symbol was found; location and signature come from the source
6
+ not_found every lookup path was followed to the end and the name is absent
7
+ cannot_verify the answer depends on something static analysis cannot settle
8
+ (dynamic __getattr__, an external base class or re-export, a
9
+ module missing from the artifact, an unparseable file)
10
+ A "not_found" is only returned when no unresolved escape hatch exists.
11
+ """
12
+ import ast
13
+ import builtins
14
+ import os
15
+ from dataclasses import dataclass, field, asdict
16
+ from typing import Optional
17
+
18
+ from .fetch import fetch_source, FetchError
19
+
20
+ MAX_DEPTH = 12
21
+ _WRAP_OK = {"staticmethod", "classmethod", "property", "overload", "abstractmethod",
22
+ "cached_property", "functools.cached_property", "typing.overload",
23
+ "abc.abstractmethod", "override", "typing.override"}
24
+
25
+
26
+ @dataclass
27
+ class Result:
28
+ status: str
29
+ package: str
30
+ version: Optional[str]
31
+ symbol: str
32
+ kind: Optional[str] = None
33
+ signature: Optional[str] = None
34
+ location: Optional[dict] = None
35
+ deprecation_signals: list = field(default_factory=list)
36
+ params: dict = field(default_factory=dict)
37
+ reason: Optional[str] = None
38
+ notes: list = field(default_factory=list)
39
+ artifact: Optional[dict] = None
40
+
41
+ def to_dict(self):
42
+ return {k: v for k, v in asdict(self).items() if v not in (None, [], {})} | {"status": self.status}
43
+
44
+
45
+ class Found:
46
+ def __init__(self, kind, path, line, node=None, modname=None, extra=None):
47
+ self.kind, self.path, self.line, self.node, self.modname = kind, path, line, node, modname
48
+ self.extra = extra or {}
49
+
50
+
51
+ class Unknown(Exception):
52
+ pass
53
+
54
+
55
+ class Ctx:
56
+ def __init__(self, base):
57
+ self.base = base
58
+ self.cache = {}
59
+ self.flags = [] # reasons that block a not_found conclusion
60
+
61
+ def modpath(self, dotted):
62
+ parts = dotted.split(".")
63
+ d = os.path.join(self.base, *parts)
64
+ if os.path.isfile(os.path.join(d, "__init__.py")):
65
+ return os.path.join(d, "__init__.py"), True
66
+ if os.path.isfile(d + ".py"):
67
+ return d + ".py", False
68
+ return None, False
69
+
70
+ def load(self, dotted):
71
+ if dotted in self.cache:
72
+ return self.cache[dotted]
73
+ path, is_pkg = self.modpath(dotted)
74
+ res = None
75
+ if path:
76
+ try:
77
+ with open(path, "rb") as fh:
78
+ res = (path, is_pkg, ast.parse(fh.read(), filename=path))
79
+ except (SyntaxError, ValueError) as e:
80
+ self.flags.append(f"cannot parse {os.path.relpath(path, self.base)}: {e.__class__.__name__}")
81
+ self.cache[dotted] = res
82
+ return res
83
+
84
+
85
+ def _flat(body):
86
+ """Statements at this scope, descending into if/try/with but not defs."""
87
+ for n in body:
88
+ yield n
89
+ if isinstance(n, ast.If):
90
+ yield from _flat(n.body); yield from _flat(n.orelse)
91
+ elif isinstance(n, ast.Try):
92
+ yield from _flat(n.body); yield from _flat(n.orelse); yield from _flat(n.finalbody)
93
+ for h in n.handlers:
94
+ yield from _flat(h.body)
95
+ elif isinstance(n, (ast.With,)):
96
+ yield from _flat(n.body)
97
+
98
+
99
+ def _targets(n):
100
+ if isinstance(n, ast.Assign):
101
+ for t in n.targets:
102
+ if isinstance(t, ast.Name):
103
+ yield t.id
104
+ elif isinstance(t, (ast.Tuple, ast.List)):
105
+ for e in t.elts:
106
+ if isinstance(e, ast.Name):
107
+ yield e.id
108
+ elif isinstance(n, (ast.AnnAssign, ast.AugAssign)) and isinstance(n.target, ast.Name):
109
+ yield n.target.id
110
+
111
+
112
+ def _dotted(node):
113
+ parts = []
114
+ while isinstance(node, ast.Attribute):
115
+ parts.append(node.attr); node = node.value
116
+ if isinstance(node, ast.Name):
117
+ parts.append(node.id)
118
+ return list(reversed(parts))
119
+ return None
120
+
121
+
122
+ def _abs_module(modname, is_pkg, level, module):
123
+ if level == 0:
124
+ return module or ""
125
+ pkg = modname.split(".") if is_pkg else modname.split(".")[:-1]
126
+ if level - 1 > len(pkg):
127
+ return None
128
+ pkg = pkg[: len(pkg) - (level - 1)]
129
+ return ".".join(pkg + ([module] if module else []))
130
+
131
+
132
+ def lookup_module(ctx, modname, rest, depth=0, seen=None):
133
+ seen = seen or set()
134
+ if depth > MAX_DEPTH:
135
+ raise Unknown("import chain too deep")
136
+ key = (modname, tuple(rest))
137
+ if key in seen:
138
+ return None
139
+ seen = seen | {key}
140
+ m = ctx.load(modname)
141
+ if m is None:
142
+ raise Unknown(f"module {modname} is not in the released artifact (external or unparseable)")
143
+ path, is_pkg, tree = m
144
+ if not rest:
145
+ return Found("module", path, 1, tree, modname)
146
+ name, tail = rest[0], rest[1:]
147
+ unknown = []
148
+ for n in _flat(tree.body):
149
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == name:
150
+ if tail:
151
+ unknown.append(f"{name} is a function; attribute {tail[0]} cannot be checked statically")
152
+ continue
153
+ return Found("function", path, n.lineno, n, modname)
154
+ if isinstance(n, ast.ClassDef) and n.name == name:
155
+ if not tail:
156
+ return Found("class", path, n.lineno, n, modname)
157
+ r = lookup_class(ctx, modname, is_pkg, n, tail, depth + 1, seen)
158
+ if r is not None:
159
+ return r
160
+ continue
161
+ if name in set(_targets(n)):
162
+ val = getattr(n, "value", None)
163
+ d = _dotted(val) if val is not None else None
164
+ if d:
165
+ try:
166
+ r = lookup_module(ctx, modname, d + tail, depth + 1, seen)
167
+ if r is not None:
168
+ return r
169
+ except Unknown as e:
170
+ unknown.append(str(e))
171
+ continue
172
+ if not tail:
173
+ return Found("variable", path, n.lineno, n, modname)
174
+ unknown.append(f"{name} is assigned at line {n.lineno}; attributes of its value cannot be checked statically")
175
+ continue
176
+ if isinstance(n, ast.ImportFrom):
177
+ target = _abs_module(modname, is_pkg, n.level, n.module)
178
+ for a in n.names:
179
+ if a.name == "*":
180
+ if target is None:
181
+ continue
182
+ try:
183
+ r = lookup_module(ctx, target, rest, depth + 1, seen)
184
+ if r is not None:
185
+ return r
186
+ except Unknown as e:
187
+ unknown.append(f"star import from {target}: {e}")
188
+ elif (a.asname or a.name) == name:
189
+ if target is None:
190
+ unknown.append("relative import outside package")
191
+ continue
192
+ if ctx.modpath(target)[0] is None and not ctx.load(target):
193
+ if not tail:
194
+ return Found("name imported from external module", path, n.lineno, None, modname,
195
+ {"external": target})
196
+ unknown.append(f"{name} comes from external module {target}; {tail[0]} cannot be checked")
197
+ continue
198
+ try:
199
+ r = lookup_module(ctx, target, [a.name] + tail, depth + 1, seen)
200
+ if r is None and ctx.modpath(f"{target}.{a.name}")[0]:
201
+ r = lookup_module(ctx, f"{target}.{a.name}", tail, depth + 1, seen)
202
+ if r is not None:
203
+ return r
204
+ except Unknown as e:
205
+ unknown.append(f"re-exported from {target}: {e}")
206
+ elif isinstance(n, ast.Import):
207
+ for a in n.names:
208
+ bound = a.asname or a.name.split(".")[0]
209
+ if bound == name and ctx.modpath(a.name.split(".")[0])[0] is None:
210
+ if not tail:
211
+ return Found("imported external module", path, n.lineno, None, modname, {"external": a.name})
212
+ unknown.append(f"{name} is external module {a.name}; {tail[0]} cannot be checked")
213
+ continue
214
+ if a.asname == name:
215
+ try:
216
+ r = lookup_module(ctx, a.name, tail, depth + 1, seen)
217
+ if r is not None:
218
+ return r
219
+ except Unknown as e:
220
+ unknown.append(str(e))
221
+ # submodule of a package
222
+ if is_pkg and ctx.modpath(f"{modname}.{name}")[0]:
223
+ r = lookup_module(ctx, f"{modname}.{name}", tail, depth + 1, seen)
224
+ if r is not None:
225
+ return r
226
+ for n in _flat(tree.body):
227
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)) and n.name == "__getattr__":
228
+ unknown.append(f"{modname} defines module-level __getattr__ (names may be created lazily)")
229
+ if isinstance(n, ast.Expr) and isinstance(n.value, ast.Call):
230
+ fn = _dotted(n.value.func)
231
+ if fn and fn[-1] in ("setattr",) or (fn and fn[:1] == ["globals"]):
232
+ unknown.append(f"{modname} sets names dynamically")
233
+ for n in ast.walk(tree):
234
+ if isinstance(n, ast.Subscript) and isinstance(n.value, ast.Call):
235
+ fn = _dotted(n.value.func)
236
+ if fn == ["globals"] and isinstance(n.ctx, ast.Store):
237
+ unknown.append(f"{modname} writes to globals()")
238
+ if unknown:
239
+ ctx.flags.extend(unknown)
240
+ return None
241
+
242
+
243
+ def _class_members(cls):
244
+ out = {}
245
+ for n in _flat(cls.body):
246
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
247
+ out[n.name] = ("function", n)
248
+ elif isinstance(n, ast.ClassDef):
249
+ out[n.name] = ("class", n)
250
+ else:
251
+ for t in _targets(n):
252
+ out[t] = ("variable", n)
253
+ return out
254
+
255
+
256
+ def _instance_attrs(cls):
257
+ attrs = {}
258
+ for n in _flat(cls.body):
259
+ if isinstance(n, (ast.FunctionDef, ast.AsyncFunctionDef)):
260
+ for s in ast.walk(n):
261
+ tg = []
262
+ if isinstance(s, ast.Assign):
263
+ tg = s.targets
264
+ elif isinstance(s, (ast.AnnAssign, ast.AugAssign)):
265
+ tg = [s.target]
266
+ for t in tg:
267
+ if isinstance(t, ast.Attribute) and isinstance(t.value, ast.Name) and t.value.id == "self":
268
+ attrs.setdefault(t.attr, s.lineno)
269
+ return attrs
270
+
271
+
272
+ def lookup_class(ctx, modname, is_pkg, cls, rest, depth, seen):
273
+ name, tail = rest[0], rest[1:]
274
+ path = ctx.load(modname)[0]
275
+ members = _class_members(cls)
276
+ if name in members:
277
+ kind, node = members[name]
278
+ if tail:
279
+ if kind == "class":
280
+ return lookup_class(ctx, modname, is_pkg, node, tail, depth + 1, seen)
281
+ ctx.flags.append(f"{name} is not a class; {tail[0]} cannot be checked statically")
282
+ return None
283
+ k = "method" if kind == "function" else ("class" if kind == "class" else "class attribute")
284
+ if kind == "function":
285
+ for d in node.decorator_list:
286
+ dn = ".".join(_dotted(d) or []) if not isinstance(d, ast.Call) else ".".join(_dotted(d.func) or [])
287
+ if dn.split(".")[-1] in ("property", "cached_property"):
288
+ k = "property"
289
+ return Found(k, path, node.lineno, node, modname, {"cls": cls.name})
290
+ ia = _instance_attrs(cls)
291
+ if name in ia and not tail:
292
+ return Found("instance attribute", path, ia[name], None, modname, {"cls": cls.name})
293
+ if name in ("__getattr__",):
294
+ pass
295
+ if "__getattr__" in members or "__getattribute__" in members:
296
+ ctx.flags.append(f"class {cls.name} defines __getattr__ (attributes may be dynamic)")
297
+ if any(k.arg == "metaclass" for k in cls.keywords):
298
+ ctx.flags.append(f"class {cls.name} uses a custom metaclass")
299
+ for b in cls.bases:
300
+ d = _dotted(b)
301
+ if not d:
302
+ ctx.flags.append(f"class {cls.name} has a base that is not a plain name")
303
+ continue
304
+ if len(d) == 1 and hasattr(builtins, d[0]):
305
+ bt = getattr(builtins, d[0])
306
+ if not tail and hasattr(bt, name):
307
+ return Found("inherited builtin member", path, cls.lineno, None, modname, {"cls": cls.name, "base": d[0]})
308
+ continue
309
+ try:
310
+ r = lookup_module(ctx, modname, d, depth + 1, seen)
311
+ except Unknown as e:
312
+ ctx.flags.append(f"base class {'.'.join(d)} of {cls.name} cannot be resolved: {e}")
313
+ continue
314
+ if r is None or r.kind != "class":
315
+ ctx.flags.append(f"base class {'.'.join(d)} of {cls.name} cannot be resolved in this artifact")
316
+ continue
317
+ sub = lookup_class(ctx, r.modname, ctx.load(r.modname)[1], r.node, rest, depth + 1, seen)
318
+ if sub is not None:
319
+ sub.extra["inherited_from"] = r.node.name
320
+ return sub
321
+ return None
322
+
323
+
324
+ # ---------- details ----------
325
+ def _sig(node):
326
+ a = node.args
327
+ try:
328
+ return f"{node.name}({ast.unparse(a)})" + (f" -> {ast.unparse(node.returns)}" if node.returns else "")
329
+ except Exception:
330
+ return None
331
+
332
+
333
+ def _deprecation(node):
334
+ sig = []
335
+ for d in getattr(node, "decorator_list", []):
336
+ try:
337
+ t = ast.unparse(d)
338
+ except Exception:
339
+ continue
340
+ if "deprecat" in t.lower():
341
+ sig.append(f"decorator @{t[:80]} at line {d.lineno}")
342
+ doc = ast.get_docstring(node) if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)) else None
343
+ if doc and "deprecated" in doc.lower():
344
+ sig.append("docstring mentions 'deprecated'")
345
+ for s in ast.walk(node) if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) else []:
346
+ if isinstance(s, ast.Call):
347
+ fn = _dotted(s.func)
348
+ if fn and fn[-1] == "warn":
349
+ try:
350
+ if "deprecat" in ast.unparse(s).lower():
351
+ sig.append(f"warns about deprecation at line {s.lineno}")
352
+ break
353
+ except Exception:
354
+ pass
355
+ return sig
356
+
357
+
358
+ def _param_status(node, kwargs, ctx, found):
359
+ if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
360
+ return {k: "cannot_verify" for k in kwargs}
361
+ a = node.args
362
+ named = {x.arg for x in a.args + a.kwonlyargs}
363
+ altered = False
364
+ for d in node.decorator_list:
365
+ dn = ".".join(_dotted(d.func if isinstance(d, ast.Call) else d) or ["?"])
366
+ if dn not in _WRAP_OK and dn.split(".")[-1] not in _WRAP_OK:
367
+ altered = True
368
+ out = {}
369
+ for k in kwargs:
370
+ if k in named:
371
+ out[k] = "accepted"
372
+ elif a.kwarg is not None:
373
+ out[k] = "cannot_verify (function takes **%s)" % a.kwarg.arg
374
+ elif altered:
375
+ out[k] = "cannot_verify (decorated, signature may differ)"
376
+ else:
377
+ out[k] = "not_accepted"
378
+ return out
379
+
380
+
381
+ _CTXS = {}
382
+
383
+
384
+ def verify_symbol(symbol, version="latest", package=None, kwargs=None, _root=None):
385
+ top = symbol.split(".")[0]
386
+ package = package or top
387
+ res = Result(status="cannot_verify", package=package, version=version, symbol=symbol)
388
+ if not symbol or any(not p.isidentifier() for p in symbol.split(".")):
389
+ res.reason = "symbol must be a dotted Python path like requests.Session.get"
390
+ return res
391
+ try:
392
+ if _root:
393
+ info = {"root": _root, "filename": "local", "sha256": None, "url": None, "version": version}
394
+ else:
395
+ info = fetch_source(package, version)
396
+ except FetchError as e:
397
+ res.reason = f"could not obtain package source: {e}"
398
+ return res
399
+ res.version = info["version"]
400
+ res.artifact = {k: info[k] for k in ("filename", "sha256", "url")}
401
+ base = None
402
+ cands = [info["root"]] + [os.path.join(info["root"], d) for d in sorted(os.listdir(info["root"]))]
403
+ cands += [os.path.join(c, "src") for c in list(cands)]
404
+ for c in cands:
405
+ if os.path.isdir(c) and (os.path.isfile(os.path.join(c, top, "__init__.py")) or os.path.isfile(os.path.join(c, top + ".py"))):
406
+ base = c
407
+ break
408
+ if base is None:
409
+ res.reason = f"top-level module '{top}' not found in {package}=={res.version}; pass package= if the PyPI name differs from the import name"
410
+ return res
411
+ ctx = _CTXS.setdefault(base, Ctx(base))
412
+ ctx.flags = []
413
+ parts = symbol.split(".")
414
+ try:
415
+ found = lookup_module(ctx, parts[0], parts[1:])
416
+ except Unknown as e:
417
+ ctx.flags.append(str(e))
418
+ found = None
419
+ if found is None:
420
+ if ctx.flags:
421
+ res.reason = "not found by static lookup, but it may exist: " + "; ".join(dict.fromkeys(ctx.flags))[:600]
422
+ res.status = "cannot_verify"
423
+ else:
424
+ res.status = "not_found"
425
+ res.reason = f"no definition, import, or submodule named '{parts[-1]}' on that path in {package}=={res.version}"
426
+ return res
427
+ res.status = "verified"
428
+ res.kind = found.kind
429
+ rel = os.path.relpath(found.path, base)
430
+ res.location = {"file": rel, "line": found.line}
431
+ if "inherited_from" in found.extra:
432
+ res.notes.append(f"inherited from {found.extra['inherited_from']}")
433
+ node = found.node
434
+ sig_node = node
435
+ if found.kind == "class" and node is not None:
436
+ c2 = Ctx(base); c2.cache = ctx.cache
437
+ try:
438
+ init = lookup_class(c2, found.modname, ctx.load(found.modname)[1], node, ["__init__"], 0, set())
439
+ except Unknown:
440
+ init = None
441
+ if init is not None and init.node is not None:
442
+ sig_node = init.node
443
+ res.notes.append("signature shown is __init__")
444
+ else:
445
+ sig_node = None
446
+ res.notes.append("no __init__ found statically (inherited, dataclass, or generated); signature not shown")
447
+ if sig_node is not None and isinstance(sig_node, (ast.FunctionDef, ast.AsyncFunctionDef)):
448
+ res.signature = _sig(sig_node)
449
+ if node is not None:
450
+ res.deprecation_signals = _deprecation(node)
451
+ if kwargs:
452
+ if sig_node is not None and isinstance(sig_node, (ast.FunctionDef, ast.AsyncFunctionDef)):
453
+ res.params = _param_status(sig_node, kwargs, ctx, found)
454
+ else:
455
+ res.params = {k: "cannot_verify (no static signature)" for k in kwargs}
456
+ return res
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.4
2
+ Name: apiverify
3
+ Version: 0.1.0
4
+ Summary: Source-backed check of whether a Python API exists in an exact package version. Answers verified, not_found, or cannot_verify.
5
+ License: MIT
6
+ Project-URL: Homepage, https://github.com/kumar-miskin/apiverify
7
+ Project-URL: Source, https://github.com/kumar-miskin/apiverify
8
+ Project-URL: Issues, https://github.com/kumar-miskin/apiverify/issues
9
+ Keywords: mcp,ai-agents,api-verification,hallucination,pypi
10
+ Classifier: License :: OSI Approved :: MIT License
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Topic :: Software Development :: Quality Assurance
13
+ Requires-Python: >=3.9
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Dynamic: license-file
17
+
18
+ <!-- mcp-name: io.github.kumar-miskin/apiverify -->
19
+ # apiverify
20
+
21
+ Does this Python API exist in this exact package version? apiverify answers from the
22
+ published source of that version, not from docs or model memory.
23
+
24
+ Three answers only:
25
+
26
+ - `verified`: found. Returns file, line, signature, and deprecation signals.
27
+ - `not_found`: every lookup path was followed and the name is absent.
28
+ - `cannot_verify`: the answer depends on something static analysis cannot settle
29
+ (module-level `__getattr__`, a base class or re-export from outside the package,
30
+ a file that will not parse). The agent should not assume either way.
31
+
32
+ It downloads the release from PyPI, checks the sha256 PyPI lists for it, unpacks it
33
+ safely, and reads it with `ast`. It never imports or runs package code. No dependencies.
34
+
35
+ ## Use
36
+
37
+ ```
38
+ python -m apiverify.cli requests.Session.get --version 2.31.0
39
+ python -m apiverify.cli requests.exceptions.JSONDecodeError -v 2.26.0 # not_found
40
+ python -m apiverify.cli requests.exceptions.JSONDecodeError -v 2.27.0 # verified
41
+ python -m apiverify.cli PIL.Image.open -v 10.0.0 --package pillow -k mode
42
+ ```
43
+
44
+ Exit code: 0 verified, 1 not_found, 2 cannot_verify.
45
+
46
+ ## Install
47
+
48
+ ```
49
+ pip install apiverify # or: uvx apiverify-mcp (MCP server)
50
+ ```
51
+
52
+ ## As an MCP server (stdio)
53
+
54
+ Tool: `verify_python_api` with `symbol`, `version`, optional `package`, `kwargs`.
55
+
56
+ ```json
57
+ { "mcpServers": { "apiverify": { "command": "uvx", "args": ["--from", "apiverify", "apiverify-mcp"] } } }
58
+ ```
59
+
60
+ (From a clone you can also use `python -m apiverify.mcp_server`.)
61
+
62
+ Suggested line for an agent's instructions file (AGENTS.md / CLAUDE.md):
63
+ "Before calling a library API you are not certain exists in the project's pinned
64
+ version, call verify_python_api. Treat cannot_verify as unknown, not as yes."
65
+
66
+ ## Tested scope (see `eval/`)
67
+
68
+ Unit tests: `python -m unittest discover -s tests` (offline fixtures, 14 tests).
69
+
70
+ Runtime comparison: `python eval/run_eval.py` installs exact versions of requests (4),
71
+ click (3) and flask (3), asks Python itself whether each candidate symbol exists, and
72
+ compares. Candidates are all public names found across the tested versions plus invented
73
+ decoys. Result of the last run is in `eval/last_run.txt`: 2,411 correct, 0 false
74
+ positives, 0 false negatives, 442 abstentions (all flask, mostly names re-exported
75
+ from werkzeug/jinja2, which live outside the flask artifact), 2 instance attributes
76
+ not scored.
77
+
78
+ ## Limits
79
+
80
+ - Python on PyPI only. No JavaScript, Rust or Go yet.
81
+ - Static analysis. Names created at runtime are reported as `cannot_verify`, not guessed.
82
+ - Not scored in the eval: keyword-argument checks, deprecation signals, and
83
+ `instance attribute` results.
84
+ - The eval's candidates mostly come from names that exist in some version, with only a
85
+ few decoys per library, so it measures version differences well and hallucinated
86
+ names weakly. It is three libraries, not a benchmark.
87
+ - It has not been compared against Context7 or any retrieval tool. That comparison
88
+ needs an agent harness and model spend, and is not done.
89
+ - No evidence yet that developers would pay for it or that agents call it unprompted.
90
+ - Needs network access to pypi.org and files.pythonhosted.org. Artifacts are cached in
91
+ `$APIVERIFY_CACHE`.
92
+
93
+ ## Reaching agents
94
+
95
+ See `DISTRIBUTION.md`.
@@ -0,0 +1,14 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ apiverify/__init__.py
5
+ apiverify/cli.py
6
+ apiverify/fetch.py
7
+ apiverify/mcp_server.py
8
+ apiverify/resolve.py
9
+ apiverify.egg-info/PKG-INFO
10
+ apiverify.egg-info/SOURCES.txt
11
+ apiverify.egg-info/dependency_links.txt
12
+ apiverify.egg-info/entry_points.txt
13
+ apiverify.egg-info/top_level.txt
14
+ tests/test_resolve.py
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ apiverify = apiverify.cli:main
3
+ apiverify-mcp = apiverify.mcp_server:main
@@ -0,0 +1 @@
1
+ apiverify
@@ -0,0 +1,30 @@
1
+ [project]
2
+ name = "apiverify"
3
+ version = "0.1.0"
4
+ description = "Source-backed check of whether a Python API exists in an exact package version. Answers verified, not_found, or cannot_verify."
5
+ readme = "README.md"
6
+ requires-python = ">=3.9"
7
+ license = { text = "MIT" }
8
+ dependencies = []
9
+ keywords = ["mcp", "ai-agents", "api-verification", "hallucination", "pypi"]
10
+ classifiers = [
11
+ "License :: OSI Approved :: MIT License",
12
+ "Programming Language :: Python :: 3",
13
+ "Topic :: Software Development :: Quality Assurance",
14
+ ]
15
+
16
+ [project.urls]
17
+ Homepage = "https://github.com/kumar-miskin/apiverify"
18
+ Source = "https://github.com/kumar-miskin/apiverify"
19
+ Issues = "https://github.com/kumar-miskin/apiverify/issues"
20
+
21
+ [project.scripts]
22
+ apiverify = "apiverify.cli:main"
23
+ apiverify-mcp = "apiverify.mcp_server:main"
24
+
25
+ [build-system]
26
+ requires = ["setuptools>=61"]
27
+ build-backend = "setuptools.build_meta"
28
+
29
+ [tool.setuptools]
30
+ packages = ["apiverify"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,142 @@
1
+ import json, os, subprocess, sys, tempfile, textwrap, unittest
2
+ sys.path.insert(0, os.path.join(os.path.dirname(__file__), ".."))
3
+ from apiverify.resolve import verify_symbol, _CTXS
4
+ from apiverify import mcp_server
5
+
6
+
7
+ def make(files):
8
+ root = tempfile.mkdtemp()
9
+ for p, c in files.items():
10
+ fp = os.path.join(root, p)
11
+ os.makedirs(os.path.dirname(fp), exist_ok=True)
12
+ open(fp, "w").write(textwrap.dedent(c))
13
+ _CTXS.clear()
14
+ return root
15
+
16
+
17
+ LIB = {
18
+ "lib/__init__.py": """
19
+ from .core import Client, make_client
20
+ from . import util
21
+ from .compat import *
22
+ VERSION = "1"
23
+ """,
24
+ "lib/core.py": """
25
+ import warnings
26
+ from .base import Base
27
+ from external_pkg import Thing
28
+ class Client(Base):
29
+ retries = 3
30
+ def __init__(self, url, *, timeout=5, verify=True):
31
+ self.url = url
32
+ self.session = None
33
+ def get(self, path, params=None):
34
+ return 1
35
+ @property
36
+ def ready(self): return True
37
+ def old(self):
38
+ '''Deprecated: use get.'''
39
+ warnings.warn("old is deprecated", DeprecationWarning)
40
+ class Odd(Thing):
41
+ pass
42
+ def make_client(url, **opts): pass
43
+ """,
44
+ "lib/base.py": """
45
+ class Base:
46
+ def close(self): pass
47
+ """,
48
+ "lib/util.py": """
49
+ def helper(a, b=2): pass
50
+ """,
51
+ "lib/compat.py": """
52
+ def legacy_name(): pass
53
+ """,
54
+ "lib/lazy/__init__.py": """
55
+ def __getattr__(name): raise AttributeError(name)
56
+ """,
57
+ }
58
+
59
+
60
+ class T(unittest.TestCase):
61
+ @classmethod
62
+ def setUpClass(cls):
63
+ cls.root = make(LIB)
64
+
65
+ def v(self, sym, **kw):
66
+ return verify_symbol(sym, "1.0", "lib", _root=self.root, **kw)
67
+
68
+ def test_class_and_signature(self):
69
+ r = self.v("lib.Client")
70
+ self.assertEqual(r.status, "verified")
71
+ self.assertIn("timeout=5", r.signature)
72
+ self.assertEqual(r.location["file"], "lib/core.py")
73
+
74
+ def test_inherited_method(self):
75
+ r = self.v("lib.Client.close")
76
+ self.assertEqual(r.status, "verified")
77
+ self.assertIn("inherited from Base", r.notes)
78
+
79
+ def test_reexport_and_star_import(self):
80
+ self.assertEqual(self.v("lib.make_client").status, "verified")
81
+ self.assertEqual(self.v("lib.legacy_name").status, "verified")
82
+ self.assertEqual(self.v("lib.util.helper").status, "verified")
83
+
84
+ def test_missing_is_not_found(self):
85
+ self.assertEqual(self.v("lib.Client.fetch").status, "not_found")
86
+ self.assertEqual(self.v("lib.nothing").status, "not_found")
87
+ self.assertEqual(self.v("lib.util.nothing").status, "not_found")
88
+
89
+ def test_external_base_abstains(self):
90
+ r = self.v("lib.core.Odd.anything")
91
+ self.assertEqual(r.status, "cannot_verify")
92
+ self.assertIn("Thing", r.reason)
93
+
94
+ def test_module_getattr_abstains(self):
95
+ r = self.v("lib.lazy.whatever")
96
+ self.assertEqual(r.status, "cannot_verify")
97
+
98
+ def test_external_reexport_exists_but_attrs_unknown(self):
99
+ self.assertEqual(self.v("lib.core.Thing").status, "verified")
100
+ self.assertEqual(self.v("lib.core.Thing.x").status, "cannot_verify")
101
+
102
+ def test_instance_attribute_and_property(self):
103
+ self.assertEqual(self.v("lib.Client.session").kind, "instance attribute")
104
+ self.assertEqual(self.v("lib.Client.ready").kind, "property")
105
+
106
+ def test_deprecation_signals(self):
107
+ r = self.v("lib.Client.old")
108
+ self.assertTrue(r.deprecation_signals)
109
+ self.assertFalse(self.v("lib.Client.get").deprecation_signals)
110
+
111
+ def test_kwargs(self):
112
+ r = self.v("lib.Client", kwargs=["timeout", "verify", "retry"])
113
+ self.assertEqual(r.params["timeout"], "accepted")
114
+ self.assertEqual(r.params["retry"], "not_accepted")
115
+ r = self.v("lib.make_client", kwargs=["anything"])
116
+ self.assertIn("cannot_verify", r.params["anything"])
117
+
118
+ def test_bad_input(self):
119
+ self.assertEqual(verify_symbol("not a symbol", "1", _root=self.root).status, "cannot_verify")
120
+
121
+ def test_syntax_error_abstains(self):
122
+ root = make({"bad/__init__.py": "def (:\n"})
123
+ r = verify_symbol("bad.x", "1", "bad", _root=root)
124
+ self.assertEqual(r.status, "cannot_verify")
125
+
126
+ def test_wrong_top_module(self):
127
+ r = verify_symbol("other.x", "1", "lib", _root=self.root)
128
+ self.assertEqual(r.status, "cannot_verify")
129
+
130
+
131
+ class MCP(unittest.TestCase):
132
+ def test_protocol(self):
133
+ self.assertEqual(mcp_server.handle({"jsonrpc": "2.0", "id": 1, "method": "initialize"})["result"]["serverInfo"]["name"], "apiverify")
134
+ tl = mcp_server.handle({"jsonrpc": "2.0", "id": 2, "method": "tools/list"})
135
+ self.assertEqual(tl["result"]["tools"][0]["name"], "verify_python_api")
136
+ self.assertIsNone(mcp_server.handle({"jsonrpc": "2.0", "method": "notifications/initialized"}))
137
+ bad = mcp_server.handle({"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "zzz"}})
138
+ self.assertIn("error", bad)
139
+
140
+
141
+ if __name__ == "__main__":
142
+ unittest.main()