Skip to content

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

add `ctx7 setup` command (#1851)

Fahreddin Özcan3d6619128c80
diff --git a/.changeset/bright-foxes-march.md b/.changeset/bright-foxes-march.md
new file mode 100644
index 00000000..677ec1d1
--- /dev/null
+++ b/.changeset/bright-foxes-march.md
@@ -0,0 +1,5 @@
+---
+"ctx7": minor
+---
+
+Add `ctx7 setup` command for configuring Context7 MCP and rules across Claude Code, Cursor, and OpenCode
diff --git a/.gitignore b/.gitignore
index 285bbde0..da1bf49c 100644
--- a/.gitignore
+++ b/.gitignore
@@ -171,6 +171,7 @@ dist
# IntelliJ based IDEs
.idea
+.mcp.json
.cursor
!plugins/cursor/context7/.cursor
.opencode
diff --git a/README.md b/README.md
index 50d1540e..50eadf5b 100644
--- a/README.md
+++ b/README.md
@@ -140,15 +140,15 @@ Add this to your Opencode configuration file. See [Opencode MCP docs](https://op
</details>
<details>
-<summary><b>Install with add-mcp</b></summary>
+<summary><b>Install with ctx7 setup</b></summary>
-Install the MCP server for all your coding agents:
+Set up Context7 MCP for your coding agents:
```bash
-npx add-mcp https://mcp.context7.com/mcp --header "CONTEXT7_API_KEY: YOUR_API_KEY"
+npx ctx7 setup
```
-Add `-y` to skip the confirmation prompt and install to all detected agents already in use in the project directory.
+Authenticates via OAuth, generates an API key, and configures the MCP server and rule for your agents. Use `--cursor`, `--claude`, or `--opencode` to target a specific agent.
</details>
diff --git a/packages/cli/README.md b/packages/cli/README.md
index b2062190..44d94ed6 100644
--- a/packages/cli/README.md
+++ b/packages/cli/README.md
@@ -16,6 +16,18 @@ npm install -g ctx7
## Quick Start
+```bash
+# Set up Context7 MCP for your coding agents
+ctx7 setup
+
+# Target a specific agent
+ctx7 setup --cursor
+ctx7 setup --claude
+ctx7 setup --opencode
+```
+
+### Skills
+
```bash
# Search for skills
ctx7 skills search pdf
@@ -32,6 +44,32 @@ ctx7 skills list --claude
## Usage
+### Setup
+
+Configure Context7 MCP and a rule for your AI coding agents. Authenticates via OAuth, generates an API key, and writes the config.
+
+```bash
+# Interactive (prompts for agent selection)
+ctx7 setup
+
+# Target specific agents
+ctx7 setup --cursor
+ctx7 setup --claude
+ctx7 setup --opencode
+
+# Use an existing API key instead of OAuth
+ctx7 setup --api-key YOUR_API_KEY
+
+# Use OAuth endpoint (IDE handles auth flow)
+ctx7 setup --oauth
+
+# Configure for current project only (default is global)
+ctx7 setup --project
+
+# Skip prompts
+ctx7 setup --yes
+```
+
### Generate skills
Generate custom skills tailored to your use case using AI. Requires authentication.
diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.ts
new file mode 100644
index 00000000..d63d9f4c
--- /dev/null
+++ b/packages/cli/src/commands/setup.ts
@@ -0,0 +1,280 @@
+import { Command } from "commander";
+import pc from "picocolors";
+import ora from "ora";
+import { mkdir, writeFile } from "fs/promises";
+import { dirname, join } from "path";
+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 { performLogin } from "./auth.js";
+import { loadTokens, isTokenExpired } from "../utils/auth.js";
+import {
+ type SetupAgent,
+ type AuthOptions,
+ SETUP_AGENT_NAMES,
+ AUTH_MODE_LABELS,
+ ALL_AGENT_NAMES,
+ getAgent,
+ detectAgents,
+} from "../setup/agents.js";
+import { RULE_CONTENT } from "../setup/templates.js";
+import {
+ readJsonConfig,
+ mergeServerEntry,
+ mergeInstructions,
+ writeJsonConfig,
+} from "../setup/mcp-writer.js";
+
+type Scope = "global" | "project";
+
+interface SetupOptions {
+ claude?: boolean;
+ cursor?: boolean;
+ opencode?: boolean;
+ project?: boolean;
+ yes?: boolean;
+ apiKey?: string;
+ oauth?: boolean;
+}
+
+const CHECKBOX_THEME = {
+ style: {
+ highlight: (text: string) => pc.green(text),
+ disabledChoice: (text: string) => ` ${pc.dim("◯")} ${pc.dim(text)}`,
+ },
+};
+
+function getSelectedAgents(options: SetupOptions): SetupAgent[] {
+ const agents: SetupAgent[] = [];
+ if (options.claude) agents.push("claude");
+ if (options.cursor) agents.push("cursor");
+ if (options.opencode) agents.push("opencode");
+ return agents;
+}
+
+export function registerSetupCommand(program: Command): void {
+ program
+ .command("setup")
+ .description("Set up Context7 MCP and rule for your AI coding agent")
+ .option("--claude", "Set up for Claude Code")
+ .option("--cursor", "Set up for Cursor")
+ .option("--opencode", "Set up for OpenCode")
+ .option("-p, --project", "Configure for current project instead of globally")
+ .option("-y, --yes", "Skip confirmation prompts")
+ .option("--api-key <key>", "Use API key authentication")
+ .option("--oauth", "Use OAuth endpoint (IDE handles auth flow)")
+ .action(async (options: SetupOptions) => {
+ await setupCommand(options);
+ });
+}
+
+async function authenticateAndGenerateKey(): Promise<string | null> {
+ const existingTokens = loadTokens();
+ const accessToken =
+ existingTokens && !isTokenExpired(existingTokens)
+ ? existingTokens.access_token
+ : await performLogin();
+
+ if (!accessToken) return null;
+
+ const spinner = ora("Configuring authentication...").start();
+
+ try {
+ const response = await fetch(`${getBaseUrl()}/api/dashboard/api-keys`, {
+ method: "POST",
+ headers: {
+ Authorization: `Bearer ${accessToken}`,
+ "Content-Type": "application/json",
+ },
+ body: JSON.stringify({ name: `ctx7-cli-${randomBytes(3).toString("hex")}` }),
+ });
+
+ if (!response.ok) {
+ const err = (await response.json().catch(() => ({}))) as { message?: string; error?: string };
+ spinner.fail("Authentication failed");
+ log.error(err.message || err.error || `HTTP ${response.status}`);
+ return null;
+ }
+
+ const result = (await response.json()) as { data: { apiKey: string } };
+ spinner.succeed("Authenticated");
+ return result.data.apiKey;
+ } catch (err) {
+ spinner.fail("Authentication failed");
+ log.error(err instanceof Error ? err.message : String(err));
+ return null;
+ }
+}
+
+async function resolveAuth(options: SetupOptions): Promise<AuthOptions | null> {
+ if (options.apiKey) return { mode: "api-key", apiKey: options.apiKey };
+ if (options.oauth) return { mode: "oauth" };
+
+ const apiKey = await authenticateAndGenerateKey();
+ if (!apiKey) return null;
+ return { mode: "api-key", apiKey };
+}
+
+async function isAlreadyConfigured(agentName: SetupAgent, scope: Scope): Promise<boolean> {
+ const agent = getAgent(agentName);
+ const mcpPath =
+ scope === "global" ? agent.mcp.globalPath : join(process.cwd(), agent.mcp.projectPath);
+ try {
+ const existing = await readJsonConfig(mcpPath);
+ const section = (existing[agent.mcp.configKey] as Record<string, unknown> | undefined) ?? {};
+ return "context7" in section;
+ } catch {
+ return false;
+ }
+}
+
+async function promptAgents(scope: Scope): Promise<SetupAgent[] | null> {
+ const choices = await Promise.all(
+ ALL_AGENT_NAMES.map(async (name) => {
+ const configured = await isAlreadyConfigured(name, scope);
+ return {
+ name: SETUP_AGENT_NAMES[name],
+ value: name,
+ disabled: configured ? "(already configured)" : false,
+ };
+ })
+ );
+
+ if (choices.every((c) => c.disabled)) {
+ log.info("Context7 is already configured for all detected agents.");
+ return null;
+ }
+
+ try {
+ return await checkboxWithHover(
+ {
+ message: "Which agents do you want to set up?",
+ choices,
+ loop: false,
+ theme: CHECKBOX_THEME,
+ },
+ { getName: (a: SetupAgent) => SETUP_AGENT_NAMES[a] }
+ );
+ } catch {
+ return null;
+ }
+}
+
+async function resolveAgents(options: SetupOptions, scope: Scope): Promise<SetupAgent[]> {
+ const explicit = getSelectedAgents(options);
+ if (explicit.length > 0) return explicit;
+
+ const detected = await detectAgents(scope);
+
+ if (detected.length > 0 && options.yes) return detected;
+
+ log.blank();
+ const selected = await promptAgents(scope);
+ if (!selected) {
+ log.warn("Setup cancelled");
+ return [];
+ }
+ return selected;
+}
+
+async function setupAgent(
+ agentName: SetupAgent,
+ auth: AuthOptions,
+ scope: Scope
+): Promise<{
+ agent: string;
+ mcpStatus: string;
+ mcpPath: string;
+ ruleStatus: string;
+ rulePath: string;
+}> {
+ const agent = getAgent(agentName);
+
+ const mcpPath =
+ scope === "global" ? agent.mcp.globalPath : join(process.cwd(), agent.mcp.projectPath);
+
+ let mcpStatus: string;
+ try {
+ const existing = await readJsonConfig(mcpPath);
+ const { config, alreadyExists } = mergeServerEntry(
+ existing,
+ agent.mcp.configKey,
+ "context7",
+ agent.mcp.buildEntry(auth)
+ );
+
+ if (alreadyExists) {
+ mcpStatus = "already configured";
+ } else {
+ mcpStatus = `configured with ${AUTH_MODE_LABELS[auth.mode]}`;
+ }
+
+ const finalConfig = agent.rule.instructionsGlob
+ ? mergeInstructions(config, agent.rule.instructionsGlob(scope))
+ : config;
+
+ if (finalConfig !== existing) {
+ await writeJsonConfig(mcpPath, finalConfig);
+ }
+ } catch (err) {
+ mcpStatus = `failed: ${err instanceof Error ? err.message : String(err)}`;
+ }
+
+ const rulePath =
+ scope === "global"
+ ? join(agent.rule.dir("global"), agent.rule.filename)
+ : join(process.cwd(), agent.rule.dir("project"), agent.rule.filename);
+
+ let ruleStatus: string;
+ try {
+ await mkdir(dirname(rulePath), { recursive: true });
+ await writeFile(rulePath, RULE_CONTENT, "utf-8");
+ ruleStatus = "installed";
+ } catch (err) {
+ ruleStatus = `failed: ${err instanceof Error ? err.message : String(err)}`;
+ }
+
+ return { agent: agent.displayName, mcpStatus, mcpPath, ruleStatus, rulePath };
+}
+
+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;
+
+ const auth = await resolveAuth(options);
+ if (!auth) {
+ log.warn("Setup cancelled");
+ return;
+ }
+
+ log.blank();
+ const spinner = ora("Setting up Context7...").start();
+
+ const results = [];
+ for (const agentName of agents) {
+ spinner.text = `Setting up ${getAgent(agentName).displayName}...`;
+ results.push(await setupAgent(agentName, auth, scope));
+ }
+
+ spinner.succeed("Context7 setup complete");
+
+ log.blank();
+ for (const r of results) {
+ log.plain(` ${pc.bold(r.agent)}`);
+ const mcpIcon = r.mcpStatus.startsWith("configured") ? pc.green("+") : pc.dim("~");
+ log.plain(` ${mcpIcon} MCP server ${r.mcpStatus}`);
+ log.plain(` ${pc.dim(r.mcpPath)}`);
+ const ruleIcon = r.ruleStatus === "installed" ? pc.green("+") : pc.dim("~");
+ log.plain(` ${ruleIcon} Rule ${r.ruleStatus}`);
+ log.plain(` ${pc.dim(r.rulePath)}`);
+ }
+ log.blank();
+
+ trackEvent("setup", { agents, scope, authMode: auth.mode });
+}
diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.ts
index 6a1352fe..44442bcb 100644
--- a/packages/cli/src/index.ts
+++ b/packages/cli/src/index.ts
@@ -3,6 +3,7 @@ import pc from "picocolors";
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 { setBaseUrl } from "./utils/api.js";
import { VERSION } from "./constants.js";
@@ -52,6 +53,7 @@ Visit ${brand.primary("https://context7.com")} to browse skills
registerSkillCommands(program);
registerSkillAliases(program);
registerAuthCommands(program);
+registerSetupCommand(program);
program.action(() => {
console.log("");
diff --git a/packages/cli/src/setup/agents.ts b/packages/cli/src/setup/agents.ts
new file mode 100644
index 00000000..eae7122a
--- /dev/null
+++ b/packages/cli/src/setup/agents.ts
@@ -0,0 +1,156 @@
+import { access } from "fs/promises";
+import { join } from "path";
+import { homedir } from "os";
+
+export type SetupAgent = "claude" | "cursor" | "opencode";
+export type AuthMode = "oauth" | "api-key";
+
+export interface AuthOptions {
+ mode: AuthMode;
+ apiKey?: string;
+}
+
+export const SETUP_AGENT_NAMES: Record<SetupAgent, string> = {
+ claude: "Claude Code",
+ cursor: "Cursor",
+ opencode: "OpenCode",
+};
+
+export const AUTH_MODE_LABELS: Record<AuthMode, string> = {
+ oauth: "OAuth",
+ "api-key": "API Key",
+};
+
+const MCP_BASE_URL = "https://mcp.context7.com";
+
+export interface AgentConfig {
+ name: SetupAgent;
+ displayName: string;
+ mcp: {
+ projectPath: string;
+ globalPath: string;
+ configKey: string;
+ buildEntry: (auth: AuthOptions) => Record<string, unknown>;
+ };
+ rule: {
+ dir: (scope: "project" | "global") => string;
+ filename: string;
+ /** When set, the rule path is registered in the agent's config `instructions` array */
+ instructionsGlob?: (scope: "project" | "global") => string;
+ };
+ detect: {
+ projectPaths: string[];
+ globalPaths: string[];
+ };
+}
+
+function mcpUrl(auth: AuthOptions): string {
+ return auth.mode === "oauth" ? `${MCP_BASE_URL}/mcp/oauth` : `${MCP_BASE_URL}/mcp`;
+}
+
+function withHeaders(base: Record<string, unknown>, auth: AuthOptions): Record<string, unknown> {
+ if (auth.mode === "api-key" && auth.apiKey) {
+ return { ...base, headers: { CONTEXT7_API_KEY: auth.apiKey } };
+ }
+ return base;
+}
+
+const agents: Record<SetupAgent, AgentConfig> = {
+ claude: {
+ name: "claude",
+ displayName: "Claude Code",
+ mcp: {
+ projectPath: ".mcp.json",
+ globalPath: join(homedir(), ".claude.json"),
+ configKey: "mcpServers",
+ buildEntry: (auth) => withHeaders({ type: "http", url: mcpUrl(auth) }, auth),
+ },
+ rule: {
+ dir: (scope) =>
+ scope === "global" ? join(homedir(), ".claude", "rules") : join(".claude", "rules"),
+ filename: "context7.md",
+ },
+ detect: {
+ projectPaths: [".mcp.json", ".claude"],
+ globalPaths: [join(homedir(), ".claude")],
+ },
+ },
+
+ cursor: {
+ name: "cursor",
+ displayName: "Cursor",
+ mcp: {
+ projectPath: join(".cursor", "mcp.json"),
+ globalPath: join(homedir(), ".cursor", "mcp.json"),
+ configKey: "mcpServers",
+ buildEntry: (auth) => withHeaders({ url: mcpUrl(auth) }, auth),
+ },
+ rule: {
+ dir: (scope) =>
+ scope === "global" ? join(homedir(), ".cursor", "rules") : join(".cursor", "rules"),
+ filename: "context7.mdc",
+ },
+ detect: {
+ projectPaths: [".cursor"],
+ globalPaths: [join(homedir(), ".cursor")],
+ },
+ },
+
+ opencode: {
+ name: "opencode",
+ displayName: "OpenCode",
+ mcp: {
+ projectPath: ".opencode.json",
+ globalPath: join(homedir(), ".config", "opencode", "opencode.json"),
+ configKey: "mcp",
+ buildEntry: (auth) => withHeaders({ type: "remote", url: mcpUrl(auth), enabled: true }, auth),
+ },
+ rule: {
+ dir: (scope) =>
+ scope === "global"
+ ? join(homedir(), ".config", "opencode", "rules")
+ : join(".opencode", "rules"),
+ filename: "context7.md",
+ instructionsGlob: (scope) =>
+ scope === "global"
+ ? join(homedir(), ".config", "opencode", "rules", "*.md")
+ : ".opencode/rules/*.md",
+ },
+ detect: {
+ projectPaths: [".opencode.json"],
+ globalPaths: [join(homedir(), ".config", "opencode")],
+ },
+ },
+};
+
+export function getAgent(name: SetupAgent): AgentConfig {
+ return agents[name];
+}
+
+export const ALL_AGENT_NAMES: SetupAgent[] = Object.keys(agents) as SetupAgent[];
+
+async function pathExists(p: string): Promise<boolean> {
+ try {
+ await access(p);
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+export async function detectAgents(scope: "project" | "global"): Promise<SetupAgent[]> {
+ const detected: SetupAgent[] = [];
+
+ for (const agent of Object.values(agents)) {
+ const paths = scope === "global" ? agent.detect.globalPaths : agent.detect.projectPaths;
+ for (const p of paths) {
+ const fullPath = scope === "global" ? p : join(process.cwd(), p);
+ if (await pathExists(fullPath)) {
+ detected.push(agent.name);
+ break;
+ }
+ }
+ }
+
+ return detected;
+}
diff --git a/packages/cli/src/setup/mcp-writer.ts b/packages/cli/src/setup/mcp-writer.ts
new file mode 100644
index 00000000..abbb03ba
--- /dev/null
+++ b/packages/cli/src/setup/mcp-writer.ts
@@ -0,0 +1,57 @@
+import { readFile, writeFile, mkdir } from "fs/promises";
+import { dirname } from "path";
+
+export async function readJsonConfig(filePath: string): Promise<Record<string, unknown>> {
+ let raw: string;
+ try {
+ raw = await readFile(filePath, "utf-8");
+ } catch {
+ return {};
+ }
+
+ raw = raw.trim();
+ if (!raw) return {};
+
+ return JSON.parse(raw) as Record<string, unknown>;
+}
+
+export function mergeServerEntry(
+ existing: Record<string, unknown>,
+ configKey: string,
+ serverName: string,
+ entry: Record<string, unknown>
+): { config: Record<string, unknown>; alreadyExists: boolean } {
+ const section = (existing[configKey] as Record<string, unknown> | undefined) ?? {};
+
+ if (serverName in section) {
+ return { config: existing, alreadyExists: true };
+ }
+
+ return {
+ config: {
+ ...existing,
+ [configKey]: {
+ ...section,
+ [serverName]: entry,
+ },
+ },
+ alreadyExists: false,
+ };
+}
+
+export function mergeInstructions(
+ config: Record<string, unknown>,
+ glob: string
+): Record<string, unknown> {
+ const instructions = (config.instructions as string[] | undefined) ?? [];
+ if (instructions.includes(glob)) return config;
+ return { ...config, instructions: [...instructions, glob] };
+}
+
+export async function writeJsonConfig(
+ filePath: string,
+ config: Record<string, unknown>
+): Promise<void> {
+ await mkdir(dirname(filePath), { recursive: true });
+ await writeFile(filePath, JSON.stringify(config, null, 2) + "\n", "utf-8");
+}
diff --git a/packages/cli/src/setup/templates.ts b/packages/cli/src/setup/templates.ts
new file mode 100644
index 00000000..819fa570
--- /dev/null
+++ b/packages/cli/src/setup/templates.ts
@@ -0,0 +1,13 @@
+export const RULE_CONTENT = `---
+alwaysApply: true
+---
+
+When working with libraries, frameworks, or APIs — use Context7 MCP to fetch current documentation instead of relying on training data. This includes setup questions, code generation, API references, and anything involving specific packages.
+
+## Steps
+
+1. Call \`resolve-library-id\` with the library name and the user's question
+2. Pick the best match — prefer exact names and version-specific IDs when a version is mentioned
+3. Call \`query-docs\` with the selected library ID and the user's question
+4. Answer using the fetched docs — include code examples and cite the version
+`;