Skip to content

Context7 Platform -- Up-to-date docs for AI agents

feat(cli): add resolve and query commands for library documentation (#2119)

Fahreddin Özcandf60e3e20e88
diff --git a/.changeset/tall-pandas-hunt.md b/.changeset/tall-pandas-hunt.md
new file mode 100644
index 00000000..2e2de85d
--- /dev/null
+++ b/.changeset/tall-pandas-hunt.md
@@ -0,0 +1,5 @@
+---
+"ctx7": patch
+---
+
+Add `library` and `docs` commands for querying library documentation from the terminal
diff --git a/packages/cli/README.md b/packages/cli/README.md
index 44d94ed6..13952c3c 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -1,6 +1,6 @@
# ctx7
-CLI for the [Context7 Skills Registry](https://context7.com) - install and manage AI coding skills across different AI coding assistants.
+CLI for [Context7](https://context7.com) - query up-to-date library documentation and manage AI coding skills.
Skills are reusable prompt instructions that enhance your AI coding assistant with specialized capabilities like working with specific frameworks, libraries, or coding patterns.
@@ -26,6 +26,18 @@ ctx7 setup --claude
ctx7 setup --opencode
```
+### Library Documentation
+
+```bash
+# Find a library
+ctx7 library react
+ctx7 library nextjs "app router"
+
+# Get documentation
+ctx7 docs /facebook/react "useEffect cleanup"
+ctx7 docs /vercel/next.js "middleware"
+```
+
### Skills
```bash
@@ -44,6 +56,32 @@ ctx7 skills list --claude
## Usage
+### Find a library
+
+Resolve a library name to a Context7 library ID.
+
+```bash
+ctx7 library react
+ctx7 library nextjs "app router setup"
+ctx7 library prisma "database relations"
+
+# Output as JSON
+ctx7 library react --json
+```
+
+### Query documentation
+
+Fetch documentation for a specific library using its Context7 ID.
+
+```bash
+ctx7 docs /facebook/react "useEffect cleanup"
+ctx7 docs /vercel/next.js "middleware authentication"
+ctx7 docs /prisma/prisma "one-to-many relations"
+
+# Output as JSON
+ctx7 docs /facebook/react "hooks" --json
+```
+
### Setup
Configure Context7 MCP and a rule for your AI coding agents. Authenticates via OAuth, generates an API key, and writes the config.
diff --git a/packages/cli/src/commands/docs.ts b/packages/cli/src/commands/docs.ts
new file mode 100644
index 00000000..1547e14f
--- /dev/null
+++ b/packages/cli/src/commands/docs.ts
@@ -0,0 +1,220 @@
+import { Command } from "commander";
+import pc from "picocolors";
+import ora from "ora";
+
+import { resolveLibrary, getLibraryContext } from "../utils/api.js";
+import { log } from "../utils/logger.js";
+import { trackEvent } from "../utils/tracking.js";
+import { loadTokens, isTokenExpired } from "../utils/auth.js";
+import type { LibrarySearchResult, ContextResponse } from "../types.js";
+
+const isTTY = process.stdout.isTTY;
+
+function getAccessToken(): string | undefined {
+ const tokens = loadTokens();
+ if (!tokens || isTokenExpired(tokens)) return undefined;
+ return tokens.access_token;
+}
+
+function formatLibraryResult(lib: LibrarySearchResult, index: number): string {
+ const lines: string[] = [];
+ lines.push(`${pc.dim(`${index + 1}.`)} ${pc.bold(lib.title)} ${pc.cyan(lib.id)}`);
+
+ if (lib.description) {
+ lines.push(` ${pc.dim(lib.description)}`);
+ }
+
+ const meta: string[] = [];
+ if (lib.totalSnippets) {
+ meta.push(`${lib.totalSnippets} snippets`);
+ }
+ if (lib.stars && lib.stars > 0) {
+ meta.push(`${lib.stars.toLocaleString()} stars`);
+ }
+ if (lib.trustScore !== undefined) {
+ meta.push(`trust: ${lib.trustScore}/10`);
+ }
+ if (lib.benchmarkScore !== undefined && lib.benchmarkScore > 0) {
+ meta.push(`benchmark: ${lib.benchmarkScore}`);
+ }
+ if (meta.length > 0) {
+ lines.push(` ${pc.dim(meta.join(" · "))}`);
+ }
+
+ if (lib.versions && lib.versions.length > 0) {
+ lines.push(` ${pc.dim(`versions: ${lib.versions.join(", ")}`)}`);
+ }
+
+ return lines.join("\n");
+}
+
+async function resolveCommand(
+ library: string,
+ query: string | undefined,
+ options: { json?: boolean }
+): Promise<void> {
+ trackEvent("command", { name: "library" });
+
+ const spinner = isTTY ? ora(`Searching for "${library}"...`).start() : null;
+ const accessToken = getAccessToken();
+
+ let data;
+ try {
+ data = await resolveLibrary(library, query, accessToken);
+ } catch (err) {
+ spinner?.fail(`Error: ${err instanceof Error ? err.message : String(err)}`);
+ if (!spinner) log.error(err instanceof Error ? err.message : String(err));
+ process.exitCode = 1;
+ return;
+ }
+
+ if (data.error) {
+ spinner?.fail(data.message || data.error);
+ if (!spinner) log.error(data.message || data.error);
+ process.exitCode = 1;
+ return;
+ }
+
+ if (!data.results || data.results.length === 0) {
+ spinner?.warn(`No libraries found matching "${library}"`);
+ if (!spinner) log.warn(`No libraries found matching "${library}"`);
+ return;
+ }
+
+ const results = data.results;
+
+ spinner?.stop();
+
+ if (options.json) {
+ console.log(JSON.stringify(results, null, 2));
+ return;
+ }
+
+ log.blank();
+ for (let i = 0; i < results.length; i++) {
+ log.plain(formatLibraryResult(results[i], i));
+ log.blank();
+ }
+
+ if (isTTY && results.length > 0) {
+ const best = results[0];
+ log.plain(
+ `${pc.bold("Quick command:")}\n` + ` ${pc.cyan(`ctx7 docs "${best.id}" "<your question>"`)}`
+ );
+ log.blank();
+ }
+}
+
+async function queryCommand(
+ libraryId: string,
+ query: string,
+ options: { json?: boolean }
+): Promise<void> {
+ trackEvent("command", { name: "docs" });
+
+ if (!libraryId.startsWith("/")) {
+ log.error(`Invalid library ID: ${libraryId}`);
+ log.info(`Library IDs start with "/" (e.g., /facebook/react)`);
+ log.info(`Run "ctx7 library <name>" to find the correct ID`);
+ process.exitCode = 1;
+ return;
+ }
+
+ const spinner = isTTY ? ora(`Fetching docs for "${libraryId}"...`).start() : null;
+ const accessToken = getAccessToken();
+ const outputType = options.json ? "json" : "txt";
+
+ let result;
+ try {
+ result = await getLibraryContext(libraryId, query, { type: outputType }, accessToken);
+ } catch (err) {
+ spinner?.fail(`Error: ${err instanceof Error ? err.message : String(err)}`);
+ if (!spinner) log.error(err instanceof Error ? err.message : String(err));
+ process.exitCode = 1;
+ return;
+ }
+
+ if (typeof result === "string") {
+ spinner?.stop();
+ console.log(result);
+ return;
+ }
+
+ const ctx = result as ContextResponse;
+
+ if (ctx.error) {
+ if (ctx.redirectUrl) {
+ spinner?.warn("Library has been redirected");
+ if (!spinner) log.warn("Library has been redirected");
+ log.info(`New ID: ${pc.cyan(ctx.redirectUrl)}`);
+ log.info(`Run: ${pc.cyan(`ctx7 docs "${ctx.redirectUrl}" "${query}"`)}`);
+ process.exitCode = 1;
+ return;
+ }
+
+ spinner?.fail(ctx.message || ctx.error);
+ if (!spinner) log.error(ctx.message || ctx.error);
+ process.exitCode = 1;
+ return;
+ }
+
+ const total = (ctx.codeSnippets?.length || 0) + (ctx.infoSnippets?.length || 0);
+ if (total === 0) {
+ spinner?.warn(`No documentation found for: "${query}"`);
+ if (!spinner) log.warn(`No documentation found for: "${query}"`);
+ return;
+ }
+
+ spinner?.stop();
+
+ if (options.json) {
+ console.log(JSON.stringify(ctx, null, 2));
+ return;
+ }
+
+ log.blank();
+
+ if (ctx.codeSnippets) {
+ for (const snippet of ctx.codeSnippets) {
+ log.plain(pc.bold(snippet.codeTitle));
+ if (snippet.codeDescription) log.dim(snippet.codeDescription);
+ log.blank();
+ for (const code of snippet.codeList) {
+ log.plain("```" + code.language);
+ log.plain(code.code);
+ log.plain("```");
+ log.blank();
+ }
+ }
+ }
+
+ if (ctx.infoSnippets) {
+ for (const snippet of ctx.infoSnippets) {
+ if (snippet.breadcrumb) log.plain(pc.bold(snippet.breadcrumb));
+ log.plain(snippet.content);
+ log.blank();
+ }
+ }
+}
+
+export function registerDocsCommands(program: Command): void {
+ program
+ .command("library")
+ .argument("<name>", "Library name to search for")
+ .argument("[query]", "Question or task for relevance ranking")
+ .option("--json", "Output as JSON")
+ .description("Resolve a library name to a Context7 library ID")
+ .action(async (name: string, query: string | undefined, options: { json?: boolean }) => {
+ await resolveCommand(name, query, options);
+ });
+
+ program
+ .command("docs")
+ .argument("<libraryId>", "Context7 library ID (e.g., /facebook/react)")
+ .argument("<query>", "Question or task to get docs for")
+ .option("--json", "Output as JSON")
+ .description("Query documentation for a library")
+ .action(async (libraryId: string, query: string, options: { json?: boolean }) => {
+ await queryCommand(libraryId, query, options);
+ });
+}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 44442bcb..905999a3 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -4,6 +4,7 @@ import figlet from "figlet";
import { registerSkillCommands, registerSkillAliases } from "./commands/skill.js";
import { registerAuthCommands, setAuthBaseUrl } from "./commands/auth.js";
import { registerSetupCommand } from "./commands/setup.js";
+import { registerDocsCommands } from "./commands/docs.js";
import { setBaseUrl } from "./utils/api.js";
import { VERSION } from "./constants.js";
@@ -46,6 +47,10 @@ Examples:
${brand.primary("npx ctx7 skills list --claude")}
${brand.primary("npx ctx7 skills remove pdf")}
+ ${brand.dim("# Query library documentation")}
+ ${brand.primary('npx ctx7 library react "how to use hooks"')}
+ ${brand.primary('npx ctx7 docs /facebook/react "useEffect examples"')}
+
Visit ${brand.primary("https://context7.com")} to browse skills
`
);
@@ -54,6 +59,7 @@ registerSkillCommands(program);
registerSkillAliases(program);
registerAuthCommands(program);
registerSetupCommand(program);
+registerDocsCommands(program);
program.action(() => {
console.log("");
diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.ts
index c0785118..90735772 100644
--- a/packages/cli/src/types.ts
+++ b/packages/cli/src/types.ts
@@ -215,3 +215,39 @@ export interface SkillQuotaResponse {
message?: string;
error?: string;
}
+
+export interface LibraryResolveResponse {
+ results: LibrarySearchResult[];
+ error?: string;
+ message?: string;
+}
+
+export interface CodeExample {
+ language: string;
+ code: string;
+}
+
+export interface CodeSnippet {
+ codeTitle: string;
+ codeDescription: string;
+ codeLanguage: string;
+ codeTokens: number;
+ codeId: string;
+ pageTitle: string;
+ codeList: CodeExample[];
+}
+
+export interface InfoSnippet {
+ pageId?: string;
+ breadcrumb?: string;
+ content: string;
+ contentTokens: number;
+}
+
+export interface ContextResponse {
+ codeSnippets: CodeSnippet[];
+ infoSnippets: InfoSnippet[];
+ error?: string;
+ message?: string;
+ redirectUrl?: string;
+}
diff --git a/packages/cli/src/utils/api.ts b/packages/cli/src/utils/api.ts
index 09e0d5ce..acebe31c 100644
--- a/packages/cli/src/utils/api.ts
+++ b/packages/cli/src/utils/api.ts
@@ -9,6 +9,8 @@ import type {
StructuredGenerateInput,
GenerateStreamEvent,
SkillQuotaResponse,
+ LibraryResolveResponse,
+ ContextResponse,
} from "../types.js";
import { downloadSkillFromGitHub } from "./github.js";
@@ -249,3 +251,93 @@ async function handleGenerateResponse(
return { content, libraryName: finalLibraryName, error };
}
+
+function getAuthHeaders(accessToken?: string): Record<string, string> {
+ const headers: Record<string, string> = {};
+ const apiKey = process.env.CONTEXT7_API_KEY;
+ if (apiKey) {
+ headers["Authorization"] = `Bearer ${apiKey}`;
+ } else if (accessToken) {
+ headers["Authorization"] = `Bearer ${accessToken}`;
+ }
+ return headers;
+}
+
+export async function resolveLibrary(
+ libraryName: string,
+ query?: string,
+ accessToken?: string
+): Promise<LibraryResolveResponse> {
+ const params = new URLSearchParams({ libraryName });
+ if (query) {
+ params.set("query", query);
+ }
+
+ const response = await fetch(`${baseUrl}/api/v2/libs/search?${params}`, {
+ headers: getAuthHeaders(accessToken),
+ });
+
+ if (!response.ok) {
+ const errorData = (await response.json().catch(() => ({}))) as {
+ error?: string;
+ message?: string;
+ };
+ return {
+ results: [],
+ error: errorData.error || `HTTP error ${response.status}`,
+ message: errorData.message,
+ };
+ }
+
+ return (await response.json()) as LibraryResolveResponse;
+}
+
+export interface GetContextOptions {
+ type?: "json" | "txt";
+}
+
+export async function getLibraryContext(
+ libraryId: string,
+ query: string,
+ options?: GetContextOptions,
+ accessToken?: string
+): Promise<ContextResponse | string> {
+ const params = new URLSearchParams({ libraryId, query });
+ if (options?.type) {
+ params.set("type", options.type);
+ }
+ const response = await fetch(`${baseUrl}/api/v2/context?${params}`, {
+ headers: getAuthHeaders(accessToken),
+ });
+
+ if (!response.ok) {
+ const errorData = (await response.json().catch(() => ({}))) as {
+ error?: string;
+ message?: string;
+ redirectUrl?: string;
+ };
+
+ if (response.status === 301 && errorData.redirectUrl) {
+ return {
+ codeSnippets: [],
+ infoSnippets: [],
+ error: errorData.error || "library_redirected",
+ message: errorData.message,
+ redirectUrl: errorData.redirectUrl,
+ };
+ }
+
+ return {
+ codeSnippets: [],
+ infoSnippets: [],
+ error: errorData.error || `HTTP error ${response.status}`,
+ message: errorData.message,
+ };
+ }
+
+ if (options?.type === "txt") {
+ return await response.text();
+ }
+
+ return (await response.json()) as ContextResponse;
+}