Skip to main content
Glama
README.md
# phantom-api

[![CI](https://github.com/MertTomak/phantom-api/actions/workflows/ci.yml/badge.svg)](https://github.com/MertTomak/phantom-api/actions/workflows/ci.yml)

Finds calls to library APIs that don't exist in Python code, the kind LLMs invent: `df.to_markdown_table()`, `np.linalg.mean()`, `os.makedirs(path, exists_ok=True)`. It reads the code without running it, checks every library reference against what the library actually provides and suggests the real name.

```
$ phantom-api answer.md
answer.md:12:1: error: `to_markdown_table` doesn't exist on `pandas.DataFrame` objects (pandas 3.1)
    df.to_markdown_table  did you mean: to_markdown
answer.md:15:5: error: `mean` doesn't exist on `numpy.linalg` (NumPy 2.5)
    np.linalg.mean  did you mean: numpy.mean, numpy.ma.mean
answer.md:24:1: error: `joinpath` doesn't exist on `os.path` (Python 3.12 (runtime))
    os.path.joinpath  did you mean: join, commonpath, normpath
answer.md: 42 API references checked, 11 errors, 1 warnings
```

No dependencies, no API keys and nothing third-party gets imported or executed. It works on plain Python files and on markdown answers (it pulls out the code blocks and checks them as one program, so imports in the first block carry over to the rest).

## How it works

**Two sources of truth.**
- **Standard library:** checked at runtime against the Python that runs the tool. Answers are exact, and keyword arguments are checked against real signatures.
- **NumPy, pandas, Matplotlib, PyTorch, scikit-learn and SciPy:** checked against their Sphinx `objects.inv` inventories. These are the indexes their documentation sites publish, about 28,000 documented names in all. They're bundled in [`phantom_api/data/inventories`](phantom_api/data/inventories), with versions and URLs in `SOURCES.json`.

**Static analysis with Python's `ast`.** It follows:
- imports and aliases (`import numpy as np`, `from pandas import DataFrame as DF`)
- attribute chains (`np.linalg.norm`, `pd.DataFrame.from_dict`)
- instances, from constructors and from functions with a known return type, so `df = pd.read_csv(...)` makes `df` a DataFrame, and `df.groupby(...).agg(...)` is checked on a `DataFrameGroupBy`
- DataFrame column access (`df["a"]` is a Series, `df[mask]` is a DataFrame)
- `fig, ax = plt.subplots()`
- function parameters and reassignments that shadow a name

Anything it can't type with confidence is left alone. It would rather miss a hallucination than report a false one.

**Suggestions.** Close matches among the real names, plus the place a name actually lives (`np.linalg.mean` → `numpy.mean`).

**Errors and warnings.** Inventories don't record inheritance. A member that isn't documented on a class, but is documented on another class in the same package, is reported as a *warning* ("may be inherited") instead of an error. Known base classes (`torch.nn.Module`, sklearn's `BaseEstimator`, ...) are listed in [`supplements.json`](phantom_api/data/supplements.json), together with real names that the inventories file somewhere else (PyTorch dtypes, `plt.style`, re-exports from `torch.nn.modules`). Each entry has a reason. That file is where false-positive fixes go.

## Results

From [`eval/results.md`](eval/results.md), run by CI on every push:

| Measurement | Result |
|---|---|
| False positives on real code, **held-out set** (242 API references, written after the rules were frozen) | **1 (0.4%)** |
| False positives on real code, dev set (462 references, rules tuned on it) | 0 |
| Curated LLM-style hallucinations caught as errors (53 cases) | **86.8%** (92.5% counting warnings) |
| Fake names injected at real call sites, held-out set (292 mutants) | 100% |

How to read these numbers:
- **The held-out false positive** is `from torch.utils.data import random_split`. PyTorch documents the function only at `torch.utils.data.dataset.random_split`. I left it unfixed so the held-out number stays honest. There's also one false warning (`ConvexHull.volume`).
- **The four missed curated cases** are out of reach by design:
  - keyword arguments of third-party functions (inventories carry no signatures)
  - a `subprocess.run` keyword swallowed by `**kwargs`
  - a method called on a variable of unknown type
- **The injected-fakes test measures reach, not the oracle.** Fakes are checked against the same inventories the tool uses, so this number shows whether the analysis gets to every call site (aliases, instances, chains). It can't show whether the inventories are complete; the false-positive rows measure that.

### CI gate

Every push runs:
- the unit tests and the evaluation on Python 3.10 to 3.13 ([`.github/workflows/ci.yml`](.github/workflows/ci.yml))
- a check that the package installs with no dependencies
- a smoke test of the MCP server

[`eval/run.py`](eval/run.py) exits with an error if any of these crosses the minimum in [`eval/baseline.json`](eval/baseline.json): the held-out false-positive rate, any false positive on the dev set, curated recall or mutant recall. A change that makes the tool noisier or blinder can't be merged.

## Using it

Requirements: Python 3.10 or newer. Nothing else.

```bash
pip install .                         # or run in place: python -m phantom_api
phantom-api script.py                 # a Python file
phantom-api answer.md                 # code blocks of an LLM answer
cat answer.md | phantom-api -         # stdin
phantom-api --json script.py          # machine-readable
phantom-api --libraries               # what's covered
```

Exit code: 0 clean, 1 when there's at least one error, 2 when the input can't be parsed. `--strict` makes warnings fail too.

### As an MCP server (for coding agents)

Register the `phantom-api-mcp` command as a stdio server in any MCP client. A typical client config:

```json
{ "mcpServers": { "phantom-api": { "command": "phantom-api-mcp" } } }
```

| Tool | What it does |
|---|---|
| `check_code` | Checks Python source or a markdown answer and returns findings with suggestions. Meant for an agent to run on its own code before showing or running it. |
| `lookup_api` | Does `pandas.DataFrame.to_markdown` exist? Found, missing (with close matches) or not covered. |

The server speaks MCP's stdio JSON-RPC directly, so it needs no SDK either.

## Benchmark: which models invent APIs?

[`benchmark/`](benchmark) holds 36 coding tasks across the covered libraries. They lean toward less common functionality, where models are more likely to make something up. [`benchmark/run.py`](benchmark/run.py) scores answers from any source and reports, per model:
- the share of answers with a hallucinated API
- hallucinations per 100 API references

Every finding is listed so it can be reviewed by hand. See [`benchmark/README.md`](benchmark/README.md).

### First run: three current models, December 2026

I ran three current LLMs from one provider on all 36 tasks. Their names are hidden (model A, B, C). The answers were generated inside an agentic coding tool rather than through the bare API, and the models were told to answer from memory: no running code, no web search, no documentation. Full results are in [`benchmark/results.md`](benchmark/results.md), and the raw answers are in [`benchmark/answers/`](benchmark/answers).

| Model | Answers | Answers with a hallucinated API | API references checked |
|---|---|---|---|
| A | 36 | 0 | 389 |
| B | 36 | 0 | 332 |
| C | 36 | 0 | 434 |

The tool raised 4 findings across the 108 answers. I checked each one by hand, and all 4 were false positives of the tool, not hallucinations:
- `super().default(o)` inside a `JSONEncoder` subclass. The tool treated `super()` as an ordinary object. **Fixed.**
- `matplotlib.dates.MO`. It's real: `matplotlib.dates` re-exports dateutil's weekday and frequency constants in its `__all__`, but the documentation index doesn't list them. **Fixed** in `supplements.json`, with the source reference.
- `from torch.utils.data import random_split`, in two answers. This is the known held-out false positive. I left it unfixed and marked both cases in [`benchmark/review.json`](benchmark/review.json), so they're excluded from the scores.

What this shows:
- **These models rarely invent APIs on tasks like these.** One answer even guarded a removed pandas method with `hasattr`, using it only on old versions.
- **Zero is a lower bound, not proof.** The tool doesn't check third-party keyword arguments or values it can't type. The run also exposed a reach gap: members reached through a property, such as `df.style.highlight_max`, aren't checked yet.
- **The most useful output of this run was finding the tool's own false positives.** That's what a benchmark on real model output is for.

## Limits

- **Coverage.** Only the standard library and the six bundled libraries are checked. Imports of anything else (`requests`, `transformers`, ...) are ignored, never flagged.
- **Versions.** A name "exists" if it's in the bundled documentation version (NumPy 2.5, pandas 3.1, ...) or in the running Python. Code written for an older pandas that uses `df.append` (removed in 2.0) is flagged too. That's usually what you want from code an LLM just wrote.
- **No types beyond simple tracking.** Values returned by unknown functions, loop variables and most subscripts aren't followed.
- **Third-party keyword arguments.** These aren't checked, because inventories have no signatures.

## Credits

The idea grew out of [API_Lens](https://github.com/MertTomak/API_Lens), a team project that tags API mentions in text with sequence models and checks them against the same kind of inventories. phantom-api works on code instead of prose and needs no model. The bundled inventories come from the libraries' own documentation sites. Each library's documentation is under its own license (BSD-3-Clause for NumPy, SciPy, pandas, scikit-learn and PyTorch; Matplotlib's and Python's PSF-based licenses).

## License

MIT, see [LICENSE](LICENSE).

TDQS

A3.8/5.0

Scored across 2 tools

Disambiguation4/5

Both tools address the same underlying question (does this Python API exist?), but the descriptions draw a clear line: check_code scans a whole snippet/markdown block, while lookup_api resolves a single fully-qualified name. An agent could still occasionally reach for lookup_api when check_code would be better, but the granularity difference is stated explicitly.

Naming Consistency5/5

Both names follow a clean verb_noun snake_case pattern (check_code, lookup_api), with verbs that accurately describe the action. No mixed conventions or vague verbs.

Tool Count4/5

The server has a deliberately narrow purpose (hallucinated-API detection), so two complementary tools—batch and single-name—are defensible rather than redundant. It sits slightly under the typical range, with no tool for repo/directory-level scanning, but nothing feels padded.

Completeness3/5

Coverage is limited to the stdlib plus six scientific/data libraries, leaving common ecosystems (requests, Flask/Django/FastAPI, SQLAlchemy, boto3, pytest) returning 'not covered', which will blunt usefulness on many real codebases. There is also no way to check multiple names in bulk or check a whole project directory, though the graceful 'not covered' response lets agents work around gaps.

Maintenance

ActivityMaintained
ResponsivenessNo recent community issues