Skip to content

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

feat(mcp): prompt anonymous users to sign in (#2604)

Fahreddin Özcan34fda7d9b834
diff --git a/.changeset/funky-sides-behave.md b/.changeset/funky-sides-behave.md
new file mode 100644
index 00000000..49cf4d34
--- /dev/null
+++ b/.changeset/funky-sides-behave.md
@@ -0,0 +1,5 @@
+---
+"ctx7": patch
+---
+
+Add `--stdio` flag to `ctx7 setup` to configure Context7 as a local stdio MCP server.
diff --git a/.changeset/mcp-auth-prompt.md b/.changeset/mcp-auth-prompt.md
new file mode 100644
index 00000000..03cf68fc
--- /dev/null
+++ b/.changeset/mcp-auth-prompt.md
@@ -0,0 +1,9 @@
+---
+"@upstash/context7-mcp": minor
+---
+
+Prompt anonymous users to sign in. After the backend signals (via the `X-Context7-Auth-Prompt: 1` response header on `/v2/libs/search` or `/v2/context`) that an anonymous client has crossed the per-IP threshold, the MCP server appends a one-time sign-in invitation to the tool result.
+
+- Both **stdio** and **HTTP** transports surface the same nudge: a tool-result notice asking the assistant to run `npx ctx7 setup --<client> --mcp -y` (with `--stdio` appended when the MCP server is running on stdio) after explicit user confirmation. The CLI handles OAuth and writes credentials into the MCP client's config; the user restarts their MCP server / editor to pick up the new credentials.
+- Detects the calling client from `X-Context7-Client-IDE` / User-Agent and selects the matching CLI flag (`--cursor`, `--claude`, `--codex`, `--opencode`, `--gemini`); falls back to interactive setup when unknown.
+- HTTP transport remains stateless — the threshold is tracked by the backend (per-IP, 24h TTL), the MCP server only reacts to the signal.
diff --git a/packages/cli/src/__tests__/setup.test.ts b/packages/cli/src/__tests__/setup.test.ts
index 77c6e972..6b5c4bd9 100644
--- a/packages/cli/src/__tests__/setup.test.ts
+++ b/packages/cli/src/__tests__/setup.test.ts
@@ -26,10 +26,13 @@ import {
readJsonConfig,
writeJsonConfig,
readTomlServerExists,
+ readTomlServerEntry,
buildTomlServerBlock,
appendTomlServer,
removeTomlServer,
resolveMcpPath,
+ isStdioContext7Entry,
+ patchStdioApiKey,
} from "../setup/mcp-writer.js";
import { getAgent, ALL_AGENT_NAMES, type AuthOptions } from "../setup/agents.js";
@@ -625,7 +628,7 @@ describe("agent config integration", () => {
const agent = getAgent("claude");
test("buildEntry with api-key produces correct shape", () => {
- const entry = agent.mcp.buildEntry(apiKeyAuth);
+ const entry = agent.mcp.buildEntry(apiKeyAuth, "http");
expect(entry).toEqual({
type: "http",
url: "https://mcp.context7.com/mcp",
@@ -634,7 +637,7 @@ describe("agent config integration", () => {
});
test("buildEntry with oauth produces correct shape", () => {
- const entry = agent.mcp.buildEntry(oauthAuth);
+ const entry = agent.mcp.buildEntry(oauthAuth, "http");
expect(entry).toEqual({
type: "http",
url: "https://mcp.context7.com/mcp/oauth",
@@ -669,7 +672,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
await writeJsonConfig(path, config);
@@ -693,7 +696,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
expect(alreadyExists).toBe(true);
await writeJsonConfig(path, config);
@@ -711,7 +714,7 @@ describe("agent config integration", () => {
const agent = getAgent("cursor");
test("buildEntry with api-key produces correct shape (no type field)", () => {
- const entry = agent.mcp.buildEntry(apiKeyAuth);
+ const entry = agent.mcp.buildEntry(apiKeyAuth, "http");
expect(entry).toEqual({
url: "https://mcp.context7.com/mcp",
headers: { CONTEXT7_API_KEY: "sk-test-123" },
@@ -720,7 +723,7 @@ describe("agent config integration", () => {
});
test("buildEntry with oauth produces correct shape", () => {
- const entry = agent.mcp.buildEntry(oauthAuth);
+ const entry = agent.mcp.buildEntry(oauthAuth, "http");
expect(entry).toEqual({
url: "https://mcp.context7.com/mcp/oauth",
});
@@ -733,7 +736,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(oauthAuth)
+ agent.mcp.buildEntry(oauthAuth, "http")
);
await writeJsonConfig(path, config);
@@ -754,7 +757,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
expect(alreadyExists).toBe(true);
await writeJsonConfig(path, config);
@@ -773,7 +776,7 @@ describe("agent config integration", () => {
const agent = getAgent("opencode");
test("buildEntry with api-key includes type, url, enabled, and headers", () => {
- const entry = agent.mcp.buildEntry(apiKeyAuth);
+ const entry = agent.mcp.buildEntry(apiKeyAuth, "http");
expect(entry).toEqual({
type: "remote",
url: "https://mcp.context7.com/mcp",
@@ -783,7 +786,7 @@ describe("agent config integration", () => {
});
test("buildEntry with oauth includes type, url, enabled without headers", () => {
- const entry = agent.mcp.buildEntry(oauthAuth);
+ const entry = agent.mcp.buildEntry(oauthAuth, "http");
expect(entry).toEqual({
type: "remote",
url: "https://mcp.context7.com/mcp/oauth",
@@ -804,7 +807,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
await writeJsonConfig(path, config);
@@ -829,7 +832,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(oauthAuth)
+ agent.mcp.buildEntry(oauthAuth, "http")
);
expect(alreadyExists).toBe(true);
await writeJsonConfig(path, config);
@@ -859,7 +862,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
await writeJsonConfig(path, config);
@@ -873,7 +876,7 @@ describe("agent config integration", () => {
const agent = getAgent("codex");
test("buildEntry with api-key produces correct shape", () => {
- const entry = agent.mcp.buildEntry(apiKeyAuth);
+ const entry = agent.mcp.buildEntry(apiKeyAuth, "http");
expect(entry).toEqual({
type: "http",
url: "https://mcp.context7.com/mcp",
@@ -882,7 +885,7 @@ describe("agent config integration", () => {
});
test("buildEntry with oauth produces correct shape", () => {
- const entry = agent.mcp.buildEntry(oauthAuth);
+ const entry = agent.mcp.buildEntry(oauthAuth, "http");
expect(entry).toEqual({
type: "http",
url: "https://mcp.context7.com/mcp/oauth",
@@ -894,7 +897,7 @@ describe("agent config integration", () => {
const { alreadyExists } = await appendTomlServer(
path,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
expect(alreadyExists).toBe(false);
@@ -908,7 +911,7 @@ describe("agent config integration", () => {
test("appends oauth entry to TOML without headers", async () => {
const path = join(tempDir, "config.toml");
- await appendTomlServer(path, "context7", agent.mcp.buildEntry(oauthAuth));
+ await appendTomlServer(path, "context7", agent.mcp.buildEntry(oauthAuth, "http"));
const content = await readFile(path, "utf-8");
expect(content).toContain("[mcp_servers.context7]");
@@ -918,11 +921,11 @@ describe("agent config integration", () => {
test("overwrites existing TOML config", async () => {
const path = join(tempDir, "config.toml");
- await appendTomlServer(path, "context7", agent.mcp.buildEntry(oauthAuth));
+ await appendTomlServer(path, "context7", agent.mcp.buildEntry(oauthAuth, "http"));
const { alreadyExists } = await appendTomlServer(
path,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
expect(alreadyExists).toBe(true);
@@ -939,7 +942,7 @@ describe("agent config integration", () => {
path,
'[mcp_servers.other]\nurl = "https://other.com"\n\n[mcp_servers.context7]\ntype = "http"\nurl = "https://old.com"\n'
);
- await appendTomlServer(path, "context7", agent.mcp.buildEntry(apiKeyAuth));
+ await appendTomlServer(path, "context7", agent.mcp.buildEntry(apiKeyAuth, "http"));
const content = await readFile(path, "utf-8");
expect(content).toContain("[mcp_servers.other]");
@@ -953,7 +956,7 @@ describe("agent config integration", () => {
const agent = getAgent("gemini");
test("buildEntry with api-key uses httpUrl", () => {
- const entry = agent.mcp.buildEntry(apiKeyAuth);
+ const entry = agent.mcp.buildEntry(apiKeyAuth, "http");
expect(entry).toEqual({
httpUrl: "https://mcp.context7.com/mcp",
headers: { CONTEXT7_API_KEY: "sk-test-123" },
@@ -962,7 +965,7 @@ describe("agent config integration", () => {
});
test("buildEntry with oauth uses httpUrl without headers", () => {
- const entry = agent.mcp.buildEntry(oauthAuth);
+ const entry = agent.mcp.buildEntry(oauthAuth, "http");
expect(entry).toEqual({
httpUrl: "https://mcp.context7.com/mcp/oauth",
});
@@ -981,7 +984,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
await writeJsonConfig(path, config);
@@ -1004,7 +1007,7 @@ describe("agent config integration", () => {
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(apiKeyAuth)
+ agent.mcp.buildEntry(apiKeyAuth, "http")
);
expect(alreadyExists).toBe(true);
await writeJsonConfig(path, config);
@@ -1024,8 +1027,8 @@ describe("agent config integration", () => {
test.each(ALL_AGENT_NAMES)("%s buildEntry returns url for both auth modes", (name) => {
const agent = getAgent(name);
- const apiEntry = agent.mcp.buildEntry(apiKeyAuth);
- const oauthEntry = agent.mcp.buildEntry(oauthAuth);
+ const apiEntry = agent.mcp.buildEntry(apiKeyAuth, "http");
+ const oauthEntry = agent.mcp.buildEntry(oauthAuth, "http");
const urlKey = name === "gemini" ? "httpUrl" : "url";
expect(apiEntry[urlKey]).toBe("https://mcp.context7.com/mcp");
@@ -1034,8 +1037,8 @@ describe("agent config integration", () => {
test.each(ALL_AGENT_NAMES)("%s buildEntry includes headers only for api-key auth", (name) => {
const agent = getAgent(name);
- const apiEntry = agent.mcp.buildEntry(apiKeyAuth);
- const oauthEntry = agent.mcp.buildEntry(oauthAuth);
+ const apiEntry = agent.mcp.buildEntry(apiKeyAuth, "http");
+ const oauthEntry = agent.mcp.buildEntry(oauthAuth, "http");
expect(apiEntry.headers).toEqual({ CONTEXT7_API_KEY: "sk-test-123" });
expect(oauthEntry).not.toHaveProperty("headers");
@@ -1043,8 +1046,261 @@ describe("agent config integration", () => {
test.each(ALL_AGENT_NAMES)("%s buildEntry without apiKey omits headers", (name) => {
const agent = getAgent(name);
- const entry = agent.mcp.buildEntry({ mode: "api-key" });
+ const entry = agent.mcp.buildEntry({ mode: "api-key" }, "http");
expect(entry).not.toHaveProperty("headers");
});
});
+
+ describe("stdio buildEntry", () => {
+ const apiKeyAuth: AuthOptions = { mode: "api-key", apiKey: "sk-test-stdio" };
+ const oauthAuth: AuthOptions = { mode: "oauth" };
+
+ test("claude stdio entry uses npx command with --api-key in args", () => {
+ const entry = getAgent("claude").mcp.buildEntry(apiKeyAuth, "stdio");
+ expect(entry).toEqual({
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp", "--api-key", "sk-test-stdio"],
+ });
+ });
+
+ test("cursor stdio entry uses npx command with --api-key in args", () => {
+ const entry = getAgent("cursor").mcp.buildEntry(apiKeyAuth, "stdio");
+ expect(entry).toEqual({
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp", "--api-key", "sk-test-stdio"],
+ });
+ });
+
+ test("opencode stdio entry uses type:local with array command", () => {
+ const entry = getAgent("opencode").mcp.buildEntry(apiKeyAuth, "stdio");
+ expect(entry).toEqual({
+ type: "local",
+ command: ["npx", "-y", "@upstash/context7-mcp", "--api-key", "sk-test-stdio"],
+ enabled: true,
+ });
+ });
+
+ test("codex stdio entry uses npx command with --api-key in args", () => {
+ const entry = getAgent("codex").mcp.buildEntry(apiKeyAuth, "stdio");
+ expect(entry).toEqual({
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp", "--api-key", "sk-test-stdio"],
+ });
+ });
+
+ test("gemini stdio entry uses npx command with --api-key in args", () => {
+ const entry = getAgent("gemini").mcp.buildEntry(apiKeyAuth, "stdio");
+ expect(entry).toEqual({
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp", "--api-key", "sk-test-stdio"],
+ });
+ });
+
+ test.each(ALL_AGENT_NAMES)("%s stdio entry omits --api-key for oauth mode", (name) => {
+ const entry = getAgent(name).mcp.buildEntry(oauthAuth, "stdio");
+ const args = (entry.args ?? entry.command) as string[];
+ expect(args).not.toContain("--api-key");
+ expect(args).toContain("@upstash/context7-mcp");
+ });
+
+ test("codex stdio entry serializes to TOML correctly", () => {
+ const block = buildTomlServerBlock(
+ "context7",
+ getAgent("codex").mcp.buildEntry(apiKeyAuth, "stdio")
+ );
+ expect(block).toContain("[mcp_servers.context7]");
+ expect(block).toContain('command = "npx"');
+ expect(block).toContain('args = ["-y","@upstash/context7-mcp","--api-key","sk-test-stdio"]');
+ expect(block).not.toContain("http_headers");
+ });
+ });
+
+ describe("isStdioContext7Entry", () => {
+ test("detects standard command/args stdio entry", () => {
+ expect(
+ isStdioContext7Entry({
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp", "--api-key", "k"],
+ })
+ ).toBe(true);
+ });
+
+ test("detects entry with @latest specifier", () => {
+ expect(
+ isStdioContext7Entry({ command: "npx", args: ["-y", "@upstash/context7-mcp@latest"] })
+ ).toBe(true);
+ });
+
+ test("detects entry with pinned version", () => {
+ expect(
+ isStdioContext7Entry({ command: "npx", args: ["-y", "@upstash/[email protected]"] })
+ ).toBe(true);
+ });
+
+ test("detects OpenCode array-command form", () => {
+ expect(
+ isStdioContext7Entry({
+ type: "local",
+ command: ["npx", "-y", "@upstash/context7-mcp@latest"],
+ enabled: true,
+ })
+ ).toBe(true);
+ });
+
+ test("returns false for HTTP entry", () => {
+ expect(isStdioContext7Entry({ url: "https://mcp.context7.com/mcp" })).toBe(false);
+ });
+
+ test("returns false for unrelated stdio package", () => {
+ expect(isStdioContext7Entry({ command: "npx", args: ["-y", "@some-other/package"] })).toBe(
+ false
+ );
+ });
+
+ test("returns false for null/undefined", () => {
+ expect(isStdioContext7Entry(null)).toBe(false);
+ expect(isStdioContext7Entry(undefined)).toBe(false);
+ });
+ });
+
+ describe("patchStdioApiKey", () => {
+ test("preserves @latest package specifier", () => {
+ const patched = patchStdioApiKey(
+ { command: "npx", args: ["-y", "@upstash/context7-mcp@latest"] },
+ "new-key"
+ );
+ expect(patched).toEqual({
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp@latest", "--api-key", "new-key"],
+ });
+ });
+
+ test("preserves pinned version specifier", () => {
+ const patched = patchStdioApiKey(
+ { command: "npx", args: ["-y", "@upstash/[email protected]"] },
+ "new-key"
+ );
+ expect(patched.args).toEqual(["-y", "@upstash/[email protected]", "--api-key", "new-key"]);
+ });
+
+ test("replaces an existing --api-key value", () => {
+ const patched = patchStdioApiKey(
+ {
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp@latest", "--api-key", "OLD"],
+ },
+ "NEW"
+ );
+ expect(patched.args).toEqual(["-y", "@upstash/context7-mcp@latest", "--api-key", "NEW"]);
+ });
+
+ test("removes --api-key when new key is undefined (oauth)", () => {
+ const patched = patchStdioApiKey(
+ { command: "npx", args: ["-y", "@upstash/context7-mcp", "--api-key", "OLD"] },
+ undefined
+ );
+ expect(patched.args).toEqual(["-y", "@upstash/context7-mcp"]);
+ });
+
+ test("preserves other args (e.g. --debug) untouched", () => {
+ const patched = patchStdioApiKey(
+ {
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp", "--debug", "--api-key", "OLD"],
+ },
+ "NEW"
+ );
+ expect(patched.args).toEqual(["-y", "@upstash/context7-mcp", "--debug", "--api-key", "NEW"]);
+ });
+
+ test("patches OpenCode array-command form", () => {
+ const patched = patchStdioApiKey(
+ {
+ type: "local",
+ command: ["npx", "-y", "@upstash/context7-mcp@latest", "--api-key", "OLD"],
+ enabled: true,
+ },
+ "NEW"
+ );
+ expect(patched).toEqual({
+ type: "local",
+ command: ["npx", "-y", "@upstash/context7-mcp@latest", "--api-key", "NEW"],
+ enabled: true,
+ });
+ });
+
+ test("preserves unrelated top-level fields", () => {
+ const patched = patchStdioApiKey(
+ { command: "npx", args: ["-y", "@upstash/context7-mcp"], cwd: "/custom" },
+ "NEW"
+ );
+ expect(patched.cwd).toBe("/custom");
+ });
+ });
+
+ describe("readTomlServerEntry", () => {
+ let tempDir: string;
+
+ beforeEach(async () => {
+ tempDir = join(tmpdir(), `ctx7-test-${Date.now()}`);
+ await mkdir(tempDir, { recursive: true });
+ });
+
+ afterEach(async () => {
+ await rm(tempDir, { recursive: true, force: true });
+ });
+
+ test("returns undefined for missing file", async () => {
+ expect(await readTomlServerEntry(join(tempDir, "nope.toml"), "context7")).toBeUndefined();
+ });
+
+ test("returns undefined for missing section", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(path, '[mcp_servers.other]\nurl = "https://other.com"\n', "utf-8");
+ expect(await readTomlServerEntry(path, "context7")).toBeUndefined();
+ });
+
+ test("parses string and array values from a stdio block", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(
+ path,
+ '[mcp_servers.context7]\ncommand = "npx"\nargs = ["-y", "@upstash/context7-mcp@latest", "--api-key", "OLD"]\n',
+ "utf-8"
+ );
+ const entry = await readTomlServerEntry(path, "context7");
+ expect(entry).toEqual({
+ command: "npx",
+ args: ["-y", "@upstash/context7-mcp@latest", "--api-key", "OLD"],
+ });
+ });
+
+ test("ignores http_headers sub-table", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(
+ path,
+ '[mcp_servers.context7]\ntype = "http"\nurl = "https://mcp.context7.com/mcp"\n\n[mcp_servers.context7.http_headers]\nCONTEXT7_API_KEY = "k"\n',
+ "utf-8"
+ );
+ const entry = await readTomlServerEntry(path, "context7");
+ expect(entry).toEqual({ type: "http", url: "https://mcp.context7.com/mcp" });
+ });
+
+ test("round-trips through patchStdioApiKey + appendTomlServer", async () => {
+ const path = join(tempDir, "config.toml");
+ await writeFile(
+ path,
+ '[mcp_servers.context7]\ncommand = "npx"\nargs = ["-y", "@upstash/context7-mcp@latest", "--api-key", "OLD"]\n',
+ "utf-8"
+ );
+ const existing = await readTomlServerEntry(path, "context7");
+ expect(existing).toBeDefined();
+ expect(isStdioContext7Entry(existing)).toBe(true);
+ const patched = patchStdioApiKey(existing!, "NEW");
+ await appendTomlServer(path, "context7", patched);
+ const content = await readFile(path, "utf-8");
+ expect(content).toContain("@upstash/context7-mcp@latest");
+ expect(content).toContain('"--api-key","NEW"');
+ expect(content).not.toContain('"OLD"');
+ });
+ });
});
diff --git a/packages/cli/src/commands/setup.ts b/packages/cli/src/commands/setup.ts
index dfbfe54e..b2037985 100644
--- a/packages/cli/src/commands/setup.ts
+++ b/packages/cli/src/commands/setup.ts
@@ -16,6 +16,7 @@ import { saveTokens, getValidAccessToken } from "../utils/auth.js";
import {
type SetupAgent,
type AuthOptions,
+ type Transport,
SETUP_AGENT_NAMES,
AUTH_MODE_LABELS,
ALL_AGENT_NAMES,
@@ -29,6 +30,10 @@ import {
writeJsonConfig,
resolveMcpPath,
appendTomlServer,
+ readTomlServerEntry,
+ isStdioContext7Entry,
+ patchStdioApiKey,
+ getJsonServerEntry,
} from "../setup/mcp-writer.js";
type Scope = "global" | "project";
@@ -48,6 +53,11 @@ interface SetupOptions {
oauth?: boolean;
cli?: boolean;
mcp?: boolean;
+ stdio?: boolean;
+}
+
+function resolveTransport(options: SetupOptions): Transport {
+ return options.stdio ? "stdio" : "http";
}
const CHECKBOX_THEME = {
@@ -84,6 +94,7 @@ export function registerSetupCommand(program: Command): void {
.option("-y, --yes", "Skip confirmation prompts")
.option("--api-key <key>", "Use API key authentication")
.option("--oauth", "Use OAuth endpoint (IDE handles auth flow)")
+ .option("--stdio", "Configure the MCP server as a local stdio process (default: HTTP)")
.action(async (options: SetupOptions) => {
await setupCommand(options);
});
@@ -134,7 +145,7 @@ async function resolveAuth(options: SetupOptions): Promise<AuthOptions | null> {
async function resolveMode(options: SetupOptions): Promise<SetupMode> {
if (options.cli) return "cli";
- if (options.mcp || options.yes || options.oauth || options.apiKey) return "mcp";
+ if (options.mcp || options.yes || options.oauth || options.apiKey || options.stdio) return "mcp";
return select<SetupMode>({
message: "How should your agent access Context7?",
@@ -260,9 +271,30 @@ async function installRule(
return { status: "installed", path: filePath };
}
+/**
+ * For stdio transport, preserve an existing `@upstash/context7-mcp` invocation
+ * (e.g., `@upstash/context7-mcp@latest` or a user-pinned version) and only
+ * swap the `--api-key` value. Falls back to the agent's canonical shape when
+ * no existing stdio entry is detected. HTTP transport always uses the
+ * canonical shape.
+ */
+function resolveEntryToWrite(
+ agent: ReturnType<typeof getAgent>,
+ auth: AuthOptions,
+ transport: Transport,
+ existingEntry: Record<string, unknown> | undefined
+): Record<string, unknown> {
+ if (transport === "stdio" && existingEntry && isStdioContext7Entry(existingEntry)) {
+ const apiKey = auth.mode === "api-key" ? auth.apiKey : undefined;
+ return patchStdioApiKey(existingEntry, apiKey);
+ }
+ return agent.mcp.buildEntry(auth, transport);
+}
+
async function setupAgent(
agentName: SetupAgent,
auth: AuthOptions,
+ transport: Transport,
scope: Scope
): Promise<{
agent: string;
@@ -284,21 +316,25 @@ async function setupAgent(
let mcpStatus: string;
try {
if (mcpPath.endsWith(".toml")) {
- const { alreadyExists } = await appendTomlServer(
- mcpPath,
- "context7",
- agent.mcp.buildEntry(auth)
- );
+ const existingTomlEntry =
+ transport === "stdio" ? await readTomlServerEntry(mcpPath, "context7") : undefined;
+ const entry = resolveEntryToWrite(agent, auth, transport, existingTomlEntry);
+ const { alreadyExists } = await appendTomlServer(mcpPath, "context7", entry);
mcpStatus = alreadyExists
? `reconfigured with ${AUTH_MODE_LABELS[auth.mode]}`
: `configured with ${AUTH_MODE_LABELS[auth.mode]}`;
} else {
const existing = await readJsonConfig(mcpPath);
+ const existingJsonEntry =
+ transport === "stdio"
+ ? getJsonServerEntry(existing, agent.mcp.configKey, "context7")
+ : undefined;
+ const entry = resolveEntryToWrite(agent, auth, transport, existingJsonEntry);
const { config, alreadyExists } = mergeServerEntry(
existing,
agent.mcp.configKey,
"context7",
- agent.mcp.buildEntry(auth)
+ entry
);
mcpStatus = alreadyExists
? `reconfigured with ${AUTH_MODE_LABELS[auth.mode]}`
@@ -350,6 +386,12 @@ async function setupAgent(
}
async function setupMcp(agents: SetupAgent[], options: SetupOptions, scope: Scope): Promise<void> {
+ const transport = resolveTransport(options);
+ if (transport === "stdio" && options.oauth) {
+ log.error("--stdio is incompatible with --oauth (OAuth uses the hosted HTTP endpoint).");
+ return;
+ }
+
const auth = await resolveAuth(options);
if (!auth) {
log.warn("Setup cancelled");
@@ -362,7 +404,7 @@ async function setupMcp(agents: SetupAgent[], options: SetupOptions, scope: Scop
const results = [];
for (const agentName of agents) {
spinner.text = `Setting up ${getAgent(agentName).displayName}...`;
- results.push(await setupAgent(agentName, auth, scope));
+ results.push(await setupAgent(agentName, auth, transport, scope));
}
spinner.succeed("Context7 setup complete");
diff --git a/packages/cli/src/setup/agents.ts b/packages/cli/src/setup/agents.ts
index dac7bcb6..de60b869 100644
--- a/packages/cli/src/setup/agents.ts
+++ b/packages/cli/src/setup/agents.ts
@@ -4,6 +4,7 @@ import { homedir } from "os";
export type SetupAgent = "claude" | "cursor" | "opencode" | "codex" | "gemini";
export type AuthMode = "oauth" | "api-key";
+export type Transport = "http" | "stdio";
export interface AuthOptions {
mode: AuthMode;
@@ -24,6 +25,19 @@ export const AUTH_MODE_LABELS: Record<AuthMode, string> = {
};
const MCP_BASE_URL = "https://mcp.context7.com";
+export const STDIO_PACKAGE = "@upstash/context7-mcp";
+
+function stdioArgs(auth: AuthOptions): string[] {
+ const args = ["-y", STDIO_PACKAGE];
+ if (auth.mode === "api-key" && auth.apiKey) {
+ args.push("--api-key", auth.apiKey);
+ }
+ return args;
+}
+
+function stdioEntry(auth: AuthOptions): Record<string, unknown> {
+ return { command: "npx", args: stdioArgs(auth) };
+}
function claudeConfigDir(): string {
return process.env.CLAUDE_CONFIG_DIR || join(homedir(), ".claude");
@@ -51,7 +65,7 @@ export interface AgentConfig {
projectPaths: string[];
globalPaths: string[];
configKey: string;
- buildEntry: (auth: AuthOptions) => Record<string, unknown>;
+ buildEntry: (auth: AuthOptions, transport: Transport) => Record<string, unknown>;
};
rule: RuleType;
skill: {
@@ -85,7 +99,10 @@ const agents: Record<SetupAgent, AgentConfig> = {
return [claudeGlobalMcpPath()];
},
configKey: "mcpServers",
- buildEntry: (auth) => withHeaders({ type: "http", url: mcpUrl(auth) }, auth),
+ buildEntry: (auth, transport) =>
+ transport === "stdio"
+ ? stdioEntry(auth)
+ : withHeaders({ type: "http", url: mcpUrl(auth) }, auth),
},
rule: {
kind: "file",
@@ -113,7 +130,8 @@ const agents: Record<SetupAgent, AgentConfig> = {
projectPaths: [join(".cursor", "mcp.json")],
globalPaths: [join(homedir(), ".cursor", "mcp.json")],
configKey: "mcpServers",
- buildEntry: (auth) => withHeaders({ url: mcpUrl(auth) }, auth),
+ buildEntry: (auth, transport) =>
+ transport === "stdio" ? stdioEntry(auth) : withHeaders({ url: mcpUrl(auth) }, auth),
},
rule: {
kind: "file",
@@ -144,7 +162,10 @@ const agents: Record<SetupAgent, AgentConfig> = {
join(homedir(), ".config", "opencode", ".opencode.jsonc"),
],
configKey: "mcp",
- buildEntry: (auth) => withHeaders({ type: "remote", url: mcpUrl(auth), enabled: true }, auth),
+ buildEntry: (auth, transport) =>
+ transport === "stdio"
+ ? { type: "local", command: ["npx", ...stdioArgs(auth)], enabled: true }
+ : withHeaders({ type: "remote", url: mcpUrl(auth), enabled: true }, auth),
},
rule: {
kind: "append",
@@ -170,13 +191,10 @@ const agents: Record<SetupAgent, AgentConfig> = {
projectPaths: [join(".codex", "config.toml")],
globalPaths: [join(homedir(), ".codex", "config.toml")],
configKey: "mcp_servers",
- buildEntry: (auth) => {
- const entry: Record<string, unknown> = { type: "http", url: mcpUrl(auth) };
- if (auth.mode === "api-key" && auth.apiKey) {
- entry.headers = { CONTEXT7_API_KEY: auth.apiKey };
- }
- return entry;
- },
+ buildEntry: (auth, transport) =>
+ transport === "stdio"
+ ? stdioEntry(auth)
+ : withHeaders({ type: "http", url: mcpUrl(auth) }, auth),
},
rule: {
kind: "append",
@@ -201,7 +219,8 @@ const agents: Record<SetupAgent, AgentConfig> = {
projectPaths: [join(".gemini", "settings.json")],
globalPaths: [join(homedir(), ".gemini", "settings.json")],
configKey: "mcpServers",
- buildEntry: (auth) => withHeaders({ httpUrl: mcpUrl(auth) }, auth),
+ buildEntry: (auth, transport) =>
+ transport === "stdio" ? stdioEntry(auth) : withHeaders({ httpUrl: mcpUrl(auth) }, auth),
},
rule: {
kind: "append",
diff --git a/packages/cli/src/setup/mcp-writer.ts b/packages/cli/src/setup/mcp-writer.ts
index 884f588d..1c9ddf16 100644
--- a/packages/cli/src/setup/mcp-writer.ts
+++ b/packages/cli/src/setup/mcp-writer.ts
@@ -1,5 +1,6 @@
import { access, readFile, writeFile, mkdir } from "fs/promises";
import { dirname } from "path";
+import { STDIO_PACKAGE } from "./agents.js";
function stripJsonComments(text: string): string {
let result = "";
@@ -115,6 +116,117 @@ export async function readTomlServerExists(filePath: string, serverName: string)
}
}
+/**
+ * Reads the top-level `[mcp_servers.<serverName>]` block from a TOML config
+ * file and parses its key-value lines into a JS object. Handles string and
+ * array values (TOML array syntax is JSON-compatible). Sub-tables like
+ * `[mcp_servers.<serverName>.http_headers]` are ignored. Returns undefined
+ * if the file or section is missing.
+ */
+export async function readTomlServerEntry(
+ filePath: string,
+ serverName: string
+): Promise<Record<string, unknown> | undefined> {
+ let raw: string;
+ try {
+ raw = await readFile(filePath, "utf-8");
+ } catch {
+ return undefined;
+ }
+
+ const sectionHeader = `[mcp_servers.${serverName}]`;
+ const startIdx = raw.indexOf(sectionHeader);
+ if (startIdx === -1) return undefined;
+
+ // The top-level table's values live between its header and the next `[...]`
+ // header (whether that's a sub-table like `[mcp_servers.foo.http_headers]`
+ // or an unrelated section). Sub-table values belong to the sub-table, not
+ // here, so excluding them is correct.
+ const rest = raw.slice(startIdx + sectionHeader.length);
+ const nextHeader = /^\[/m.exec(rest);
+ const block = nextHeader ? rest.slice(0, nextHeader.index) : rest;
+
+ const entry: Record<string, unknown> = {};
+ const lineRe = /^([A-Za-z_][\w-]*)\s*=\s*(.+?)\s*$/gm;
+ let lineMatch: RegExpExecArray | null;
+ while ((lineMatch = lineRe.exec(block)) !== null) {
+ const [, key, valueText] = lineMatch;
+ try {
+ entry[key] = JSON.parse(valueText);
+ } catch {
+ // Skip values we can't parse as JSON (e.g., bare TOML numbers like 20)
+ }
+ }
+ return Object.keys(entry).length > 0 ? entry : undefined;
+}
+
+/**
+ * True when `entry` looks like a stdio invocation of `@upstash/context7-mcp`
+ * (either `command: "npx", args: [..., "@upstash/context7-mcp", ...]` or
+ * OpenCode-style `command: ["npx", ..., "@upstash/context7-mcp", ...]`).
+ */
+export function isStdioContext7Entry(entry: unknown): entry is Record<string, unknown> {
+ if (!entry || typeof entry !== "object") return false;
+ const e = entry as Record<string, unknown>;
+ const refs = (s: unknown) => typeof s === "string" && s.includes(STDIO_PACKAGE);
+
+ if (Array.isArray(e.command)) {
+ return (e.command as unknown[]).some(refs);
+ }
+ if (typeof e.command === "string" && Array.isArray(e.args)) {
+ return (e.args as unknown[]).some(refs);
+ }
+ return false;
+}
+
+/**
+ * Extracts an existing per-server entry from an in-memory JSON config
+ * (e.g., the object returned by `readJsonConfig`). Returns `undefined`
+ * when the section, server, or entry shape is missing.
+ */
+export function getJsonServerEntry(
+ config: Record<string, unknown>,
+ configKey: string,
+ serverName: string
+): Record<string, unknown> | undefined {
+ const section = config[configKey];
+ if (!section || typeof section !== "object") return undefined;
+ const entry = (section as Record<string, unknown>)[serverName];
+ return entry && typeof entry === "object" ? (entry as Record<string, unknown>) : undefined;
+}
+
+function stripApiKeyPair(args: string[]): string[] {
+ const result: string[] = [];
+ for (let i = 0; i < args.length; i++) {
+ if (args[i] === "--api-key") {
+ i++; // skip the value too
+ continue;
+ }
+ result.push(args[i]);
+ }
+ return result;
+}
+
+/**
+ * Returns a copy of `entry` with any existing `--api-key <value>` pair
+ * removed from args (or array-form command), then a new `--api-key <apiKey>`
+ * appended when `apiKey` is provided. All other fields — including the
+ * package specifier (e.g., `@upstash/context7-mcp@latest`) — are preserved.
+ */
+export function patchStdioApiKey(
+ entry: Record<string, unknown>,
+ apiKey: string | undefined
+): Record<string, unknown> {
+ if (Array.isArray(entry.command)) {
+ const cmd = stripApiKeyPair(entry.command as string[]);
+ if (apiKey) cmd.push("--api-key", apiKey);
+ return { ...entry, command: cmd };
+ }
+ const args = Array.isArray(entry.args) ? stripApiKeyPair(entry.args as string[]) : [];
+ if (apiKey) args.push("--api-key", apiKey);
+ return { ...entry, args };
+}
+
export function buildTomlServerBlock(serverName: string, entry: Record<string, unknown>): string {
const lines: string[] = [`[mcp_servers.${serverName}]`];
const headers = entry.headers as Record<string, string> | undefined;
diff --git a/packages/mcp/src/index.ts b/packages/mcp/src/index.ts
index 125be614..77392b36 100644
--- a/packages/mcp/src/index.ts
+++ b/packages/mcp/src/index.ts
@@ -5,7 +5,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import type { Transport } from "@modelcontextprotocol/sdk/shared/transport.js";
import { z } from "zod";
import { searchLibraries, fetchLibraryContext } from "./lib/api.js";
-import { ClientContext } from "./lib/encryption.js";
+import type { ClientContext } from "./lib/types.js";
import { formatSearchResults, extractClientInfoFromUserAgent } from "./lib/utils.js";
import { isJWT, validateJWT } from "./lib/jwt.js";
import express from "express";
@@ -18,6 +18,7 @@ import {
AUTH_SERVER_URL,
OPENAI_APPS_CHALLENGE_TOKEN,
} from "./lib/constants.js";
+import { appendAuthPrompt } from "./lib/auth/auth-prompt.js";
/** Default HTTP server port */
const DEFAULT_PORT = 3000;
@@ -204,33 +205,29 @@ IMPORTANT: Do not call this tool more than 3 times per question. If you cannot f
idempotentHint: true,
},
},
- async ({ query, libraryName }) => {
- const searchResponse = await searchLibraries(query, libraryName, getClientContext());
+ async ({ query, libraryName }: { query: string; libraryName: string }) => {
+ const ctx = getClientContext();
+ const searchResponse = await searchLibraries(query, libraryName, ctx);
if (!searchResponse.results || searchResponse.results.length === 0) {
+ const text = searchResponse.error ?? "No libraries found matching the provided name.";
return {
content: [
{
type: "text",
- text: searchResponse.error
- ? searchResponse.error
- : "No libraries found matching the provided name.",
+ text: appendAuthPrompt(text, ctx),
},
],
};
}
const resultsText = formatSearchResults(searchResponse);
-
- const responseText = `Available Libraries:
-
-${resultsText}`;
-
+ const responseText = `Available Libraries:\n\n${resultsText}`;
return {
content: [
{
type: "text",
- text: responseText,
+ text: appendAuthPrompt(responseText, ctx),
},
],
};
@@ -265,14 +262,14 @@ Do not call this tool more than 3 times per question.`,
idempotentHint: true,
},
},
- async ({ query, libraryId }) => {
- const response = await fetchLibraryContext({ query, libraryId }, getClientContext());
-
+ async ({ query, libraryId }: { query: string; libraryId: string }) => {
+ const ctx = getClientContext();
+ const response = await fetchLibraryContext({ query, libraryId }, ctx);
return {
content: [
{
type: "text",
- text: response.data,
+ text: appendAuthPrompt(response.data, ctx),
},
],
};
diff --git a/packages/mcp/src/lib/api.ts b/packages/mcp/src/lib/api.ts
index 2ba6e2a6..6bcd4502 100644
--- a/packages/mcp/src/lib/api.ts
+++ b/packages/mcp/src/lib/api.ts
@@ -1,5 +1,5 @@
-import { SearchResponse, ContextRequest, ContextResponse } from "./types.js";
-import { ClientContext, generateHeaders } from "./encryption.js";
+import { SearchResponse, ContextRequest, ContextResponse, ClientContext } from "./types.js";
+import { generateHeaders } from "./encryption.js";
import { Agent, ProxyAgent, setGlobalDispatcher } from "undici";
import { CONTEXT7_API_BASE_URL } from "./constants.js";
import { readFileSync } from "fs";
@@ -94,6 +94,12 @@ if (PROXY_URL && !PROXY_URL.startsWith("$") && /^(http|https):\/\//i.test(PROXY_
}
}
+function readPromptSignal(response: Response, context: ClientContext): void {
+ if (response.headers.get("X-Context7-Auth-Prompt") === "1") {
+ context.shouldPrompt = true;
+ }
+}
+
/**
* Searches for libraries matching the given query
* @param query The user's question or task (used for LLM relevance ranking)
@@ -114,6 +120,7 @@ export async function searchLibraries(
const headers = generateHeaders(context);
const response = await fetch(url, { headers });
+ readPromptSignal(response, context);
if (!response.ok) {
const errorMessage = await parseErrorResponse(response, context.apiKey);
console.error(errorMessage);
@@ -146,6 +153,7 @@ export async function fetchLibraryContext(
const headers = generateHeaders(context);
const response = await fetch(url, { headers });
+ readPromptSignal(response, context);
if (!response.ok) {
const errorMessage = await parseErrorResponse(response, context.apiKey);
console.error(errorMessage);
diff --git a/packages/mcp/src/lib/auth/auth-prompt.ts b/packages/mcp/src/lib/auth/auth-prompt.ts
new file mode 100644
index 00000000..982e0268
--- /dev/null
+++ b/packages/mcp/src/lib/auth/auth-prompt.ts
@@ -0,0 +1,54 @@
+import type { ClientContext } from "../types.js";
+
+function clientFlagForCli(ide: string | undefined): string {
+ if (!ide) return "";
+ const lower = ide.toLowerCase();
+ if (lower.includes("cursor")) return "--cursor";
+ if (lower.includes("claude")) return "--claude";
+ if (lower.includes("codex")) return "--codex";
+ if (lower.includes("opencode")) return "--opencode";
+ if (lower.includes("gemini")) return "--gemini";
+ return "";
+}
+
+export interface BuildAuthPromptOptions {
+ clientIde?: string;
+ transport?: "stdio" | "http";
+}
+
+/**
+ * Appends a sign-in nudge to `text` when the backend has signaled (via
+ * `X-Context7-Auth-Prompt: 1`, captured on `ctx.shouldPrompt` in api.ts)
+ * that the anonymous caller should be prompted to authenticate. No-op for
+ * authenticated callers or when the signal wasn't set.
+ */
+export function appendAuthPrompt(text: string, ctx: ClientContext): string {
+ if (ctx.apiKey || !ctx.shouldPrompt) return text;
+ return `${text}\n\n${buildAuthPrompt({
+ clientIde: ctx.clientInfo?.ide,
+ transport: ctx.transport,
+ })}`;
+}
+
+export function buildAuthPrompt(opts: BuildAuthPromptOptions): string {
+ const flag = clientFlagForCli(opts.clientIde);
+ const transportFlag = opts.transport === "stdio" ? " --stdio" : "";
+ const command = flag
+ ? `npx ctx7 setup ${flag} --mcp${transportFlag} -y`
+ : `npx ctx7 setup --mcp${transportFlag}`;
+
+ return [
+ "---",
+ `**[Heads up] Notice for the user — please relay the following section to them and offer to run the command for them after their confirmation:**`,
+ "",
+ "> You're using Context7 anonymously. To sign in for **free** higher rate limits, run this in your terminal:",
+ ">",
+ "> ```",
+ `> ${command}`,
+ "> ```",
+ ">",
+ "> It opens the browser, completes sign-in, and writes credentials into your MCP client config. After it finishes, disable + re-enable the Context7 MCP server in your editor so the new credentials take effect.",
+ "",
+ `(Background for the assistant: this user is using Context7 anonymously. Surface the notice above to the user; with their permission, you may run \`${command}\` for them via your shell tool.)`,
+ ].join("\n");
+}
diff --git a/packages/mcp/src/lib/encryption.ts b/packages/mcp/src/lib/encryption.ts
index 119acaaa..f0b5d22e 100644
--- a/packages/mcp/src/lib/encryption.ts
+++ b/packages/mcp/src/lib/encryption.ts
@@ -1,5 +1,6 @@
import { createCipheriv, randomBytes } from "crypto";
import { SERVER_VERSION } from "./constants.js";
+import type { ClientContext } from "./types.js";
const DEFAULT_ENCRYPTION_KEY = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";
const ENCRYPTION_KEY = process.env.CLIENT_IP_ENCRYPTION_KEY || DEFAULT_ENCRYPTION_KEY;
@@ -28,16 +29,6 @@ function encryptClientIp(clientIp: string): string {
}
}
-export interface ClientContext {
- clientIp?: string;
- apiKey?: string;
- clientInfo?: {
- ide?: string;
- version?: string;
- };
- transport?: "stdio" | "http";
-}
-
/**
* Generate headers for Context7 API requests.
* Handles client IP encryption, authentication, and telemetry headers.
diff --git a/packages/mcp/src/lib/types.ts b/packages/mcp/src/lib/types.ts
index e25ae758..483dd6b7 100644
--- a/packages/mcp/src/lib/types.ts
+++ b/packages/mcp/src/lib/types.ts
@@ -31,3 +31,16 @@ export type ContextRequest = {
export type ContextResponse = {
data: string;
};
+
+export interface ClientContext {
+ clientIp?: string;
+ apiKey?: string;
+ clientInfo?: {
+ ide?: string;
+ version?: string;
+ };
+ transport?: "stdio" | "http";
+ /** Mutable: set by the upstream API layer when the backend signals the
+ * client should be prompted to sign in. Read by the auth-prompt wrapper. */
+ shouldPrompt?: boolean;
+}