How to Stop AI Agents Hallucinating Code in 2026
A. Frans
Published July 30, 2026
Table of Contents
- 01Why "be accurate" doesn't work
- 02The tools, and what each one grounds
- 03Ground against current docs: Context7
- 04Ground against real source: GitMCP
- 05Ground against your own documents: NotebookLM MCP
- 06Ground against the live web
- 07Catch it after the fact: Superpowers
- 08The habits that matter more than the tools
- 09Where I'd start
- 10FAQ
The most expensive bug an AI agent produces is a method that doesn't exist, called with confidence, wrapped in a try/catch, with a comment explaining what it does.
Syntax errors fail loudly. A hallucinated API call looks like working code until it hits an edge path in production. And the reason it happens is boring: the model is predicting what a plausible API looks like, because it doesn't have the real one in front of it.
Everything below is about fixing that: putting the real documentation, the real source, and the real current behavior into the model's context so it doesn't have to guess. Grounding, not prompting.
Why "be accurate" doesn't work
You can tell a model not to invent APIs. It'll agree, and then invent one anyway, because it isn't lying. It's completing a pattern. When a library's real method is client.messages.create() and every similar library uses client.chat.completions(), the model has no way to know which is true unless something tells it.
Prompt instructions can reduce confident phrasing. They can't add information the model doesn't have. That's a retrieval problem, and it needs a retrieval fix.
Three things reliably trigger it:
Libraries that changed after the training cutoff. The model knows v2's API. You're on v4.
Your own internal code. No model has seen your private repo. It will confidently guess your service layer's method names based on convention.
Anything niche. Small libraries, regional APIs, in-house frameworks. Thin training coverage means high-confidence guessing.
The tools, and what each one grounds
| Tool | Grounds against | Stars | License | Last push |
|---|---|---|---|---|
| Context7 | Current library docs | 60.0K | MIT | 2026-07-29 |
| GitMCP | Any GitHub repo's real source | 8.3K | Apache-2.0 | 2026-05-08 |
| NotebookLM MCP | Your own document corpus | 3.1K | MIT | 2026-05-01 |
| Deep Research | Multi-source synthesis w/ citations | 964 | none declared | 2026-04-11 |
| Google AI Mode | Live web search with citations | 271 | none declared | 2026-01-08 |
| Superpowers | Evidence-driven debugging | 263K | MIT | 2026-07-28 |
Ground against current docs: Context7
Context7 serves up-to-date library documentation into the model's context on request. It's the single highest-value install here, because "the library changed" is the most common cause of the failure.
claude mcp add context7 -- npx -y upstash/context7
60K stars, MIT, pushed the day before this was written. We have a fuller walkthrough in the Context7 install guide.
What it won't fix: your private code, and anything not covered in its indexed documentation set. It's a docs layer, so it's only as good as the docs.
Ground against real source: GitMCP
GitMCP takes a different route. It turns any GitHub repository into a documentation endpoint the model can query. Its own README says the goal is eliminating code hallucinations, and the design follows: instead of recalling what a library's API probably looks like, the model reads the repo.
It's a remote server, so there's nothing to install. You point at a URL:
- One repo:
https://gitmcp.io/{owner}/{repo} - GitHub Pages site:
https://{owner}.gitmcp.io/{repo} - Any repo, chosen per request:
https://gitmcp.io/docs
In Claude Code, register it as a remote MCP server:
claude mcp add --transport http gitmcp https://gitmcp.io/upstash/context7
Apache-2.0, 8.3K stars. Last push was 2026-05-08, about three months quiet at the time of writing. Not abandoned, but worth knowing.
The scoping advice in their README is good and most people ignore it: pin the specific repo rather than using the generic /docs endpoint. Pinning means the model can't wander into an unintended repository, and it removes a per-request guess about which project you meant.
The obvious limit: public GitHub only. Your private monorepo isn't reachable this way.
Ground against your own documents: NotebookLM MCP
For internal specs, architecture decision records, and API contracts that live in your own docs rather than a public repo, NotebookLM MCP routes the model's questions through NotebookLM and returns citation-backed answers from your own knowledge base.
The install command in most directory listings is wrong. The one from the project's README:
claude mcp add notebooklm -- npx notebooklm-mcp@latest
MIT, 3.1K stars, last push 2026-05-01. One setup detail that catches people: the first-run setup_auth opens a visible browser window for the Google login, so on a headless server you need to run it once under xvfb-run. After that the persistent Chrome profile lets subsequent runs go fully headless.
The tradeoff is a dependency on a Google product and a login session that can expire. When it does, this fails at exactly the moment you'd forgotten it was load-bearing.
Ground against the live web
Two options, both with caveats I'd want to know before installing.
Google AI Mode skill gives Claude Code free Google AI Mode search with citations, using a persistent browser profile. Useful for "what's the current recommended approach for X."
Two flags. The repo declares no license; GitHub's API reports none, which legally means all rights reserved, not open source. And the last push was 2026-01-08, roughly seven months before this article. For a skill that drives a browser against a Google product that changes its UI regularly, seven months is long enough that I'd test it before relying on it. The README says to clone it into ~/.claude/skills rather than using a claude skill add one-liner.
Deep Research runs an eight-phase pipeline that synthesizes multiple sources, cross-references findings, and produces reports with citations. 964 stars, last push 2026-04-11, no declared license. Note that it depends on a separate search-cli binary (brew tap 199-biotechnologies/tap && brew install search-cli) plus API keys, so it isn't a one-command install. We reviewed it separately in is the Deep Research skill worth installing.
A note on install commands generally: several of these are listed incorrectly across skill directories, including ours in places. The command in a repo's own README is the source of truth. We wrote up how to verify a skill's install command for exactly this reason, and I'd read it before pasting anything from a listing page, this one included.
Catch it after the fact: Superpowers
Grounding reduces hallucination. It doesn't eliminate it, and the second line of defense is a debugging process that doesn't let a wrong assumption survive.
Superpowers bundles a systematic-debugging skill: form a hypothesis, gather evidence, isolate variables, verify the fix. That sounds like process overhead until you watch an agent try six random fixes in a row, each one built on the same wrong assumption about what a function returns.
Install is through the plugin marketplace, not claude skill add:
/plugin install superpowers@claude-plugins-official
263K stars, MIT, actively maintained. The debugging skill is one of many in the bundle.
The habits that matter more than the tools
Make the model run the code. A hallucinated method dies the first time it executes. The fastest anti-hallucination measure is a test the agent runs itself, before it tells you it's done.
Ask for the source, not the answer. "Show me the actual signature from the installed package" beats "what are the parameters." One reads a file; the other recalls a pattern.
Distrust confidence on obscure things. The model sounds equally certain about React.useState and about a method in a library with 200 downloads a week. Its tone carries no information about its accuracy.
Pin your versions. If the model knows you're on [email protected] rather than "Stripe," it has a far better shot. Put the versions in your project instructions.
Check the imports first. Hallucinated code usually imports something that doesn't exist. Scanning the import block takes five seconds and catches a large share of it.
For the broader tooling picture, see our full list for developers.
Where I'd start
One install: Context7. Stale-library APIs cause most of the hallucinations most people hit.
Two: add GitMCP, pinned to the specific repositories you work against.
Working on internal systems: NotebookLM MCP is the only thing here that grounds against documents the public internet has never seen.
Skip the web-search skills unless you specifically need live results. Both have license and maintenance questions that make them a poor default.
And install the debugging discipline regardless. Grounding lowers the hallucination rate; it doesn't get it to zero, and the difference between an annoying bug and a production incident is usually whether something caught it in between.
FAQ
Does a bigger context window fix hallucinations? No. A bigger window means you can fit more grounding material. It doesn't put the material there. An empty 1M-token window hallucinates exactly as much as an empty 200K one.
Do these work with agents other than Claude Code? The MCP servers (Context7, GitMCP, NotebookLM MCP) work with any MCP-compatible client, including Cursor and Codex. The skills and plugins are Claude Code specific.
Will grounding slow my agent down? Yes, slightly. A docs lookup is a round trip. It's still faster than three failed attempts at an invented API, which is the thing it replaces.
Why do agents hallucinate my internal code so confidently? Because convention is a strong prior. If your service layer looks like a thousand others in the training data, the model will predict the conventional method name and be right often enough to keep doing it. Grounding against your actual repo is the fix.
Can I just tell it to say "I don't know"? It helps at the margin and it's worth putting in your instructions. But the model often doesn't know that it doesn't know: a confabulated API feels, internally, like a recalled one. Retrieval beats instruction here.
Share this article
⚙Related Tools
📄Related Articles
Get More AI Tool Guides
New comparisons and guides every week. Join thousands of professionals staying ahead of the AI curve.