Context7 Platform -- Up-to-date docs for AI agents
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { mkdir, readFile, rm, writeFile } from "fs/promises";
import { tmpdir } from "os";
import { join } from "path";
import { Command } from "commander";
import { DEFAULT_CONTEXT7_BASE_URL, setBaseUrl } from "../utils/api.js";
const promptMocks = vi.hoisted(() => ({
password: vi.fn(),
select: vi.fn(),
}));
vi.mock("@inquirer/prompts", () => promptMocks);
import { registerSetupCommand } from "../commands/setup.js";
let originalCwd: string;
let tempDir: string;
beforeEach(async () => {
process.exitCode = undefined;
originalCwd = process.cwd();
tempDir = join(tmpdir(), `ctx7-on-prem-setup-${Date.now()}`);
await mkdir(tempDir, { recursive: true });
process.chdir(tempDir);
vi.unstubAllEnvs();
promptMocks.password.mockReset();
promptMocks.select.mockReset();
vi.stubEnv("CTX7_TELEMETRY_DISABLED", "");
vi.stubEnv("CONTEXT7_API_KEY", "");
setBaseUrl("https://context7.internal.example");
vi.stubGlobal(
"fetch",
vi.fn(async (input: string | URL | Request) => {
const url = String(input);
if (url === "https://context7.internal.example/api/auth/mcp") {
return {
ok: true,
json: async () => ({ enabled: false }),
} as Response;
}
throw new Error(`Unexpected outbound request: ${url}`);
})
);
vi.spyOn(console, "log").mockImplementation(() => {});
vi.spyOn(console, "error").mockImplementation(() => {});
});
afterEach(async () => {
process.exitCode = undefined;
process.chdir(originalCwd);
setBaseUrl(DEFAULT_CONTEXT7_BASE_URL);
await rm(tempDir, { recursive: true, force: true });
vi.unstubAllGlobals();
vi.unstubAllEnvs();
vi.restoreAllMocks();
});
describe("on-premise setup network boundary", () => {
test("only contacts the configured deployment and uses bundled assets", async () => {
const program = new Command();
program.exitOverride();
registerSetupCommand(program);
await program.parseAsync([
"node",
"ctx7",
"setup",
"--mcp",
"--base-url",
"https://context7.internal.example",
"--codex",
"--project",
"--yes",
]);
expect(fetch).toHaveBeenCalledTimes(1);
expect(fetch).toHaveBeenCalledWith(
"https://context7.internal.example/api/auth/mcp",
expect.objectContaining({
headers: { Accept: "application/json" },
redirect: "manual",
})
);
const config = await readFile(join(tempDir, ".codex", "config.toml"), "utf-8");
expect(config).toContain('url = "https://context7.internal.example/mcp"');
expect(config).not.toContain("Authorization");
const skill = await readFile(
join(tempDir, ".agents", "skills", "context7-mcp", "SKILL.md"),
"utf-8"
);
expect(skill).toContain("name: context7-mcp");
expect(skill).toContain("resolve-library-id");
expect(await readFile(join(tempDir, "AGENTS.md"), "utf-8")).toContain("query-docs");
});
test("re-running setup replaces the AGENTS.md section without touching user content", async () => {
const agentsPath = join(tempDir, "AGENTS.md");
await writeFile(
agentsPath,
"# Before\n\n<!-- context7 -->\nstale rule\n<!-- context7 -->\n\n# After\n",
"utf-8"
);
const runSetup = async () => {
const program = new Command();
program.exitOverride();
registerSetupCommand(program);
await program.parseAsync([
"node",
"ctx7",
"setup",
"--mcp",
"--base-url",
"https://context7.internal.example",
"--codex",
"--project",
"--yes",
]);
return readFile(agentsPath, "utf-8");
};
const first = await runSetup();
expect(first.startsWith("# Before\n\n<!-- context7 -->\n")).toBe(true);
expect(first.endsWith("<!-- context7 -->\n\n# After\n")).toBe(true);
expect(first).not.toContain("stale rule");
expect(first).toContain("query-docs");
expect(await runSetup()).toBe(first);
});
test("selects MCP mode automatically for a custom deployment", async () => {
const program = new Command();
program.exitOverride();
registerSetupCommand(program);
await program.parseAsync([
"node",
"ctx7",
"setup",
"--base-url",
"https://context7.internal.example",
"--codex",
"--project",
]);
expect(promptMocks.select).not.toHaveBeenCalled();
expect(fetch).toHaveBeenCalledTimes(1);
expect(await readFile(join(tempDir, ".codex", "config.toml"), "utf-8")).toContain(
'url = "https://context7.internal.example/mcp"'
);
});
test("reports an invalid deployment URL without throwing", async () => {
const program = new Command();
program.exitOverride();
registerSetupCommand(program);
await expect(
program.parseAsync([
"node",
"ctx7",
"setup",
"--base-url",
"https://context7.internal.example/mcp",
"--codex",
"--project",
])
).resolves.toBe(program);
expect(process.exitCode).toBe(1);
expect(promptMocks.select).not.toHaveBeenCalled();
expect(fetch).not.toHaveBeenCalled();
expect(console.log).toHaveBeenCalledWith(
expect.stringContaining("Pass the Context7 deployment root")
);
});
test("prompts securely for an on-premise key when MCP auth is enabled", async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
json: async () => ({ enabled: true }),
} as Response);
promptMocks.password.mockResolvedValue(" ctx7op-preview_secret ");
const program = new Command();
program.exitOverride();
registerSetupCommand(program);
await program.parseAsync([
"node",
"ctx7",
"setup",
"--mcp",
"--base-url",
"https://context7.internal.example",
"--codex",
"--project",
]);
expect(promptMocks.password).toHaveBeenCalledWith(
expect.objectContaining({
message: "Personal API key (create one at https://context7.internal.example/account)",
mask: true,
validate: expect.any(Function),
})
);
const config = await readFile(join(tempDir, ".codex", "config.toml"), "utf-8");
expect(config).toContain('url = "https://context7.internal.example/mcp"');
expect(config).toContain('Authorization = "Bearer ctx7op-preview_secret"');
});
test("configures newly registered HTTP clients against the on-premise URL", async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
json: async () => ({ enabled: true }),
} as Response);
const program = new Command();
program.exitOverride();
registerSetupCommand(program);
await program.parseAsync([
"node",
"ctx7",
"setup",
"--mcp",
"--base-url",
"https://context7.internal.example",
"--vscode",
"--project",
"--yes",
"--api-key",
"ctx7op-preview_secret",
]);
const config = JSON.parse(await readFile(join(tempDir, ".vscode", "mcp.json"), "utf-8")) as {
servers: Record<string, unknown>;
};
expect(config.servers.context7).toEqual({
type: "http",
url: "https://context7.internal.example/mcp",
headers: { Authorization: "Bearer ctx7op-preview_secret" },
});
expect(
await readFile(join(tempDir, ".github", "instructions", "context7.instructions.md"), "utf-8")
).toContain('applyTo: "**"');
});
test("does not prompt during non-interactive --yes setup", async () => {
vi.mocked(fetch).mockResolvedValueOnce({
ok: true,
json: async () => ({ enabled: true }),
} as Response);
const program = new Command();
program.exitOverride();
registerSetupCommand(program);
await program.parseAsync([
"node",
"ctx7",
"setup",
"--mcp",
"--base-url",
"https://context7.internal.example",
"--codex",
"--project",
"--yes",
]);
expect(promptMocks.password).not.toHaveBeenCalled();
expect(process.exitCode).toBe(1);
await expect(readFile(join(tempDir, ".codex", "config.toml"), "utf-8")).rejects.toThrow();
});
test("returns a failure status when authentication discovery is unreachable", async () => {
vi.mocked(fetch).mockRejectedValueOnce(new Error("connection refused"));
const program = new Command();
program.exitOverride();
registerSetupCommand(program);
await program.parseAsync([
"node",
"ctx7",
"setup",
"--mcp",
"--base-url",
"https://context7.internal.example",
"--codex",
"--project",
"--yes",
]);
expect(process.exitCode).toBe(1);
await expect(readFile(join(tempDir, ".codex", "config.toml"), "utf-8")).rejects.toThrow();
});
});