Context7 Platform -- Up-to-date docs for AI agents
feat(cli): add CLI + Skills mode to ctx7 setup (#2187)
Fahreddin Özcand418405f851f
diff --git a/.changeset/setup-cli-mode.md b/.changeset/setup-cli-mode.mdnew file mode 100644index 00000000..345e4281--- /dev/null+++ b/.changeset/setup-cli-mode.md@@ -0,0 +1,5 @@+---+"ctx7": patch+---++Add CLI mode to ctx7 setup for installing the docs skill without MCP configurationdiff --git a/docs/clients/cli.mdx b/docs/clients/cli.mdxindex d2da9182..14a7835a 100644--- a/docs/clients/cli.mdx+++ b/docs/clients/cli.mdx@@ -103,19 +103,32 @@ ctx7 docs /vercel/next.js "How to add middleware for route protection" | grep -A## Setup-Configure Context7 MCP for your AI coding agent. Writes the MCP server config, a Context7 rule file, and a `documentation-lookup` skill.+Configure Context7 for your AI coding agent. On first run, prompts you to choose between two modes:++- **MCP server** — registers the Context7 MCP server in your agent's config so it can call `resolve-library-id` and `get-library-docs` tools natively+- **CLI + Skills** — installs a `docs` skill that guides your agent to fetch up-to-date library docs using `ctx7` CLI commands (no MCP required)### ctx7 setup```bash-# Interactive — prompts for agent selection+# Interactive — prompts for mode, then agent/install targetctx7 setup-# Target a specific agent+# Skip the mode prompt+ctx7 setup --mcp # MCP server mode+ctx7 setup --cli # CLI + Skills mode++# Target a specific agent (MCP mode)ctx7 setup --claudectx7 setup --cursorctx7 setup --opencode+# Target a specific install location (CLI + Skills mode)+ctx7 setup --cli --claude # Claude Code (~/.claude/skills)+ctx7 setup --cli --cursor # Cursor (~/.cursor/skills)+ctx7 setup --cli --universal # Universal (~/.config/agents/skills)+ctx7 setup --cli --antigravity # Antigravity (~/.config/agent/skills)+# Configure for current project only (default is global)ctx7 setup --project@@ -126,16 +139,16 @@ ctx7 setup --yes**Authentication options:**```bash-# Use an existing API key+# Use an existing API key (works for both MCP and CLI + Skills mode)ctx7 setup --api-key YOUR_API_KEY-# Use OAuth endpoint (IDE handles the auth flow)+# Use OAuth endpoint — MCP mode only (IDE handles the auth flow)ctx7 setup --oauth```-Without `--api-key` or `--oauth`, setup opens a browser for OAuth login and generates a new API key automatically.+Without `--api-key` or `--oauth`, setup opens a browser for OAuth login. MCP mode additionally generates a new API key after login. `--oauth` is MCP-only — use it when an IDE handles the auth flow on your behalf.-**What gets written:**+**What gets written — MCP mode:**| File | Purpose ||------|---------|@@ -143,6 +156,12 @@ Without `--api-key` or `--oauth`, setup opens a browser for OAuth login and gene| Agent rules directory | Rule file — instructs the agent to use Context7 for library docs || Agent skills directory | `documentation-lookup` skill |+**What gets written — CLI + Skills mode:**++| File | Purpose |+|------|---------|+| Agent skills directory | `docs` skill — guides the agent to use `ctx7 library` and `ctx7 docs` commands |+---## Authentication@@ -180,7 +199,7 @@ export CONTEXT7_API_KEY=your_key| `ctx7 library` / `ctx7 docs` | No — login gives higher rate limits || `ctx7 skills install / search / suggest / list / remove` | No || `ctx7 skills generate` | Yes |-| `ctx7 setup` | Yes — unless `--api-key` or `--oauth` is passed |+| `ctx7 setup` | Yes — unless `--api-key` is passed (`--oauth` also skips login for MCP mode) |---diff --git a/packages/cli/src/commands/docs.ts b/packages/cli/src/commands/docs.tsindex 3427b85c..abe070c6 100644--- a/packages/cli/src/commands/docs.ts+++ b/packages/cli/src/commands/docs.ts@@ -120,9 +120,9 @@ async function queryCommand(): 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)`);+ if (!libraryId.startsWith("/") || !/^\/[^/]+\/[^/]/.test(libraryId)) {+ log.error(`Invalid library ID: "${libraryId}"`);+ log.info(`Expected format: /owner/repo or /owner/repo/version (e.g., /facebook/react)`);log.info(`Run "ctx7 library <name>" to find the correct ID`);process.exitCode = 1;return;diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.tsindex d3ea0ea2..a270e7e6 100644--- a/packages/cli/src/commands/setup.ts+++ b/packages/cli/src/commands/setup.ts@@ -1,6 +1,7 @@import { Command } from "commander";import pc from "picocolors";import ora from "ora";+import { select } from "@inquirer/prompts";import { mkdir, writeFile } from "fs/promises";import { dirname, join } from "path";import { randomBytes } from "crypto";@@ -8,9 +9,11 @@ import { randomBytes } from "crypto";import { log } from "../utils/logger.js";import { checkboxWithHover } from "../utils/prompts.js";import { trackEvent } from "../utils/tracking.js";-import { getBaseUrl } from "../utils/api.js";+import { getBaseUrl, downloadSkill } from "../utils/api.js";+import { installSkillFiles } from "../utils/installer.js";+import { promptForInstallTargets, getTargetDirs } from "../utils/ide.js";import { performLogin } from "./auth.js";-import { loadTokens, isTokenExpired } from "../utils/auth.js";+import { loadTokens, isTokenExpired, saveTokens } from "../utils/auth.js";import {type SetupAgent,type AuthOptions,@@ -29,15 +32,20 @@ import {} from "../setup/mcp-writer.js";type Scope = "global" | "project";+type SetupMode = "mcp" | "cli";interface SetupOptions {claude?: boolean;cursor?: boolean;+ universal?: boolean;+ antigravity?: boolean;opencode?: boolean;project?: boolean;yes?: boolean;apiKey?: string;oauth?: boolean;+ cli?: boolean;+ mcp?: boolean;}const CHECKBOX_THEME = {@@ -58,10 +66,14 @@ function getSelectedAgents(options: SetupOptions): SetupAgent[] {export function registerSetupCommand(program: Command): void {program.command("setup")- .description("Set up Context7 MCP and rule for your AI coding agent")+ .description("Set up Context7 for your AI coding agent").option("--claude", "Set up for Claude Code").option("--cursor", "Set up for Cursor")+ .option("--universal", "Set up for Universal (.agents/skills)")+ .option("--antigravity", "Set up for Antigravity (.agent/skills)").option("--opencode", "Set up for OpenCode")+ .option("--mcp", "Set up MCP server mode")+ .option("--cli", "Set up CLI + Skills mode (no MCP server)").option("-p, --project", "Configure for current project instead of globally").option("-y, --yes", "Skip confirmation prompts").option("--api-key <key>", "Use API key authentication")@@ -118,6 +130,49 @@ async function resolveAuth(options: SetupOptions): Promise<AuthOptions | null> {return { mode: "api-key", apiKey };}+async function resolveMode(options: SetupOptions): Promise<SetupMode> {+ if (options.cli) return "cli";+ if (options.mcp || options.yes || options.oauth || options.apiKey) return "mcp";++ return select<SetupMode>({+ message: "How should your agent access Context7?",+ choices: [+ {+ name: `MCP server\n ${pc.dim("Agent calls Context7 tools via MCP protocol to retrieve up-to-date library docs")}`,+ value: "mcp" as SetupMode,+ },+ {+ name: `CLI + Skills\n ${pc.dim("Installs a docs skill that guides your agent to fetch up-to-date library docs using ")}${pc.dim(pc.bold("ctx7"))}${pc.dim(" CLI commands")}`,+ value: "cli" as SetupMode,+ },+ ],+ theme: {+ style: {+ highlight: (text: string) => pc.green(text),+ answer: (text: string) => pc.green(text.split("\n")[0].trim()),+ },+ },+ });+}++async function resolveCliAuth(apiKey?: string): Promise<void> {+ if (apiKey) {+ saveTokens({ access_token: apiKey, token_type: "bearer" });+ log.blank();+ log.plain(`${pc.green("✔")} Authenticated`);+ return;+ }++ const existingTokens = loadTokens();+ if (existingTokens && !isTokenExpired(existingTokens)) {+ log.blank();+ log.plain(`${pc.green("✔")} Authenticated`);+ return;+ }++ await performLogin();+}+async function isAlreadyConfigured(agentName: SetupAgent, scope: Scope): Promise<boolean> {const agent = getAgent(agentName);const mcpPath =@@ -131,10 +186,10 @@ async function isAlreadyConfigured(agentName: SetupAgent, scope: Scope): Promise}}-async function promptAgents(scope: Scope): Promise<SetupAgent[] | null> {+async function promptAgents(scope: Scope, mode: SetupMode): Promise<SetupAgent[] | null> {const choices = await Promise.all(ALL_AGENT_NAMES.map(async (name) => {- const configured = await isAlreadyConfigured(name, scope);+ const configured = mode === "mcp" ? await isAlreadyConfigured(name, scope) : false;return {name: SETUP_AGENT_NAMES[name],value: name,@@ -148,10 +203,13 @@ async function promptAgents(scope: Scope): Promise<SetupAgent[] | null> {return null;}+ const message =+ mode === "cli" ? "Install docs skill for which agents?" : "Which agents do you want to set up?";+try {return await checkboxWithHover({- message: "Which agents do you want to set up?",+ message,choices,loop: false,theme: CHECKBOX_THEME,@@ -163,7 +221,11 @@ async function promptAgents(scope: Scope): Promise<SetupAgent[] | null> {}}-async function resolveAgents(options: SetupOptions, scope: Scope): Promise<SetupAgent[]> {+async function resolveAgents(+ options: SetupOptions,+ scope: Scope,+ mode: SetupMode = "mcp"+): Promise<SetupAgent[]> {const explicit = getSelectedAgents(options);if (explicit.length > 0) return explicit;@@ -172,7 +234,7 @@ async function resolveAgents(options: SetupOptions, scope: Scope): Promise<Setupif (detected.length > 0 && options.yes) return detected;log.blank();- const selected = await promptAgents(scope);+ const selected = await promptAgents(scope, mode);if (!selected) {log.warn("Setup cancelled");return [];@@ -265,13 +327,7 @@ async function setupAgent(};}-async function setupCommand(options: SetupOptions): Promise<void> {- trackEvent("command", { name: "setup" });-- const scope: Scope = options.project ? "project" : "global";- const agents = await resolveAgents(options, scope);- if (agents.length === 0) return;-+async function setupMcp(agents: SetupAgent[], options: SetupOptions, scope: Scope): Promise<void> {const auth = await resolveAuth(options);if (!auth) {log.warn("Setup cancelled");@@ -306,3 +362,69 @@ async function setupCommand(options: SetupOptions): Promise<void> {trackEvent("setup", { agents, scope, authMode: auth.mode });}++async function setupCli(options: SetupOptions): Promise<void> {+ await resolveCliAuth(options.apiKey);++ const targets = await promptForInstallTargets({ ...options, global: !options.project }, false);+ if (!targets) {+ log.warn("Setup cancelled");+ return;+ }++ log.blank();+ const spinner = ora("Downloading docs skill...").start();++ const downloadData = await downloadSkill("/upstash/context7", "docs");+ if (downloadData.error || downloadData.files.length === 0) {+ spinner.fail(`Failed to download docs skill: ${downloadData.error || "no files"}`);+ return;+ }++ spinner.succeed("Downloaded docs skill");++ const targetDirs = getTargetDirs(targets);+ const installSpinner = ora("Installing docs skill...").start();++ for (const dir of targetDirs) {+ installSpinner.text = `Installing to ${dir}...`;+ await installSkillFiles("docs", downloadData.files, dir);+ }++ installSpinner.stop();+ log.blank();+ log.plain(`${pc.green("✔")} Context7 CLI setup complete`);++ log.blank();+ for (const dir of targetDirs) {+ log.itemAdd(+ `docs ${pc.dim("Guides your agent to fetch up-to-date library docs on demand using ctx7 CLI commands")}`+ );+ log.plain(` ${pc.dim(dir)}`);+ }+ log.blank();+ log.plain(` ${pc.bold("Next steps")}`);+ log.plain(` Ask your agent: ${pc.cyan(`"Use ctx7 CLI to look up React hooks"`)}`);+ log.blank();++ trackEvent("setup", { mode: "cli" });+}++async function setupCommand(options: SetupOptions): Promise<void> {+ trackEvent("command", { name: "setup" });++ try {+ const mode = await resolveMode(options);+ if (mode === "mcp") {+ const scope: Scope = options.project ? "project" : "global";+ const agents = await resolveAgents(options, scope, mode);+ if (agents.length === 0) return;+ await setupMcp(agents, options, scope);+ } else {+ await setupCli(options);+ }+ } catch (err) {+ if (err instanceof Error && err.name === "ExitPromptError") process.exit(0);+ throw err;+ }+}diff --git a/packages/cli/src/types.ts b/packages/cli/src/types.tsindex 143339e5..52e3ef12 100644--- a/packages/cli/src/types.ts+++ b/packages/cli/src/types.ts@@ -139,7 +139,7 @@ export interface ScopeOptions {global?: boolean;}-export type AddOptions = IDEOptions & ScopeOptions & { all?: boolean };+export type AddOptions = IDEOptions & ScopeOptions & { all?: boolean; yes?: boolean };export type SuggestOptions = IDEOptions & ScopeOptions;export type ListOptions = IDEOptions & ScopeOptions;export type RemoveOptions = IDEOptions & ScopeOptions;diff --git a/packages/cli/src/utils/api.ts b/packages/cli/src/utils/api.tsindex 44eb3047..0221cf7e 100644--- a/packages/cli/src/utils/api.ts+++ b/packages/cli/src/utils/api.ts@@ -12,6 +12,7 @@ import type {ContextResponse,} from "../types.js";import { downloadSkillFromGitHub } from "./github.js";+import { VERSION } from "../constants.js";let baseUrl = "https://context7.com";@@ -252,7 +253,12 @@ async function handleGenerateResponse(}function getAuthHeaders(accessToken?: string): Record<string, string> {- const headers: Record<string, string> = {};+ const headers: Record<string, string> = {+ "X-Context7-Source": "cli",+ "X-Context7-Client-IDE": "ctx7-cli",+ "X-Context7-Client-Version": VERSION,+ "X-Context7-Transport": "cli",+ };const apiKey = process.env.CONTEXT7_API_KEY;if (apiKey) {headers["Authorization"] = `Bearer ${apiKey}`;diff --git a/packages/cli/src/utils/ide.ts b/packages/cli/src/utils/ide.tsindex 83a28d5c..674b078a 100644--- a/packages/cli/src/utils/ide.ts+++ b/packages/cli/src/utils/ide.ts@@ -63,7 +63,10 @@ export function getUniversalDir(scope: Scope): string {return join(process.cwd(), UNIVERSAL_SKILLS_PATH);}-export async function promptForInstallTargets(options: AddOptions): Promise<InstallTargets | null> {+export async function promptForInstallTargets(+ options: AddOptions,+ forceUniversal = true+): Promise<InstallTargets | null> {if (hasExplicitIdeOption(options)) {const ides = getSelectedIdes(options);const scope: Scope = options.global ? "global" : "project";@@ -104,13 +107,17 @@ export async function promptForInstallTargets(options: AddOptions): Promise<Instlog.blank();let confirmed: boolean;- try {- confirmed = await confirm({- message: `Install to detected location(s)?\n${pc.dim(pathLines.join("\n"))}`,- default: true,- });- } catch {- return null;+ if (options.yes) {+ confirmed = true;+ } else {+ try {+ confirmed = await confirm({+ message: `Install to detected location(s)?\n${pc.dim(pathLines.join("\n"))}`,+ default: true,+ });+ } catch {+ return null;+ }}if (!confirmed) {@@ -124,10 +131,15 @@ export async function promptForInstallTargets(options: AddOptions): Promise<Inst// Nothing detected — show checkbox to pickconst universalLabel = `Universal \u2014 ${UNIVERSAL_AGENTS_LABEL} ${pc.dim(`(${universalPath})`)}`;const choices: { name: string; value: IDE; checked: boolean }[] = [+ {+ name: `${IDE_NAMES["claude"]} ${pc.dim(`(${pathMap["claude"]})`)}`,+ value: "claude" as IDE,+ checked: false,+ },{ name: universalLabel, value: "universal", checked: false },];- for (const ide of VENDOR_SPECIFIC_AGENTS) {+ for (const ide of VENDOR_SPECIFIC_AGENTS.filter((ide) => ide !== "claude")) {choices.push({name: `${IDE_NAMES[ide]} ${pc.dim(`(${pathMap[ide]})`)}`,value: ide,@@ -148,7 +160,7 @@ export async function promptForInstallTargets(options: AddOptions): Promise<Inststyle: {highlight: (text: string) => pc.green(text),message: (text: string, status: string) => {- if (status === "done") return pc.dim(text.split("\n")[0]);+ if (status === "done") return text.split("\n")[0];return pc.bold(text);},},@@ -160,8 +172,9 @@ export async function promptForInstallTargets(options: AddOptions): Promise<Instreturn null;}- // Universal is always included- const ides: IDE[] = ["universal", ...selectedIdes.filter((ide) => ide !== "universal")];+ const ides: IDE[] = forceUniversal+ ? ["universal", ...selectedIdes.filter((ide) => ide !== "universal")]+ : selectedIdes;return { ides, scopes: [scope] };}@@ -179,9 +192,12 @@ export async function promptForSingleTarget(log.blank();const universalLabel = `Universal ${pc.dim(`(${UNIVERSAL_SKILLS_PATH})`)}`;- const choices: { name: string; value: IDE }[] = [{ name: universalLabel, value: "universal" }];+ const choices: { name: string; value: IDE }[] = [+ { name: `${IDE_NAMES["claude"]} ${pc.dim(`(${IDE_PATHS["claude"]})`)}`, value: "claude" },+ { name: universalLabel, value: "universal" },+ ];- for (const ide of VENDOR_SPECIFIC_AGENTS) {+ for (const ide of VENDOR_SPECIFIC_AGENTS.filter((ide) => ide !== "claude")) {choices.push({name: `${IDE_NAMES[ide]} ${pc.dim(`(${IDE_PATHS[ide]})`)}`,value: ide,diff --git a/packages/cli/src/utils/prompts.ts b/packages/cli/src/utils/prompts.tsindex a2f20736..80b8395f 100644--- a/packages/cli/src/utils/prompts.ts+++ b/packages/cli/src/utils/prompts.ts@@ -64,6 +64,7 @@ export async function checkboxWithHover<T>(theme: {...config.theme,style: {+ answer: (text: string) => pc.green(text),...config.theme?.style,highlight: (text: string) => pc.green(text),renderSelectedChoices: (diff --git a/skills/ctx7-cli/references/setup.md b/skills/ctx7-cli/references/setup.mdindex 709cf912..37a7e95b 100644--- a/skills/ctx7-cli/references/setup.md+++ b/skills/ctx7-cli/references/setup.md@@ -2,26 +2,42 @@## ctx7 setup-One-time command to configure Context7 MCP for your AI coding agent. Writes the MCP server config, a Context7 rule file, and a `documentation-lookup` skill.+One-time command to configure Context7 for your AI coding agent. Prompts for mode on first run:+- **MCP server** — registers the Context7 MCP server so the agent can call tools natively+- **CLI + Skills** — installs a `docs` skill that guides the agent to use `ctx7` CLI commands (no MCP required)```bash-ctx7 setup # Interactive — prompts for agent selection+ctx7 setup # Interactive — prompts for mode, then agent/install target+ctx7 setup --mcp # Skip prompt, use MCP server mode+ctx7 setup --cli # Skip prompt, use CLI + Skills mode++# MCP mode — target a specific agentctx7 setup --claude # Claude Code onlyctx7 setup --cursor # Cursor onlyctx7 setup --opencode # OpenCode only++# CLI + Skills mode — target a specific install location+ctx7 setup --cli --claude # Claude Code (~/.claude/skills)+ctx7 setup --cli --cursor # Cursor (~/.cursor/skills)+ctx7 setup --cli --universal # Universal (~/.config/agents/skills)+ctx7 setup --cli --antigravity # Antigravity (~/.config/agent/skills)+ctx7 setup --project # Configure current project instead of globallyctx7 setup --yes # Skip confirmation prompts```**Authentication options:**```bash-ctx7 setup --api-key YOUR_KEY # Use an existing API key-ctx7 setup --oauth # OAuth endpoint (IDE handles the auth flow)+ctx7 setup --api-key YOUR_KEY # Use an existing API key (both MCP and CLI + Skills mode)+ctx7 setup --oauth # OAuth endpoint — MCP mode only (IDE handles the auth flow)```-Without `--api-key` or `--oauth`, setup opens a browser for OAuth login and generates a new API key automatically.+Without `--api-key` or `--oauth`, setup opens a browser for OAuth login. MCP mode additionally generates a new API key after login. `--oauth` is MCP-only.-**What gets written:**+**What gets written — MCP mode:**- MCP server entry in the agent's config file (`.mcp.json` for Claude, `.cursor/mcp.json` for Cursor, `.opencode.json` for OpenCode)- A Context7 rule file instructing the agent to use Context7 for library docs- A `documentation-lookup` skill in the agent's skills directory++**What gets written — CLI + Skills mode:**+- A `docs` skill in the chosen agent's skills directory, guiding the agent to use `ctx7 library` and `ctx7 docs` commands