Context7 and Claude Code: Wiring the API and Testing It With and Without

17 min readaiclaude-codemcpdevtoolsagents

Next.js now writes a file into my repo that talks to AI agents. It is called AGENTS.md, and its heading says: "This is NOT the Next.js you know."

That line exists because coding agents keep writing code for versions that are gone. The model learned the framework at some point in the past. The framework kept moving. The code it writes still looks right, and sometimes it even compiles.

I wanted to know how much of that Context7 actually fixes, so I skipped the usual MCP install and wired the API in myself. I connected the Context7 API to Claude Code with a 57-line script and a skill. Then I gave clean Claude Code sessions the same real task on this blog, three runs with Context7 and three without. Two of the three runs without it wrote code that passed every check I had and was still a version behind.

This post covers what Context7 is, the MCP vs API choice, whether you need a Context7 API key, the full script and skill, and the test results with numbers. I checked every API detail against the Context7 API guide on November 30, 2026. Context7 ships changes almost every week, so treat the docs as the source of truth if anything here has drifted.

What Is Context7?

Context7 is a documentation service from Upstash that gives coding agents current, version-specific library docs and code examples on demand. It indexes library documentation ahead of time, and when your agent asks a question, it returns only the snippets that answer that question. You can reach it through an MCP server, a CLI called ctx7, a Claude Code plugin, a TypeScript SDK, or a plain REST API.

The Context7 MCP server is how most people meet it. The open-source repo has over 65,000 GitHub stars, and the remote MCP server at https://mcp.context7.com/mcp exposes two tools by default: resolve-library-id and query-docs. Under the hood those two tools call two REST endpoints. That is the part I care about here, because once you know the endpoints, you can call Context7 from a script, a hook, or a CI step.

Why Coding Agents Write Code for Old Versions

A model knows a library as it was when the training data was collected. Libraries do not wait for that.

My test task used the AI SDK. Version 7.0.0 shipped on June 25, 2026, and it renamed several things people write every day. Here are three of them, straight from the AI SDK 7 migration guide:

What you writeAI SDK 6AI SDK 7
Step limitstopWhen: stepCountIs(5)stopWhen: isStepCount(5)
System promptsystem: '...'instructions: '...'
Streaming a chat responseresult.toUIMessageStreamResponse()createUIMessageStreamResponse({ stream: toUIMessageStream({ stream: result.stream }) })

Here is the nasty part. All three old names still work in AI SDK 7. system is marked deprecated in favor of instructions. toUIMessageStreamResponse is marked deprecated and will be removed in the next major release. stepCountIs is kept as a plain alias of isStepCount, with no marker at all. Code written from memory type-checks, runs, and ships a version behind.

That is the real problem Context7 targets: code that passes every check you have and is still out of date. I wrote about how much of an agent's output depends on what lands in its context in my context engineering guide, and library docs are the gap I hit most often.

Context7 MCP vs the Context7 API

There are four ways to get Context7 into Claude Code. They all hit the same index. The difference is who decides when docs get fetched and what you can do with the result.

OptionSetupWho triggers a lookupCallable from a hook or scriptAPI calls per lookup
Claude Code plugin/plugin marketplace add upstash/context7The modelNo1 or 2
MCP serverclaude mcp addThe modelNo1 or 2
ctx7 CLI plus skillnpx ctx7 setup --claudeThe model, through a skillYes2
REST API, your own script57 linesYou decideYes1 or 2

If you want the fastest path, run npx ctx7 setup --claude (it needs Node 22.13 or later). It signs you in, generates an API key, and installs either the Context7 MCP server or a CLI-based skill. It works for Cursor and a few other agents too. The manual route to add Context7 to Claude Code as a remote MCP server is one command:

bash
claude mcp add --scope user --header "Authorization: Bearer YOUR_API_KEY" --transport http context7 https://mcp.context7.com/mcp

I went with the raw API for three reasons. First, I wanted to see exactly what comes back before the model does. Second, an MCP tool needs an MCP client to call it. Claude Code is one, including its mcp_tool hooks, but a git pre-commit script or a plain CI step has none. A script that makes a plain HTTP request runs anywhere. Third, I control the output format, so I can trim search results down to what the model needs to make a choice. If you are new to MCP itself, my Claude Code MCP guide covers the setup side.

Do You Need a Context7 API Key?

No, not to try it. Every valid call I made without a key returned 200. The response headers said context7-quota-tier: anonymous and ratelimit-limit: 200, with a reset at midnight UTC. Context7 does not publish its anonymous rate limits, so treat 200 a day as what I observed, not a promise.

For real use, get a key. The free tier gives you 1,000 API calls a month, plus 20 bonus calls a day once those run out. Pro is $10 per seat for 2,000 calls, then $5 per extra 1,000, according to the Context7 plans page on November 30, 2026. Each library search or docs request counts as one call, so the two-step flow costs two.

You create the key in the Context7 dashboard. It starts with ctx7sk, and it goes in a standard header: Authorization: Bearer ctx7sk-.... Put it in an environment variable called CONTEXT7_API_KEY. Do not put it in CLAUDE.md, a skill file, or anything else that gets committed.

Step 1: Call the Context7 API With curl

Two endpoints do the work. The first finds the library ID:

bash
curl -G "https://context7.com/api/v2/libs/search" \
  --data-urlencode "libraryName=ai sdk" \
  --data-urlencode "query=stream text with tools in a Next.js route"

You get back JSON with one entry per candidate library: an id like /websites/ai-sdk_dev, a title, a trustScore, the last update date, and the indexed versions. The query is not decoration. Context7 uses it to rerank the results, so a real question gets a better match than a bare name.

The second endpoint returns the docs for that ID:

bash
curl -G "https://context7.com/api/v2/context" \
  --data-urlencode "libraryId=/websites/ai-sdk_dev" \
  --data-urlencode "query=streamText with tools in a Next.js route handler, AI SDK 7"

The default response is plain Markdown: a title, the source URL, a short description, and a code block per snippet. It is ready to drop into a context window as is. Add type=json if you want structure. Add version=7.0.185 to pin the version you have installed. If that exact version is not indexed, Context7 serves the closest docs and says so at the top of the response.

There is also a newer one-call endpoint, GET /api/v3/search, that takes only a question and picks up to four libraries itself. It is simpler, but in two samples it returned between 1.2 and 2.6 times more text than a targeted v2/context call for a similar question. For an agent that pays for every token, I prefer the two-step version.

Step 2: A Small Script Claude Code Can Run

Here is the whole script. Save it as .claude/skills/context7-docs/scripts/c7.mjs. It needs Node 18 or later and has no dependencies.

js
#!/usr/bin/env node

const API_BASE = "https://context7.com/api/v2";
const SEARCH_RESULT_LIMIT = 5;
const USAGE = `Usage:
  c7 search <library name> "<what you are trying to do>"
  c7 docs <library id> "<specific question>"`;

const buildHeaders = () => {
  const apiKey = process.env.CONTEXT7_API_KEY;
  return apiKey ? { Authorization: `Bearer ${apiKey}` } : {};
};

const request = async (path, params) => {
  const url = `${API_BASE}${path}?${new URLSearchParams(params)}`;
  const response = await fetch(url, { headers: buildHeaders() });
  if (!response.ok) {
    throw new Error(`Context7 ${response.status} on ${path}: ${await response.text()}`);
  }
  return response;
};

const searchLibraries = async (libraryName, query) => {
  const response = await request("/libs/search", { libraryName, query });
  const { results } = await response.json();
  return results.slice(0, SEARCH_RESULT_LIMIT).map((library) =>
    [
      library.id,
      library.title,
      `trust ${library.trustScore}`,
      `updated ${library.lastUpdateDate?.slice(0, 10)}`,
      `versions ${library.versions?.join(", ") || "latest only"}`,
    ].join(" | "),
  );
};

const fetchDocs = async (libraryId, query) => {
  const response = await request("/context", { libraryId, query, type: "txt" });
  return response.text();
};

const [command, target, query] = process.argv.slice(2);

if (!command || !target || !query) {
  process.stderr.write(`${USAGE}\n`);
  process.exit(1);
}

if (command === "search") {
  const lines = await searchLibraries(target, query);
  process.stdout.write(`${lines.join("\n")}\n`);
} else if (command === "docs") {
  process.stdout.write(await fetchDocs(target, query));
} else {
  process.stderr.write(`${USAGE}\n`);
  process.exit(1);
}

Three things to notice in that code.

First, the API key is optional. Without CONTEXT7_API_KEY the script runs on the anonymous tier, which is enough to try it. With the key, the same script uses your plan.

Second, search output is one line per library, not raw JSON. The model only needs enough to pick the right ID: who publishes it, how fresh it is, and which versions are indexed. Raw JSON would cost several times the tokens for the same decision.

Third, errors are thrown with the status code and the response body. When Context7 says library_not_found or 429, the model sees the real reason and can try a different ID instead of guessing.

Run it once by hand before you give it to the model:

bash
node .claude/skills/context7-docs/scripts/c7.mjs search "ai sdk" "stream text with tools in a Next.js route"

Step 3: Turn It Into a Claude Code Skill

The script does nothing until the model knows when to run it. A skill handles that. Save this as .claude/skills/context7-docs/SKILL.md:

markdown
---
name: context7-docs
description: Fetch current, version-specific documentation for a third-party library or framework from the Context7 API. Use before writing or changing code that calls a library API, especially fast-moving ones (Next.js, AI SDK, React, Zod, Drizzle, Tailwind), and whenever you are not sure an API still exists in the installed version.
---

# Context7 docs lookup

Your training data is older than the libraries in this project. Look up the docs before writing library code.

1. Check the installed version in `package.json` (or the version you are about to install).
2. Find the library ID:

   ```bash
   node .claude/skills/context7-docs/scripts/c7.mjs search "<library name>" "<what you are trying to do>"
   ```

   Pick the official source with the highest trust score whose versions match.
3. Ask one specific question per call, and include the version in it:

   ```bash
   node .claude/skills/context7-docs/scripts/c7.mjs docs "<library id>" "<specific question>"
   ```

4. Write the code from the returned snippets, not from memory. When the docs and your memory disagree, the docs win. When the docs and the installed type definitions disagree, the types in `node_modules` win.

Then add one line to the project's CLAUDE.md:

markdown
Before writing or changing code that uses a third-party library, look up the current docs with the `context7-docs` skill. Do not rely on memory for library APIs.

The skill description makes the lookup discoverable. The CLAUDE.md line makes it the default instead of an option. I covered how Claude Code decides when to load a skill in my guide to writing Claude Code skills, and the description is doing most of the work here.

Step 4 settles conflicts in advance. Docs sometimes lag code, so the installed types get the final word on what compiles. Telling the model which source wins saves it from going back and forth.

The Test: Same Task, With and Without Context7

I wanted a real task on a real codebase, so I used this blog. It runs Next.js 16.4 with React 19.3. The task was a feature I would actually consider building. Here is the prompt, word for word:

text
Add an "Ask this post" feature to this blog.

1. A POST route at app/api/ask/[slug]/route.ts. It receives { messages } from the AI SDK
   useChat hook and streams an answer using the AI SDK (the `ai` package, install the
   latest version) with the model string "anthropic/claude-sonnet-5.5" through the Vercel
   AI Gateway. Give the model one tool, getSection, that takes a heading and returns that
   section of the post's MDX content. Allow up to 4 steps so it can call the tool and then
   answer. Return 404 for an unknown slug.
2. A small client component at components/ask-post.tsx that uses useChat from
   @ai-sdk/react to talk to that route for a given slug, and renders the messages (text
   parts and tool calls) plus an input to send a question. Do not wire it into any page.

Use bun to install packages. Before finishing, make sure `bunx tsc --noEmit` passes.
Keep it minimal.

The setup, so you can judge it:

  • Six fresh copies of the blog at the same commit, one per run, with dependencies installed.
  • Claude Code 2.1.332 in headless mode (claude -p), default model (Claude Opus 5.5), same permissions.
  • My own plugins and hooks off, no MCP servers. Built-in plugins, one synced plugin and my user-level skills still loaded, my global CLAUDE.md loaded in every run, and the built-in claude-api skill fired in five of the six runs, on both sides.
  • Web search allowed on both sides. No run used it.
  • The Context7 calls were anonymous, with no API key.
  • I scored the code. No run called the finished route against a live model.
  • The "with" copies got the skill and the one-line CLAUDE.md from above. The prompt never mentions Context7.
  • Three runs per side. That is a small sample, not a benchmark.

One caveat matters more than the rest. The Context7 copies got a rule telling the model to look up docs. The other copies got no rule at all, not even one pointing at node_modules/ai/docs. So this tests Context7 plus an instruction to use it, against an agent left to its own habits.

I scored each run on four things: does it type-check, does the final code contain any of three AI SDK 6 names (stepCountIs, system, toUIMessageStreamResponse), how much did it cost, and how long did it take.

The Results

All six runs finished the task, and all six passed bunx tsc --noEmit. If type-checking were the bar, the two sides would look identical.

RunContext7Type-checkAI SDK 6 names in final codeCostTimeWhere the API knowledge came from
1NoPass0$1.24100 sDocs shipped in node_modules/ai/docs
2NoPass1 (toUIMessageStreamResponse)$1.43154 sType definitions
3NoPass2 (stepCountIs, toUIMessageStreamResponse)$1.60139 sType definitions
4YesPass0$0.84135 s3 Context7 calls, then installed types
5YesPass0$1.2396 s3 Context7 calls, then installed types
6YesPass0$1.38140 s3 Context7 calls, then installed types

Averages: without Context7, $1.42 per run, 131 seconds, 28 turns, and one AI SDK 6 name per run. With Context7, $1.15 per run, 124 seconds, 27 turns, and none of the three names I searched for.

Two of the three runs without Context7 wrote AI SDK 6 code. Run 2 used the new isStepCount but returned result.toUIMessageStreamResponse(). Run 3 used stepCountIs and toUIMessageStreamResponse(). Both files compile. Nothing I ran flagged either one.

Cost came out lower with Context7 on average, $1.15 against $1.42, but I would not read anything into it. The cheapest run ($0.84) is also the only run where the built-in claude-api skill did not load, and that skill adds roughly 129,000 characters to the context. Across the five runs where it loaded, the averages were $1.31 with Context7 and $1.42 without. The cost figures are Claude Code's own report at API list prices, not a bill.

Each Context7 run made exactly three API calls: one library search and two docs lookups.

What Worked and What Did Not

The logs show where each run looked for the API.

The runs without Context7 noticed the problem on their own. All three said some version of "AI SDK v7 is newer than what I know well" before writing a line. Claude Code knows its knowledge has a date. The question is where it goes to check.

Run 1 probed node_modules/ai/docs in its first inspection command, found the docs that ship with the package, read the chatbot and tool-usage guides, and got everything right. Runs 2 and 3 grepped the type definitions instead. They did check the deprecation notes for system and isStepCount, and used the new names. For toUIMessageStreamResponse they only matched the declaration line, so its @deprecated note never reached them. And stepCountIs has no marker at all: it is exported as a plain alias. The rule I took away from this: a grep of the type definitions tells the model what exists, not what is current, unless it checks every name for a deprecation note.

The Context7 runs went to the docs every time, because the skill told them to, and then checked the result against the installed types, as step 4 says. One query shows the gap. Run 4's docs request named AI SDK 7, then asked about stepCountIs and toUIMessageStreamResponse, the version 6 names from the model's memory. Context7 answered with isStepCount and createUIMessageStreamResponse, and the model used those. Getting the question slightly wrong did not matter, because the answer came from current docs.

Here is what did not go as well. The library search listed the AI SDK's indexed versions as v4, v5, v6, even though the docs it served were already v7. A careful model could have read that as a reason to distrust the results. None did, and the docs were right, but the version label was stale.

I did not test the skill without the CLAUDE.md line, so I cannot tell you how often it fires on its own. Context7's own tips page recommends a rule in CLAUDE.md so you do not have to type "use context7" every time, and at least one third-party guide reports the agent skips the tool without one. Add the rule.

I also did not test the obvious cheap alternative: a one-line rule telling the model to read node_modules/ai/docs. For this package, that might have closed part of the gap. For the many packages that ship no docs, it would not.

To be fair to the runs without Context7: they were not careless. They wrote code that passed every check this repo has, and the old names are easy to miss in review.

Costs, Limits and Security

Every lookup costs API calls. A search plus a docs request is two of your 1,000 free monthly calls. My test feature took three calls per run, so the free tier covers a few hundred tasks like it a month. Check your usage with GET /api/v2/usage, which needs an API key and does not count against the quota.

Docs cost tokens. One docs answer was about 5,000 to 8,000 characters in my runs, roughly 1,500 to 2,000 tokens by my estimate. That is cheap next to reading whole doc files, but it is not free. If it bothers you, run lookups in a subagent so the raw docs never land in your main context.

The right library is not always the first result. For Next.js, search returned both /vercel/next.js and /websites/nextjs, two near-duplicate sources. My skill tells the model to pick by trust score and version and to trust the installed types on conflict. I would not remove that rule.

Docs are untrusted input. This applies to every docs tool, not just this one: anything that pastes third-party text into your agent's context is an injection surface. Context7 had one real case, ContextCrush, reported by Noma Labs and fixed server-side on February 23, 2026, with no exploitation seen. Context7 now screens docs with a classifier before indexing, and teamspace policies can restrict which libraries an agent pulls from. On your side, keep shell permissions tight and secrets out of files the agent can read. My post on security risks in AI-generated code goes deeper on that.

When I Would Skip Context7

When the package ships its own docs and you tell the model to read them. AI SDK 7 puts its full docs, migration guides included, in node_modules/ai/docs. Next.js does the same in node_modules/next/dist/docs. One of my three runs without Context7 found them on its own. The other two did not look.

Most packages do not. I checked the rest of this blog's stack: shiki, satori, zod, next-mdx-remote, and @ai-sdk/react ship no docs folder at all. For those, the model has its memory, the type definitions, and whatever it finds on the web.

When the library is old and stable. If an API has not changed in three years, the model knows it, and a lookup only adds tokens.

When the code is yours. Context7 is built around public libraries and docs sites. Private repos are a Pro feature that I did not try. For internal code, I would start by pointing the agent at your own files or building a small MCP server for your own data.

If you run Claude Code on a codebase with fast-moving dependencies, set this up today. Copy the script, copy the skill, add the line to CLAUDE.md, and rerun a task you already did last week. Then search the diff for old names. If you would rather not maintain a script, npx ctx7 setup --claude gives you the same lookups in a couple of minutes.

Passing the type-check was never the bar. Current code is.

Frequently Asked

Is Context7 free? Yes, with limits. The free plan includes 1,000 API calls a month plus 20 bonus calls a day after that, and it covers the MCP server, the CLI, and the API. Pro costs $10 per seat a month for 2,000 calls per seat.

Can I use Context7 without an API key? Yes. Anonymous requests to the API and the MCP server work, and all of my test runs used them. In my tests the anonymous limit showed as 200 calls, resetting at midnight UTC, but Context7 does not publish it. A free key gives you a documented 1,000 calls a month and is the supported path.

Where do I get a Context7 API key? In the Context7 dashboard under settings. Keys start with ctx7sk and go in an Authorization: Bearer header. npx ctx7 setup can also create one for you during setup.

What are Context7 skills? Skills are Claude Code instruction files that tell the model when and how to look up docs. Context7's repo ships three official ones: context7-mcp, context7-cli, and find-docs. The skill in this post is a different option that calls the REST API directly.

What does the Context7 MCP server do? It gives the model two tools. resolve-library-id turns a name like "next.js" into a Context7 library ID, and query-docs returns the doc snippets that answer a question for that library. They map to the /v2/libs/search and /v2/context endpoints shown above.

How do I add Context7 to Claude Code? The quickest way is npx ctx7 setup --claude. You can also run the claude mcp add command from this post, install the official plugin with /plugin marketplace add upstash/context7, or use the script and skill above.

Context7 MCP or API: which should I use? Use the MCP server or ctx7 setup if you want it working in a couple of minutes. Use the API if you want control over the output, or if you need lookups from a hook or a script, where an MCP tool cannot be called directly.

Is Context7 worth it? For fast-moving libraries, it looks like it. In my small test, none of the three runs with Context7 and the rule used the old AI SDK names, and two of the three runs without it did. That is a lead, not proof, and I tested a script and a skill, not the MCP server. For stable libraries the model already knows, or packages that ship their own docs and a rule to read them, expect a smaller gain.

Does Context7 reduce token usage? My test cannot tell you. The Context7 runs cost less on average, but the cheapest run was also the only one where a large built-in skill did not load, which skews the comparison. Measure it on your own work before you count on it.

What are the best Context7 alternatives? Ref for search across public and private docs (Ref pitches itself on token efficiency), DeepWiki for understanding a whole GitHub repo, GitMCP for a single repo's docs, and vendor docs MCP servers for one product. For packages that ship docs in node_modules, Claude Code can read them with no extra tool at all.

Sources: Context7 API guide, Context7 plans, Context7 Claude Code setup, ContextCrush postmortem, and the AI SDK 7 migration guide shipped in the ai package, checked November 30, 2026.