Skip to content

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

fix(cli): reuse device login API key during setup (#3109)

Fahreddin Özcan76140fc35897
diff --git a/.changeset/fuzzy-ravens-setup.md b/.changeset/fuzzy-ravens-setup.md
new file mode 100644
index 00000000..11b461f3
--- /dev/null
+++ b/.changeset/fuzzy-ravens-setup.md
@@ -0,0 +1,5 @@
+---
+"ctx7": patch
+---
+
+Use API keys returned by the device login flow directly during MCP setup instead of sending them to a dashboard session endpoint to generate another key.
diff --git a/docs/clients/cli.mdx b/docs/clients/cli.mdx
index 6124f651..dac8af72 100644
--- a/docs/clients/cli.mdx
+++ b/docs/clients/cli.mdx
@@ -148,7 +148,7 @@ ctx7 setup --api-key YOUR_API_KEY
ctx7 setup --oauth
```
-Without `--api-key` or `--oauth`, setup runs the OAuth device flow: it shows a verification link and short code that you open on any device to sign in, so it works the same locally or on a remote, headless, or SSH host. 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.
+Without `--api-key` or `--oauth`, setup runs the OAuth device flow: it shows a verification link and short code that you open on any device to sign in, so it works the same locally or on a remote, headless, or SSH host. The device flow returns an API key that setup uses for authentication. `--oauth` is MCP-only — use it when an IDE handles the auth flow on your behalf.
**What gets written — MCP mode:**
diff --git a/packages/cli/src/__tests__/auth-commands.test.ts b/packages/cli/src/__tests__/auth-commands.test.ts
index 847871a8..7b526edd 100644
--- a/packages/cli/src/__tests__/auth-commands.test.ts
+++ b/packages/cli/src/__tests__/auth-commands.test.ts
@@ -7,14 +7,17 @@ const mockSaveTokens = vi.fn();
const mockStartDeviceAuthorization = vi.fn();
const mockPollDeviceToken = vi.fn();
-vi.mock("../utils/auth.js", () => ({
- getValidAccessToken: (...args: unknown[]) => mockGetValidAccessToken(...args),
- clearTokens: (...args: unknown[]) => mockClearTokens(...args),
- saveTokens: (...args: unknown[]) => mockSaveTokens(...args),
- startDeviceAuthorization: (...args: unknown[]) => mockStartDeviceAuthorization(...args),
- pollDeviceToken: (...args: unknown[]) => mockPollDeviceToken(...args),
- DEFAULT_DEVICE_POLL_INTERVAL_SECONDS: 5,
-}));
+vi.mock("../utils/auth.js", async (importOriginal) => {
+ const original = await importOriginal<typeof import("../utils/auth.js")>();
+ return {
+ ...original,
+ getValidAccessToken: (...args: unknown[]) => mockGetValidAccessToken(...args),
+ clearTokens: (...args: unknown[]) => mockClearTokens(...args),
+ saveTokens: (...args: unknown[]) => mockSaveTokens(...args),
+ startDeviceAuthorization: (...args: unknown[]) => mockStartDeviceAuthorization(...args),
+ pollDeviceToken: (...args: unknown[]) => mockPollDeviceToken(...args),
+ };
+});
vi.mock("../utils/tracking.js", () => ({
trackEvent: vi.fn(),
@@ -148,6 +151,19 @@ describe("whoami command", () => {
expect(logOutput.some((l) => l.includes("[email protected]"))).toBe(true);
});
+ test("reports API-key authentication without calling the dashboard", async () => {
+ mockGetValidAccessToken.mockResolvedValue("ctx7sk-valid-key");
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+
+ await runCommand("whoami");
+
+ expect(logOutput.some((l) => l.includes("Logged in"))).toBe(true);
+ expect(logOutput).toHaveLength(1);
+ expect(logOutput.some((l) => l.includes("Session may be expired"))).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
test("shows session expired hint when fetch fails", async () => {
mockGetValidAccessToken.mockResolvedValue("valid-token");
vi.stubGlobal(
@@ -200,6 +216,8 @@ describe("performLogin", () => {
access_token: "ctx7sk-x",
token_type: "bearer",
});
+ expect(fetch).not.toHaveBeenCalled();
+ expect(mockSpinner.succeed).toHaveBeenCalledWith(expect.stringContaining("API key"));
});
test("returns null on denied", async () => {
diff --git a/packages/cli/src/__tests__/auth-utils.test.ts b/packages/cli/src/__tests__/auth-utils.test.ts
index 113b6086..bf92cdb2 100644
--- a/packages/cli/src/__tests__/auth-utils.test.ts
+++ b/packages/cli/src/__tests__/auth-utils.test.ts
@@ -22,6 +22,7 @@ import {
loadTokens,
clearTokens,
isTokenExpired,
+ isContext7ApiKey,
getValidAccessToken,
startDeviceAuthorization,
pollDeviceToken,
@@ -220,6 +221,16 @@ describe("isTokenExpired", () => {
});
});
+describe("isContext7ApiKey", () => {
+ test("recognizes Context7 API keys", () => {
+ expect(isContext7ApiKey("ctx7sk-example")).toBe(true);
+ });
+
+ test("rejects OAuth access tokens", () => {
+ expect(isContext7ApiKey("legacy-oauth-token")).toBe(false);
+ });
+});
+
describe("getValidAccessToken", () => {
test("returns undefined when no tokens stored", async () => {
mfs.existsSync.mockReturnValue(false);
diff --git a/packages/cli/src/__tests__/setup-auth.test.ts b/packages/cli/src/__tests__/setup-auth.test.ts
new file mode 100644
index 00000000..803db50a
--- /dev/null
+++ b/packages/cli/src/__tests__/setup-auth.test.ts
@@ -0,0 +1,81 @@
+import { beforeEach, describe, expect, test, vi } from "vitest";
+
+const mockGetValidAccessToken = vi.fn();
+vi.mock("../utils/auth.js", async (importOriginal) => {
+ const original = await importOriginal<typeof import("../utils/auth.js")>();
+ return {
+ ...original,
+ getValidAccessToken: (...args: unknown[]) => mockGetValidAccessToken(...args),
+ };
+});
+
+const mockPerformLogin = vi.fn();
+vi.mock("../commands/auth.js", () => ({
+ performLogin: (...args: unknown[]) => mockPerformLogin(...args),
+}));
+
+const mockSpinner = {
+ start: vi.fn().mockReturnThis(),
+ succeed: vi.fn().mockReturnThis(),
+ fail: vi.fn().mockReturnThis(),
+};
+vi.mock("ora", () => ({ default: () => mockSpinner }));
+
+vi.mock("../utils/api.js", async (importOriginal) => {
+ const original = await importOriginal<typeof import("../utils/api.js")>();
+ return {
+ ...original,
+ getBaseUrl: () => "https://test.context7.com",
+ };
+});
+
+import { resolveSetupApiKey } from "../setup/auth.js";
+
+describe("setup authentication", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.unstubAllGlobals();
+ });
+
+ test("uses a stored device-flow API key directly", async () => {
+ mockGetValidAccessToken.mockResolvedValue("ctx7sk-device-key");
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(resolveSetupApiKey()).resolves.toBe("ctx7sk-device-key");
+
+ expect(mockPerformLogin).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(mockSpinner.start).not.toHaveBeenCalled();
+ });
+
+ test("uses a newly authenticated device-flow API key directly", async () => {
+ mockGetValidAccessToken.mockResolvedValue(undefined);
+ mockPerformLogin.mockResolvedValue("ctx7sk-new-key");
+ const fetchMock = vi.fn();
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(resolveSetupApiKey()).resolves.toBe("ctx7sk-new-key");
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ test("still exchanges a legacy OAuth access token for an API key", async () => {
+ mockGetValidAccessToken.mockResolvedValue("legacy-oauth-token");
+ const fetchMock = vi.fn().mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ data: { apiKey: "ctx7sk-generated-key" } }),
+ });
+ vi.stubGlobal("fetch", fetchMock);
+
+ await expect(resolveSetupApiKey()).resolves.toBe("ctx7sk-generated-key");
+
+ expect(fetchMock).toHaveBeenCalledWith(
+ "https://test.context7.com/api/dashboard/api-keys",
+ expect.objectContaining({
+ method: "POST",
+ headers: expect.objectContaining({ Authorization: "Bearer legacy-oauth-token" }),
+ })
+ );
+ });
+});
diff --git a/packages/cli/src/commands/auth.ts b/packages/cli/src/commands/auth.ts
index df893109..d1271eb0 100644
--- a/packages/cli/src/commands/auth.ts
+++ b/packages/cli/src/commands/auth.ts
@@ -7,6 +7,7 @@ import {
saveTokens,
clearTokens,
getValidAccessToken,
+ isContext7ApiKey,
startDeviceAuthorization,
pollDeviceToken,
DEFAULT_DEVICE_POLL_INTERVAL_SECONDS,
@@ -95,6 +96,8 @@ function waitForEnter(prompt: string): Promise<void> {
}
async function announceIdentity(accessToken: string): Promise<string> {
+ if (isContext7ApiKey(accessToken)) return "Authenticated with API key";
+
try {
const whoami = await fetchWhoami(accessToken);
const name = whoami.email || whoami.name;
@@ -228,6 +231,10 @@ async function whoamiCommand(): Promise<void> {
console.log(pc.green("Logged in"));
+ if (isContext7ApiKey(accessToken)) {
+ return;
+ }
+
try {
const whoami = await fetchWhoami(accessToken);
if (whoami.name) {
diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.ts
index c2aab8c2..b4b4f581 100644
--- a/packages/cli/src/commands/setup.ts
+++ b/packages/cli/src/commands/setup.ts
@@ -4,15 +4,15 @@ import ora from "ora";
import { select } from "@inquirer/prompts";
import { mkdir, readFile, 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, downloadSkill } from "../utils/api.js";
+import { downloadSkill } from "../utils/api.js";
import { installSkillFiles } from "../utils/installer.js";
import { performLogin } from "./auth.js";
import { saveTokens, getValidAccessToken } from "../utils/auth.js";
+import { resolveSetupApiKey } from "../setup/auth.js";
import {
type SetupAgent,
type AuthOptions,
@@ -99,45 +99,11 @@ export function registerSetupCommand(program: Command): void {
});
}
-async function authenticateAndGenerateKey(): Promise<string | null> {
- const accessToken = (await getValidAccessToken()) ?? (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();
+ const apiKey = await resolveSetupApiKey();
if (!apiKey) return null;
return { mode: "api-key", apiKey };
}
diff --git a/packages/cli/src/setup/auth.ts b/packages/cli/src/setup/auth.ts
new file mode 100644
index 00000000..0cd70ab2
--- /dev/null
+++ b/packages/cli/src/setup/auth.ts
@@ -0,0 +1,42 @@
+import { randomBytes } from "crypto";
+import ora from "ora";
+
+import { performLogin } from "../commands/auth.js";
+import { getBaseUrl } from "../utils/api.js";
+import { getValidAccessToken, isContext7ApiKey } from "../utils/auth.js";
+import { log } from "../utils/logger.js";
+
+export async function resolveSetupApiKey(): Promise<string | null> {
+ const accessToken = (await getValidAccessToken()) ?? (await performLogin());
+
+ if (!accessToken) return null;
+ if (isContext7ApiKey(accessToken)) return accessToken;
+
+ 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;
+ }
+}
diff --git a/packages/cli/src/utils/auth.ts b/packages/cli/src/utils/auth.ts
index bbe02de8..2cb01143 100644
--- a/packages/cli/src/utils/auth.ts
+++ b/packages/cli/src/utils/auth.ts
@@ -20,6 +20,13 @@ export interface TokenData {
scope?: string;
}
+const CONTEXT7_API_KEY_PREFIX = "ctx7sk-";
+
+/** Returns true when a credential uses Context7's API-key format. */
+export function isContext7ApiKey(accessToken: string): boolean {
+ return accessToken.startsWith(CONTEXT7_API_KEY_PREFIX);
+}
+
function ensureConfigDir(): void {
const configDir = getConfigDir();
if (!fs.existsSync(configDir)) {
diff --git a/skills/context7-cli/references/setup.md b/skills/context7-cli/references/setup.md
index d8dc5d8b..1beddace 100644
--- a/skills/context7-cli/references/setup.md
+++ b/skills/context7-cli/references/setup.md
@@ -32,7 +32,7 @@ ctx7 setup --api-key YOUR_KEY # Use an existing API key (both MCP and CLI + Ski
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. MCP mode additionally generates a new API key after login. `--oauth` is MCP-only.
+Without `--api-key` or `--oauth`, setup opens a browser for OAuth login. The device flow returns an API key that setup uses for authentication. `--oauth` is MCP-only.
**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)