Context7 Platform -- Up-to-date docs for AI agents
CTX7-1542: add uninstall command for Context7 setup (#2473)
Fahreddin Özcanf056b14cde2a
diff --git a/.changeset/fuzzy-seals-sneeze.md b/.changeset/fuzzy-seals-sneeze.mdnew file mode 100644index 00000000..819515db--- /dev/null+++ b/.changeset/fuzzy-seals-sneeze.md@@ -0,0 +1,5 @@+---+"ctx7": patch+---++Add `ctx7 remove` as the cleanup counterpart to `ctx7 setup`, with safer detection and removal behavior. The command now prompts only for agents with actual Context7 artifacts, preserves non-Context7 MCP configuration when removing entries, and includes stronger test coverage for JSON and TOML cleanup.diff --git a/README.md b/README.mdindex 9a195325..442058d2 100644--- a/README.md+++ b/README.md@@ -54,6 +54,8 @@ npx ctx7 setupAuthenticates via OAuth, generates an API key, and installs the appropriate skill. You can choose between CLI + Skills or MCP mode. Use `--cursor`, `--claude`, or `--opencode` to target a specific agent.+To remove the generated setup later, run `npx ctx7 remove`. If you globally installed the CLI with `npm install -g ctx7`, remove that package separately with `npm uninstall -g ctx7`.+To configure manually, use the Context7 server URL `https://mcp.context7.com/mcp` with your MCP client and pass your API key via the `CONTEXT7_API_KEY` header. See the link below for client-specific setup instructions.**[Manual Installation / Other Clients →](https://context7.com/docs/resources/all-clients)**diff --git a/docs/clients/cli.mdx b/docs/clients/cli.mdxindex e96985b6..0fc373c5 100644--- a/docs/clients/cli.mdx+++ b/docs/clients/cli.mdx@@ -23,6 +23,7 @@ Requires Node.js 18 or later.npx ctx7 --helpnpx ctx7 library react```+</Tab><Tab title="Global install">Install globally for faster access — no `npx` prefix needed on every command.@@ -33,6 +34,7 @@ Requires Node.js 18 or later.# Verify installationctx7 --version```+</Tab></Tabs>@@ -54,13 +56,13 @@ ctx7 library prisma "How to define one-to-many relations with cascade delete"Each result includes:-| Field | Description |-|-------|-------------|-| **Library ID** | The identifier to pass to `ctx7 docs` (format: `/org/project`) |-| **Code Snippets** | Number of indexed code examples — higher means more documentation coverage |-| **Source Reputation** | Authority indicator: High, Medium, Low, or Unknown |-| **Benchmark Score** | Quality score from 0 to 100 |-| **Versions** | Version-specific IDs when available (format: `/org/project/version`) |+| Field | Description |+| --------------------- | -------------------------------------------------------------------------- |+| **Library ID** | The identifier to pass to `ctx7 docs` (format: `/org/project`) |+| **Code Snippets** | Number of indexed code examples — higher means more documentation coverage |+| **Source Reputation** | Authority indicator: High, Medium, Low, or Unknown |+| **Benchmark Score** | Quality score from 0 to 100 |+| **Versions** | Version-specific IDs when available (format: `/org/project/version`) |When multiple results come back, the best match is usually the one with the closest name, highest snippet count, and strongest reputation. If you need docs for a specific version, pick the matching version ID from the list.@@ -83,7 +85,8 @@ ctx7 docs /prisma/prisma "How to define one-to-many relations with cascade delet```<Note>-Library IDs always start with `/`. Running `ctx7 docs react "hooks"` will fail — always use the full ID returned by `ctx7 library` in Step 1.+ Library IDs always start with `/`. Running `ctx7 docs react "hooks"` will fail — always use the+ full ID returned by `ctx7 library` in Step 1.</Note>Queries work best when they're specific. Describe what you're trying to accomplish rather than using single keywords — `"How to set up authentication with JWT in Express.js"` returns much better results than `"auth"`.@@ -150,18 +153,40 @@ Without `--api-key` or `--oauth`, setup opens a browser for OAuth login. MCP mod**What gets written — MCP mode:**-| File | Purpose |-|------|---------|-| `.mcp.json` / `.cursor/mcp.json` / `.opencode.json` | MCP server entry |-| Agent rules directory | Rule file — instructs the agent to use Context7 for library docs |-| Agent skills directory | `context7-mcp` skill |+| File | Purpose |+| --------------------------------------------------- | ---------------------------------------------------------------- |+| `.mcp.json` / `.cursor/mcp.json` / `.opencode.json` | MCP server entry |+| Agent rules directory | Rule file — instructs the agent to use Context7 for library docs |+| Agent skills directory | `context7-mcp` skill |**What gets written — CLI + Skills mode:**-| File | Purpose |-|------|---------|+| File | Purpose |+| ---------------------- | ------------------------------------------------------------------------------ || Agent skills directory | `docs` skill — guides the agent to use `ctx7 library` and `ctx7 docs` commands |+### ctx7 remove++Remove the setup written by `ctx7 setup`. By default this removes both MCP setup and CLI setup for the selected agent.++```bash+# Interactive+ctx7 remove++# Target specific agents+ctx7 remove --cursor+ctx7 remove --claude --project++# Remove both setup modes explicitly+ctx7 remove --cursor --all++# Remove only one setup mode+ctx7 remove --cursor --cli+ctx7 remove --claude --mcp+```++If you installed the CLI itself with `npm install -g ctx7`, remove that separately with `npm uninstall -g ctx7`. If you run Context7 with `npx ctx7`, there is no permanent CLI install to remove.+---## Authentication@@ -194,12 +219,12 @@ export CONTEXT7_API_KEY=your_key### When is authentication required?-| Feature | Required |-|---------|----------|-| `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` is passed (`--oauth` also skips login for MCP mode) |+| Feature | Required |+| -------------------------------------------------------- | ---------------------------------------------------------------------------- |+| `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` is passed (`--oauth` also skips login for MCP mode) |---@@ -242,7 +267,8 @@ ctx7 skills install /anthropics/skills pdf --global --all-agents --yes```<Note>-When installing to multiple clients, the skill files are created in your primary client's directory and symlinked to the others.+ When installing to multiple clients, the skill files are created in your primary client's+ directory and symlinked to the others.</Note>Alias: `ctx7 si /anthropics/skills pdf`@@ -304,7 +330,8 @@ ctx7 skills generate --global5. Choose where to install it<Tip>-Describe best practices and constraints, not step-by-step tutorials. "TypeScript strict mode patterns" generates a more useful skill than "how to write TypeScript."+ Describe best practices and constraints, not step-by-step tutorials. "TypeScript strict mode+ patterns" generates a more useful skill than "how to write TypeScript."</Tip>**Weekly limits:** Free accounts get 6 generations/week, Pro accounts get 10.@@ -346,17 +373,17 @@ Aliases: `ctx7 skills rm`, `ctx7 skills delete`## Shortcuts-| Shortcut | Full command |-|----------|-------------|-| `ctx7 si` | `ctx7 skills install` |-| `ctx7 ss` | `ctx7 skills search` |-| `ctx7 ssg` | `ctx7 skills suggest` |-| `ctx7 skills i` | `ctx7 skills install` |-| `ctx7 skills s` | `ctx7 skills search` |-| `ctx7 skills ls` | `ctx7 skills list` |-| `ctx7 skills rm` | `ctx7 skills remove` |+| Shortcut | Full command |+| ----------------- | ---------------------- |+| `ctx7 si` | `ctx7 skills install` |+| `ctx7 ss` | `ctx7 skills search` |+| `ctx7 ssg` | `ctx7 skills suggest` |+| `ctx7 skills i` | `ctx7 skills install` |+| `ctx7 skills s` | `ctx7 skills search` |+| `ctx7 skills ls` | `ctx7 skills list` |+| `ctx7 skills rm` | `ctx7 skills remove` || `ctx7 skills gen` | `ctx7 skills generate` |-| `ctx7 skills g` | `ctx7 skills generate` |+| `ctx7 skills g` | `ctx7 skills generate` |---diff --git a/docs/resources/all-clients.mdx b/docs/resources/all-clients.mdxindex 67b04256..0df2e9ea 100644--- a/docs/resources/all-clients.mdx+++ b/docs/resources/all-clients.mdx@@ -3,16 +3,18 @@ title: MCP Clientsdescription: Installation examples for MCP clients----Context7 supports all MCP clients. Below are configuration examples for popular clients. If your client isn't listed, check its documentation for MCP server installation. To configure manually, use the Context7 server URL `https://mcp.context7.com/mcp`. You can add a `CONTEXT7_API_KEY` header for authenticated usage and higher rate limits.+Context7 supports all MCP clients. Below are configuration examples for popular clients. If your client isn't listed, check its documentation for MCP server installation. To configure manually, use the Context7 server URL `https://mcp.context7.com/mcp` with your MCP client and pass your API key via the `CONTEXT7_API_KEY` header.<Tip>-Looking for the easiest way to get started? Use `npx ctx7 setup` to configure Context7 automatically. See the [CLI docs](/clients/cli) for more details.+ Looking for the easiest way to get started? Use `npx ctx7 setup` to configure Context7+ automatically, and `npx ctx7 remove` to remove the generated setup later. See the [CLI+ docs](/clients/cli) for more details.</Tip><Note>-For detailed guides including rules, skills, agents, and best practices, see the dedicated client pages:-- [Cursor](/clients/cursor) - Rules setup, Composer integration, tips-- [Claude Code](/clients/claude-code) - Skills, agents, commands, plugin installation+ For detailed guides including rules, skills, agents, and best practices, see+ [Cursor](/clients/cursor) for rules and Composer integration tips, and [Claude+ Code](/clients/claude-code) for skills, agents, commands, and plugin installation.</Note>## OAuth Authentication@@ -154,9 +156,7 @@ url = "https://mcp.context7.com/mcp"http_headers = { "CONTEXT7_API_KEY" = "YOUR_API_KEY" }```-<Note>-If you see startup timeout errors, try increasing `startup_timeout_sec` to `40`.-</Note>+<Note>If you see startup timeout errors, try increasing `startup_timeout_sec` to `40`.</Note></Accordion>@@ -437,7 +437,7 @@ Fill in the following:| ------------------ | ------------------------------------------------------------------------------------------- || **Name** | `Context7` || **Description** | `Fetch up-to-date documentation and code examples for any library directly from the source` |-| **MCP Server URL** | `https://mcp.context7.com/mcp/oauth` |+| **MCP Server URL** | `https://mcp.context7.com/mcp/oauth` |> Accept the security notice and complete the one-time OAuth authorization.@@ -469,7 +469,7 @@ Fill in the following:| ------------------ | ------------------------------------------------------------------------------------------- || **Name** | `Context7` || **Description** | `Fetch up-to-date documentation and code examples for any library directly from the source` |-| **MCP Server URL** | `https://mcp.context7.com/mcp/oauth` |+| **MCP Server URL** | `https://mcp.context7.com/mcp/oauth` |> Accept the security notice and complete the one-time OAuth authorization.@@ -902,6 +902,7 @@ See [Qwen Code MCP Configuration](https://qwenlm.github.io/qwen-code-docs/en/useBy default, configurations are saved to the project scope (`.qwen/settings.json`). Use the `--scope user` flag to save to the user scope (`~/.qwen/settings.json`) instead.#### Remote Server Connection+```shqwen mcp add --transport http context7 https://mcp.context7.com/mcp \--header "CONTEXT7_API_KEY: YOUR_API_KEY" \@@ -909,6 +910,7 @@ qwen mcp add --transport http context7 https://mcp.context7.com/mcp \```#### Local Server Connection+```shqwen mcp add context7 npx -y @upstash/context7-mcp --api-key YOUR_API_KEY```@@ -919,6 +921,7 @@ qwen mcp add context7 npx -y @upstash/context7-mcp --api-key YOUR_API_KEY2. Add the following to the `mcpServers` object:#### Remote Server Connection+```json{"mcpServers": {@@ -934,6 +937,7 @@ qwen mcp add context7 npx -y @upstash/context7-mcp --api-key YOUR_API_KEY```#### Local Server Connection+```json{"mcpServers": {diff --git a/packages/cli/README.md b/packages/cli/README.mdindex 2f724b97..eae78084 100644--- a/packages/cli/README.md+++ b/packages/cli/README.md@@ -20,6 +20,9 @@ npm install -g ctx7# Set up Context7 MCP for your coding agentsctx7 setup+# Remove Context7 setup later+ctx7 remove+# Target a specific agentctx7 setup --cursorctx7 setup --claude@@ -108,6 +111,28 @@ ctx7 setup --projectctx7 setup --yes```+### Uninstall setup++Remove the Context7 setup written by `ctx7 setup`. By default this removes both MCP setup and CLI setup for the selected agent.++```bash+# Interactive+ctx7 remove++# Target specific agents+ctx7 remove --cursor+ctx7 remove --claude --project++# Remove both setup modes explicitly+ctx7 remove --cursor --all++# Remove only one setup mode+ctx7 remove --cursor --cli+ctx7 remove --claude --mcp+```++If you installed the CLI itself globally with `npm install -g ctx7`, remove that separately with `npm uninstall -g ctx7`. If you use `npx ctx7`, there is no permanent CLI install to remove.+### Generate skillsGenerate custom skills tailored to your use case using AI. Requires authentication.@@ -230,12 +255,12 @@ ctx7 skills remove pdf --globalThe CLI automatically detects which AI coding assistants you have installed and offers to install skills for them:-| Client | Skills Directory |-|--------|-----------------|+| Client | Skills Directory |+| ------------------------------------------------------------------- | ----------------- || Universal (Amp, Codex, Gemini CLI, GitHub Copilot, OpenCode + more) | `.agents/skills/` |-| Claude Code | `.claude/skills/` |-| Cursor | `.cursor/skills/` |-| Antigravity | `.agent/skills/` |+| Claude Code | `.claude/skills/` |+| Cursor | `.cursor/skills/` |+| Antigravity | `.agent/skills/` |## Shortcutsdiff --git a/packages/cli/src/__tests__/remove.test.ts b/packages/cli/src/__tests__/remove.test.tsnew file mode 100644index 00000000..59d7f85f--- /dev/null+++ b/packages/cli/src/__tests__/remove.test.ts@@ -0,0 +1,357 @@+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";+import { Command } from "commander";+import { mkdir, readFile, writeFile, rm, access } from "fs/promises";+import { join } from "path";+import { tmpdir } from "os";++const trackEvent = vi.fn();+const mockCheckboxWithHover = vi.fn();+let logOutput: string[];++vi.mock("../utils/tracking.js", () => ({+ trackEvent: (...args: unknown[]) => trackEvent(...args),+}));++vi.mock("../utils/prompts.js", () => ({+ checkboxWithHover: (...args: unknown[]) => mockCheckboxWithHover(...args),+}));++const mockSpinner = {+ start: vi.fn().mockReturnThis(),+ stop: vi.fn().mockReturnThis(),+ succeed: vi.fn().mockReturnThis(),+ fail: vi.fn().mockReturnThis(),+ text: "",+};+vi.mock("ora", () => ({ default: () => mockSpinner }));++import { registerRemoveCommand } from "../commands/remove.js";++let tempDir: string;+let originalCwd: string;++async function exists(path: string): Promise<boolean> {+ try {+ await access(path);+ return true;+ } catch {+ return false;+ }+}++async function runCommand(...args: string[]): Promise<void> {+ const program = new Command();+ program.exitOverride();+ registerRemoveCommand(program);+ await program.parseAsync(["node", "test", ...args]);+}++beforeEach(async () => {+ vi.clearAllMocks();+ logOutput = [];+ vi.spyOn(console, "log").mockImplementation((...args: unknown[]) => {+ logOutput.push(args.join(" "));+ });+ vi.spyOn(console, "error").mockImplementation(() => {});+ originalCwd = process.cwd();+ tempDir = join(tmpdir(), `ctx7-uninstall-${Date.now()}`);+ await mkdir(tempDir, { recursive: true });+ process.chdir(tempDir);+});++afterEach(async () => {+ process.chdir(originalCwd);+ await rm(tempDir, { recursive: true, force: true });+ vi.restoreAllMocks();+});++describe("remove command", () => {+ test("removes only CLI artifacts for cursor project setup", async () => {+ const rulePath = join(tempDir, ".cursor", "rules", "context7.mdc");+ const cliSkillPath = join(tempDir, ".cursor", "skills", "find-docs", "SKILL.md");+ const mcpSkillPath = join(tempDir, ".cursor", "skills", "context7-mcp", "SKILL.md");++ await mkdir(join(tempDir, ".cursor", "rules"), { recursive: true });+ await mkdir(join(tempDir, ".cursor", "skills", "find-docs"), { recursive: true });+ await mkdir(join(tempDir, ".cursor", "skills", "context7-mcp"), { recursive: true });+ await writeFile(rulePath, "cursor rule", "utf-8");+ await writeFile(cliSkillPath, "find docs", "utf-8");+ await writeFile(mcpSkillPath, "mcp skill", "utf-8");++ await runCommand("remove", "--cursor", "--cli", "--project");++ expect(await exists(rulePath)).toBe(false);+ expect(await exists(join(tempDir, ".cursor", "skills", "find-docs"))).toBe(false);+ expect(await exists(mcpSkillPath)).toBe(true);+ expect(trackEvent).toHaveBeenCalledWith("command", { name: "remove" });+ expect(trackEvent).toHaveBeenCalledWith("remove", {+ agents: ["cursor"],+ scope: "project",+ modes: ["cli"],+ });+ });++ test("removes only MCP artifacts for codex project setup", async () => {+ const agentsPath = join(tempDir, "AGENTS.md");+ const tomlPath = join(tempDir, ".codex", "config.toml");+ const mcpSkillPath = join(tempDir, ".agents", "skills", "context7-mcp", "SKILL.md");+ const cliSkillPath = join(tempDir, ".agents", "skills", "find-docs", "SKILL.md");++ await mkdir(join(tempDir, ".codex"), { recursive: true });+ await mkdir(join(tempDir, ".agents", "skills", "context7-mcp"), { recursive: true });+ await mkdir(join(tempDir, ".agents", "skills", "find-docs"), { recursive: true });+ await writeFile(+ agentsPath,+ "# Before\n\n<!-- context7 -->\nrule body\n<!-- context7 -->\n",+ "utf-8"+ );+ await writeFile(+ tomlPath,+ 'model = "gpt-5"\n\n[mcp_servers.context7]\nurl = "https://mcp.context7.com/mcp"\n\n[mcp_servers.other]\nurl = "https://other.com"\n',+ "utf-8"+ );+ await writeFile(mcpSkillPath, "mcp skill", "utf-8");+ await writeFile(cliSkillPath, "find docs", "utf-8");++ await runCommand("remove", "--codex", "--mcp", "--project");++ const agentsContent = await readFile(agentsPath, "utf-8");+ const tomlContent = await readFile(tomlPath, "utf-8");++ expect(agentsContent).not.toContain("<!-- context7 -->");+ expect(tomlContent).toContain("[mcp_servers.other]");+ expect(tomlContent).not.toContain("[mcp_servers.context7]");+ expect(await exists(join(tempDir, ".agents", "skills", "context7-mcp"))).toBe(false);+ expect(await exists(cliSkillPath)).toBe(true);+ expect(trackEvent).toHaveBeenCalledWith("remove", {+ agents: ["codex"],+ scope: "project",+ modes: ["mcp"],+ });+ });++ test("supports uninstall alias and --all to remove both setup modes", async () => {+ const agentsPath = join(tempDir, "AGENTS.md");+ const tomlPath = join(tempDir, ".codex", "config.toml");+ const mcpSkillPath = join(tempDir, ".agents", "skills", "context7-mcp", "SKILL.md");+ const cliSkillPath = join(tempDir, ".agents", "skills", "find-docs", "SKILL.md");++ await mkdir(join(tempDir, ".codex"), { recursive: true });+ await mkdir(join(tempDir, ".agents", "skills", "context7-mcp"), { recursive: true });+ await mkdir(join(tempDir, ".agents", "skills", "find-docs"), { recursive: true });+ await writeFile(+ agentsPath,+ "# Before\n\n<!-- context7 -->\nrule body\n<!-- context7 -->\n",+ "utf-8"+ );+ await writeFile(+ tomlPath,+ '[mcp_servers.context7]\nurl = "https://mcp.context7.com/mcp"\n',+ "utf-8"+ );+ await writeFile(mcpSkillPath, "mcp skill", "utf-8");+ await writeFile(cliSkillPath, "find docs", "utf-8");++ await runCommand("uninstall", "--codex", "--all", "--project");++ const agentsContent = await readFile(agentsPath, "utf-8");+ expect(agentsContent).not.toContain("<!-- context7 -->");+ expect(await exists(join(tempDir, ".agents", "skills", "context7-mcp"))).toBe(false);+ expect(await exists(join(tempDir, ".agents", "skills", "find-docs"))).toBe(false);+ expect(await readFile(tomlPath, "utf-8")).not.toContain("[mcp_servers.context7]");+ expect(trackEvent).toHaveBeenCalledWith("remove", {+ agents: ["codex"],+ scope: "project",+ modes: ["mcp", "cli"],+ });+ });++ test("skips mode prompt when only one setup mode exists", async () => {+ const rulePath = join(tempDir, ".cursor", "rules", "context7.mdc");+ const cliSkillPath = join(tempDir, ".cursor", "skills", "find-docs", "SKILL.md");+ const mcpSkillPath = join(tempDir, ".cursor", "skills", "context7-mcp", "SKILL.md");++ await mkdir(join(tempDir, ".cursor", "rules"), { recursive: true });+ await mkdir(join(tempDir, ".cursor", "skills", "find-docs"), { recursive: true });+ await mkdir(join(tempDir, ".cursor", "skills", "context7-mcp"), { recursive: true });+ await writeFile(rulePath, "cursor rule", "utf-8");+ await writeFile(cliSkillPath, "find docs", "utf-8");+ await writeFile(mcpSkillPath, "mcp skill", "utf-8");++ await rm(join(tempDir, ".cursor", "skills", "context7-mcp"), { recursive: true });++ await runCommand("remove", "--cursor", "--project");++ expect(mockCheckboxWithHover).not.toHaveBeenCalled();+ expect(await exists(rulePath)).toBe(false);+ expect(await exists(join(tempDir, ".cursor", "skills", "find-docs"))).toBe(false);+ expect(await exists(mcpSkillPath)).toBe(false);+ expect(trackEvent).toHaveBeenCalledWith("remove", {+ agents: ["cursor"],+ scope: "project",+ modes: ["cli"],+ });+ });++ test("prompts for setup mode when both MCP and CLI artifacts exist", async () => {+ const agentsPath = join(tempDir, "AGENTS.md");+ const tomlPath = join(tempDir, ".codex", "config.toml");+ const mcpSkillPath = join(tempDir, ".agents", "skills", "context7-mcp", "SKILL.md");+ const cliSkillPath = join(tempDir, ".agents", "skills", "find-docs", "SKILL.md");++ await mkdir(join(tempDir, ".codex"), { recursive: true });+ await mkdir(join(tempDir, ".agents", "skills", "context7-mcp"), { recursive: true });+ await mkdir(join(tempDir, ".agents", "skills", "find-docs"), { recursive: true });+ await writeFile(+ agentsPath,+ "# Before\n\n<!-- context7 -->\nrule body\n<!-- context7 -->\n",+ "utf-8"+ );+ await writeFile(+ tomlPath,+ '[mcp_servers.context7]\nurl = "https://mcp.context7.com/mcp"\n',+ "utf-8"+ );+ await writeFile(mcpSkillPath, "mcp skill", "utf-8");+ await writeFile(cliSkillPath, "find docs", "utf-8");+ mockCheckboxWithHover.mockResolvedValueOnce(["cli"]);++ await runCommand("remove", "--codex", "--project");++ expect(mockCheckboxWithHover).toHaveBeenCalledTimes(1);+ expect(mockCheckboxWithHover.mock.calls[0]?.[0]).toMatchObject({+ message: "Which Context7 setup modes do you want to remove?",+ });+ expect(await exists(join(tempDir, ".agents", "skills", "find-docs"))).toBe(false);+ expect(await exists(mcpSkillPath)).toBe(true);+ expect(await readFile(tomlPath, "utf-8")).toContain("[mcp_servers.context7]");+ expect(trackEvent).toHaveBeenCalledWith("remove", {+ agents: ["codex"],+ scope: "project",+ modes: ["cli"],+ });+ });++ test("does not log not found items when other artifacts were removed", async () => {+ const agentsPath = join(tempDir, "AGENTS.md");+ const tomlPath = join(tempDir, ".codex", "config.toml");+ const mcpSkillPath = join(tempDir, ".agents", "skills", "context7-mcp", "SKILL.md");++ await mkdir(join(tempDir, ".codex"), { recursive: true });+ await mkdir(join(tempDir, ".agents", "skills", "context7-mcp"), { recursive: true });+ await writeFile(+ agentsPath,+ "# Before\n\n<!-- context7 -->\nrule body\n<!-- context7 -->\n",+ "utf-8"+ );+ await writeFile(+ tomlPath,+ '[mcp_servers.context7]\nurl = "https://mcp.context7.com/mcp"\n',+ "utf-8"+ );+ await writeFile(mcpSkillPath, "mcp skill", "utf-8");++ await runCommand("remove", "--codex", "--all", "--project");++ expect(logOutput.some((line) => line.includes("MCP config removed"))).toBe(true);+ expect(logOutput.some((line) => line.includes("Rule removed"))).toBe(true);+ expect(logOutput.some((line) => line.includes("Skill context7-mcp removed"))).toBe(true);+ expect(logOutput.some((line) => line.includes("not found"))).toBe(false);+ });++ test("removes only context7 from cursor JSON MCP config", async () => {+ const mcpPath = join(tempDir, ".cursor", "mcp.json");++ await mkdir(join(tempDir, ".cursor"), { recursive: true });+ await writeFile(+ mcpPath,+ JSON.stringify(+ {+ theme: "dark",+ mcpServers: {+ alpha: { url: "https://alpha.com" },+ context7: { url: "https://mcp.context7.com/mcp" },+ omega: { url: "https://omega.com" },+ },+ telemetry: { enabled: true },+ },+ null,+ 2+ ),+ "utf-8"+ );++ await runCommand("remove", "--cursor", "--mcp", "--project");++ expect(JSON.parse(await readFile(mcpPath, "utf-8"))).toEqual({+ theme: "dark",+ mcpServers: {+ alpha: { url: "https://alpha.com" },+ omega: { url: "https://omega.com" },+ },+ telemetry: { enabled: true },+ });+ });++ test("removes only context7 from opencode JSONC MCP config", async () => {+ const configPath = join(tempDir, "opencode.jsonc");++ await writeFile(+ configPath,+ `{+ // keep this file functional after removing Context7+ "theme": "night",+ "mcp": {+ "alpha": { "type": "remote", "url": "https://alpha.com", "enabled": true },+ "context7": { "type": "remote", "url": "https://mcp.context7.com/mcp", "enabled": true },+ "omega": { "type": "remote", "url": "https://omega.com", "enabled": false }+ },+ "telemetry": { "enabled": true }+}+`,+ "utf-8"+ );++ await runCommand("remove", "--opencode", "--mcp", "--project");++ expect(JSON.parse(await readFile(configPath, "utf-8"))).toEqual({+ theme: "night",+ mcp: {+ alpha: { type: "remote", url: "https://alpha.com", enabled: true },+ omega: { type: "remote", url: "https://omega.com", enabled: false },+ },+ telemetry: { enabled: true },+ });+ });++ test("detects only agents with Context7 artifacts, not just agent folders", async () => {+ const rulePath = join(tempDir, ".cursor", "rules", "context7.mdc");+ const cliSkillPath = join(tempDir, ".cursor", "skills", "find-docs", "SKILL.md");++ await mkdir(join(tempDir, ".cursor", "rules"), { recursive: true });+ await mkdir(join(tempDir, ".cursor", "skills", "find-docs"), { recursive: true });+ await mkdir(join(tempDir, ".gemini"), { recursive: true });+ await writeFile(rulePath, "cursor rule", "utf-8");+ await writeFile(cliSkillPath, "find docs", "utf-8");+ mockCheckboxWithHover.mockResolvedValueOnce(["cursor"]);++ await runCommand("remove", "--project");++ expect(logOutput.some((line) => line.includes("Detected: Cursor"))).toBe(true);+ expect(logOutput.some((line) => line.includes("Gemini CLI"))).toBe(false);+ expect(mockCheckboxWithHover.mock.calls[0]?.[0]).toMatchObject({+ message: "Which agents do you want to remove Context7 setup from?",+ choices: [{ name: "Cursor", value: "cursor" }],+ });+ });++ test("does not prompt when no Context7 setup is detected", async () => {+ await mkdir(join(tempDir, ".gemini"), { recursive: true });+ await writeFile(join(tempDir, ".gemini", "settings.json"), "{}", "utf-8");++ await runCommand("remove", "--project");++ expect(mockCheckboxWithHover).not.toHaveBeenCalled();+ expect(logOutput.some((line) => line.includes("No Context7 setup detected"))).toBe(true);+ });+});diff --git a/packages/cli/src/__tests__/setup.test.ts b/packages/cli/src/__tests__/setup.test.tsindex a2fe27af..22e725d5 100644--- a/packages/cli/src/__tests__/setup.test.ts+++ b/packages/cli/src/__tests__/setup.test.ts@@ -22,11 +22,13 @@ vi.stubGlobal(import { getRuleContent } from "../setup/templates.js";import {mergeServerEntry,+ removeServerEntry,readJsonConfig,writeJsonConfig,readTomlServerExists,buildTomlServerBlock,appendTomlServer,+ removeTomlServer,resolveMcpPath,} from "../setup/mcp-writer.js";import { getAgent, ALL_AGENT_NAMES, type AuthOptions } from "../setup/agents.js";@@ -151,6 +153,78 @@ describe("mergeServerEntry", () => {});});+describe("removeServerEntry", () => {+ test("removes server from config section", () => {+ const { config, removed } = removeServerEntry(+ {+ mcpServers: {+ context7: { url: "https://mcp.context7.com/mcp" },+ other: { url: "https://other.com" },+ },+ },+ "mcpServers",+ "context7"+ );++ expect(removed).toBe(true);+ expect(config).toEqual({+ mcpServers: {+ other: { url: "https://other.com" },+ },+ });+ });++ test("removes empty config section when context7 is the only server", () => {+ const { config, removed } = removeServerEntry(+ {+ mcpServers: {+ context7: { url: "https://mcp.context7.com/mcp" },+ },+ theme: "dark",+ },+ "mcpServers",+ "context7"+ );++ expect(removed).toBe(true);+ expect(config).toEqual({ theme: "dark" });+ });++ test("returns original config when server is not present", () => {+ const existing = { mcpServers: { other: { url: "https://other.com" } } };+ const { config, removed } = removeServerEntry(existing, "mcpServers", "context7");++ expect(removed).toBe(false);+ expect(config).toEqual(existing);+ });++ test("preserves unrelated top-level fields and sibling MCP servers", () => {+ const existing = {+ version: 2,+ theme: "dark",+ mcpServers: {+ alpha: { url: "https://alpha.com" },+ context7: { url: "https://mcp.context7.com/mcp", headers: { key: "secret" } },+ omega: { url: "https://omega.com" },+ },+ telemetry: { enabled: true },+ };++ const { config, removed } = removeServerEntry(existing, "mcpServers", "context7");++ expect(removed).toBe(true);+ expect(config).toEqual({+ version: 2,+ theme: "dark",+ mcpServers: {+ alpha: { url: "https://alpha.com" },+ omega: { url: "https://omega.com" },+ },+ telemetry: { enabled: true },+ });+ });+});+describe("readJsonConfig / writeJsonConfig", () => {let tempDir: string;@@ -390,6 +464,71 @@ describe("TOML config", () => {expect(content).toContain("[mcp_servers.other]");expect(content).not.toContain("\n\n\n");});++ test("removeTomlServer removes only the target server", async () => {+ const path = join(tempDir, "config.toml");+ await writeFile(+ path,+ 'model = "gpt-5"\n\n[mcp_servers.context7]\nurl = "https://mcp.context7.com/mcp"\n\n[mcp_servers.other]\nurl = "https://other.com"\n',+ "utf-8"+ );++ const { removed } = await removeTomlServer(path, "context7");+ expect(removed).toBe(true);++ const content = await readFile(path, "utf-8");+ expect(content).toContain('model = "gpt-5"');+ expect(content).toContain("[mcp_servers.other]");+ expect(content).toContain('url = "https://other.com"');+ expect(content).not.toContain("[mcp_servers.context7]");+ });++ test("removeTomlServer removes nested subsections too", async () => {+ const path = join(tempDir, "config.toml");+ await writeFile(+ path,+ '[mcp_servers.context7]\nurl = "https://mcp.context7.com/mcp"\n\n[mcp_servers.context7.http_headers]\nCONTEXT7_API_KEY = "sk-test"\n\n[settings]\nmodel = "gpt-5"\n',+ "utf-8"+ );++ const { removed } = await removeTomlServer(path, "context7");+ expect(removed).toBe(true);++ const content = await readFile(path, "utf-8");+ expect(content).toContain("[settings]");+ expect(content).toContain('model = "gpt-5"');+ expect(content).not.toContain("[mcp_servers.context7]");+ expect(content).not.toContain("CONTEXT7_API_KEY");+ });++ test("removeTomlServer preserves other MCP servers and their subsections", async () => {+ const path = join(tempDir, "config.toml");+ await writeFile(+ path,+ '[mcp_servers.context7]\nurl = "https://mcp.context7.com/mcp"\n\n[mcp_servers.context7.http_headers]\nCONTEXT7_API_KEY = "sk-test"\n\n[mcp_servers.other]\nurl = "https://other.com"\n\n[mcp_servers.other.http_headers]\nX_API_KEY = "keep-me"\n\n[settings]\nmodel = "gpt-5"\n',+ "utf-8"+ );++ const { removed } = await removeTomlServer(path, "context7");+ const content = await readFile(path, "utf-8");++ expect(removed).toBe(true);+ expect(content).toContain("[mcp_servers.other]");+ expect(content).toContain('url = "https://other.com"');+ expect(content).toContain("[mcp_servers.other.http_headers]");+ expect(content).toContain('X_API_KEY = "keep-me"');+ expect(content).toContain("[settings]");+ expect(content).not.toContain("[mcp_servers.context7]");+ expect(content).not.toContain("[mcp_servers.context7.http_headers]");+ });++ test("removeTomlServer returns false when server is missing", async () => {+ const path = join(tempDir, "config.toml");+ await writeFile(path, '[mcp_servers.other]\nurl = "https://other.com"\n', "utf-8");++ const { removed } = await removeTomlServer(path, "context7");+ expect(removed).toBe(false);+ });});describe("AGENTS.md append", () => {diff --git a/packages/cli/src/commands/remove.ts b/packages/cli/src/commands/remove.tsnew file mode 100644index 00000000..5ec08990--- /dev/null+++ b/packages/cli/src/commands/remove.ts@@ -0,0 +1,510 @@+import { Command } from "commander";+import pc from "picocolors";+import ora from "ora";+import { checkboxWithHover } from "../utils/prompts.js";+import { log } from "../utils/logger.js";+import { trackEvent } from "../utils/tracking.js";+import { ALL_AGENT_NAMES, SETUP_AGENT_NAMES, getAgent, type SetupAgent } from "../setup/agents.js";+import {+ readJsonConfig,+ readTomlServerExists,+ removeServerEntry,+ writeJsonConfig,+ resolveMcpPath,+ removeTomlServer,+} from "../setup/mcp-writer.js";+import { join } from "path";+import { access, readFile, rm, writeFile } from "fs/promises";++type Scope = "global" | "project";+type UninstallMode = "mcp" | "cli";++interface UninstallOptions {+ claude?: boolean;+ cursor?: boolean;+ opencode?: boolean;+ codex?: boolean;+ gemini?: boolean;+ project?: boolean;+ yes?: boolean;+ all?: boolean;+ cli?: boolean;+ mcp?: boolean;+}++interface CleanupStatus {+ status: string;+ path: string;+}++interface SkillCleanupStatus extends CleanupStatus {+ name: string;+}++interface AgentCleanupResult {+ agent: string;+ mcp?: CleanupStatus;+ rule?: CleanupStatus;+ skills?: SkillCleanupStatus[];+}++const CHECKBOX_THEME = {+ style: {+ highlight: (text: string) => pc.green(text),+ disabledChoice: (text: string) => ` ${pc.dim("◯")} ${pc.dim(text)}`,+ },+};++const CONTEXT7_SECTION_MARKER = "<!-- context7 -->";+const MODE_SKILLS: Record<UninstallMode, readonly string[]> = {+ mcp: ["context7-mcp"],+ cli: ["find-docs"],+};++const MODE_LABELS: Record<UninstallMode, string> = {+ mcp: "MCP",+ cli: "CLI + Skills",+};++export function registerRemoveCommand(program: Command): void {+ program+ .command("remove")+ .alias("uninstall")+ .description("Remove Context7 setup from your AI coding agent")+ .option("--claude", "Remove from Claude Code")+ .option("--cursor", "Remove from Cursor")+ .option("--opencode", "Remove from OpenCode")+ .option("--codex", "Remove from Codex")+ .option("--gemini", "Remove from Gemini CLI")+ .option("--all", "Remove both MCP setup and CLI + Skills setup")+ .option("--mcp", "Remove MCP setup")+ .option("--cli", "Remove CLI + Skills setup")+ .option("-p, --project", "Remove from the current project instead of global config")+ .option("-y, --yes", "Skip confirmation prompts")+ .action(async (options: UninstallOptions) => {+ await removeCommand(options);+ });+}++function getSelectedAgents(options: UninstallOptions): SetupAgent[] {+ const agents: SetupAgent[] = [];+ if (options.claude) agents.push("claude");+ if (options.cursor) agents.push("cursor");+ if (options.opencode) agents.push("opencode");+ if (options.codex) agents.push("codex");+ if (options.gemini) agents.push("gemini");+ return agents;+}++async function promptAgents(detected: SetupAgent[]): Promise<SetupAgent[] | null> {+ const choices = detected.map((name) => ({+ name: SETUP_AGENT_NAMES[name],+ value: name,+ }));++ if (detected.length > 0) {+ log.dim(`Detected: ${detected.map((agent) => SETUP_AGENT_NAMES[agent]).join(", ")}`);+ }++ try {+ return await checkboxWithHover(+ {+ message: "Which agents do you want to remove Context7 setup from?",+ choices,+ loop: false,+ theme: CHECKBOX_THEME,+ },+ { getName: (agent: SetupAgent) => SETUP_AGENT_NAMES[agent] }+ );+ } catch {+ return null;+ }+}++async function promptModes(modes: UninstallMode[]): Promise<UninstallMode[] | null> {+ const choices = modes.map((mode) => ({+ name: MODE_LABELS[mode],+ value: mode,+ }));++ try {+ return await checkboxWithHover(+ {+ message: "Which Context7 setup modes do you want to remove?",+ choices,+ loop: false,+ theme: CHECKBOX_THEME,+ },+ { getName: (mode: UninstallMode) => MODE_LABELS[mode] }+ );+ } catch {+ return null;+ }+}++async function resolveAgents(options: UninstallOptions, scope: Scope): Promise<SetupAgent[]> {+ const explicit = getSelectedAgents(options);+ if (explicit.length > 0) return explicit;++ const detected = await detectConfiguredAgents(scope);+ if (detected.length > 0 && options.yes) return detected;++ if (detected.length === 0) {+ log.warn(+ "No Context7 setup detected. Pass --claude, --cursor, --opencode, --codex, or --gemini."+ );+ return [];+ }++ log.blank();+ const selected = await promptAgents(detected);+ if (!selected) {+ log.warn("Remove cancelled");+ return [];+ }++ return selected;+}++function resolveFlagModes(options: UninstallOptions): UninstallMode[] {+ if (options.all) return ["mcp", "cli"];++ const selected: UninstallMode[] = [];++ if (options.mcp) selected.push("mcp");+ if (options.cli) selected.push("cli");++ return selected.length > 0 ? selected : ["mcp", "cli"];+}++async function pathExists(path: string): Promise<boolean> {+ try {+ await access(path);+ return true;+ } catch {+ return false;+ }+}++async function hasMcpConfig(agentName: SetupAgent, scope: Scope): Promise<boolean> {+ const agent = getAgent(agentName);+ const candidates =+ scope === "global"+ ? agent.mcp.globalPaths+ : agent.mcp.projectPaths.map((path) => join(process.cwd(), path));+ const mcpPath = await resolveMcpPath(candidates);++ if (mcpPath.endsWith(".toml")) {+ return readTomlServerExists(mcpPath, "context7");+ }++ const existing = await readJsonConfig(mcpPath);+ const section = existing[agent.mcp.configKey];+ return (+ !!section && typeof section === "object" && !Array.isArray(section) && "context7" in section+ );+}++async function hasRule(agentName: SetupAgent, scope: Scope): Promise<boolean> {+ const agent = getAgent(agentName);+ const rule = agent.rule;++ if (rule.kind === "file") {+ const ruleDir =+ scope === "global" ? rule.dir("global") : join(process.cwd(), rule.dir("project"));+ return pathExists(join(ruleDir, rule.filename));+ }++ const filePath =+ scope === "global" ? rule.file("global") : join(process.cwd(), rule.file("project"));++ try {+ const existing = await readFile(filePath, "utf-8");+ return existing.includes(CONTEXT7_SECTION_MARKER);+ } catch {+ return false;+ }+}++async function hasSkill(agentName: SetupAgent, scope: Scope, skillName: string): Promise<boolean> {+ const agent = getAgent(agentName);+ const skillsDir =+ scope === "global"+ ? agent.skill.dir("global")+ : join(process.cwd(), agent.skill.dir("project"));+ return pathExists(join(skillsDir, skillName));+}++async function detectAvailableModes(agents: SetupAgent[], scope: Scope): Promise<UninstallMode[]> {+ let hasMcpArtifacts = false;+ let hasCliArtifacts = false;+ let hasRuleArtifacts = false;++ for (const agent of agents) {+ hasMcpArtifacts =+ hasMcpArtifacts ||+ (await hasMcpConfig(agent, scope)) ||+ (await hasSkill(agent, scope, MODE_SKILLS.mcp[0]));+ hasCliArtifacts = hasCliArtifacts || (await hasSkill(agent, scope, MODE_SKILLS.cli[0]));+ hasRuleArtifacts = hasRuleArtifacts || (await hasRule(agent, scope));+ }++ const modes: UninstallMode[] = [];+ if (hasMcpArtifacts) modes.push("mcp");+ if (hasCliArtifacts) modes.push("cli");++ if (modes.length === 0 && hasRuleArtifacts) {+ return ["mcp", "cli"];+ }++ return modes;+}++async function hasAnyContext7Artifacts(agent: SetupAgent, scope: Scope): Promise<boolean> {+ return (+ (await hasMcpConfig(agent, scope)) ||+ (await hasRule(agent, scope)) ||+ (await hasSkill(agent, scope, MODE_SKILLS.mcp[0])) ||+ (await hasSkill(agent, scope, MODE_SKILLS.cli[0]))+ );+}++async function detectConfiguredAgents(scope: Scope): Promise<SetupAgent[]> {+ const detected: SetupAgent[] = [];++ for (const agent of ALL_AGENT_NAMES) {+ if (await hasAnyContext7Artifacts(agent, scope)) {+ detected.push(agent);+ }+ }++ return detected;+}++async function resolveModes(+ options: UninstallOptions,+ agents: SetupAgent[],+ scope: Scope+): Promise<UninstallMode[]> {+ if (options.all || options.mcp || options.cli) {+ return resolveFlagModes(options);+ }++ const detectedModes = await detectAvailableModes(agents, scope);+ if (detectedModes.length <= 1) {+ return detectedModes.length === 1 ? detectedModes : ["mcp", "cli"];+ }++ if (options.yes) {+ return detectedModes;+ }++ log.blank();+ const selected = await promptModes(detectedModes);+ if (!selected) {+ log.warn("Remove cancelled");+ return [];+ }++ return selected;+}++async function uninstallMcp(agentName: SetupAgent, scope: Scope): Promise<CleanupStatus> {+ const agent = getAgent(agentName);+ const mcpCandidates =+ scope === "global"+ ? agent.mcp.globalPaths+ : agent.mcp.projectPaths.map((path) => join(process.cwd(), path));+ const mcpPath = await resolveMcpPath(mcpCandidates);++ try {+ if (mcpPath.endsWith(".toml")) {+ const { removed } = await removeTomlServer(mcpPath, "context7");+ return { status: removed ? "removed" : "not found", path: mcpPath };+ }++ const existing = await readJsonConfig(mcpPath);+ const { config, removed } = removeServerEntry(existing, agent.mcp.configKey, "context7");+ if (removed) {+ await writeJsonConfig(mcpPath, config);+ }+ return { status: removed ? "removed" : "not found", path: mcpPath };+ } catch (err) {+ return { status: `failed: ${err instanceof Error ? err.message : String(err)}`, path: mcpPath };+ }+}++async function uninstallRule(agentName: SetupAgent, scope: Scope): Promise<CleanupStatus> {+ const agent = getAgent(agentName);+ const rule = agent.rule;++ if (rule.kind === "file") {+ const rulePath =+ scope === "global" ? rule.dir("global") : join(process.cwd(), rule.dir("project"));+ const targetPath = join(rulePath, rule.filename);++ try {+ await rm(targetPath);+ return { status: "removed", path: targetPath };+ } catch (err) {+ const error = err as NodeJS.ErrnoException;+ if (error.code === "ENOENT") return { status: "not found", path: targetPath };+ return { status: `failed: ${error.message}`, path: targetPath };+ }+ }++ const filePath =+ scope === "global" ? rule.file("global") : join(process.cwd(), rule.file("project"));++ try {+ const existing = await readFile(filePath, "utf-8");+ if (!existing.includes(CONTEXT7_SECTION_MARKER)) {+ return { status: "not found", path: filePath };+ }++ const escapedMarker = CONTEXT7_SECTION_MARKER.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");+ const updated = existing+ .replace(new RegExp(`\\n?${escapedMarker}\\n[\\s\\S]*?${escapedMarker}\\n?`, "m"), "")+ .replace(/\n{3,}/g, "\n\n")+ .replace(/^\n+/, "")+ .trimEnd();++ if (updated.length === 0) {+ await rm(filePath);+ } else {+ await writeFile(filePath, `${updated}\n`, "utf-8");+ }++ return { status: "removed", path: filePath };+ } catch (err) {+ const error = err as NodeJS.ErrnoException;+ if (error.code === "ENOENT") return { status: "not found", path: filePath };+ return { status: `failed: ${error.message}`, path: filePath };+ }+}++async function uninstallSkills(+ agentName: SetupAgent,+ scope: Scope,+ skillNames: readonly string[]+): Promise<SkillCleanupStatus[]> {+ const agent = getAgent(agentName);+ const skillsDir =+ scope === "global"+ ? agent.skill.dir("global")+ : join(process.cwd(), agent.skill.dir("project"));++ const results: SkillCleanupStatus[] = [];++ for (const skillName of skillNames) {+ const skillPath = join(skillsDir, skillName);+ try {+ await rm(skillPath, { recursive: true });+ results.push({ name: skillName, status: "removed", path: skillPath });+ } catch (err) {+ const error = err as NodeJS.ErrnoException;+ if (error.code === "ENOENT") {+ results.push({ name: skillName, status: "not found", path: skillPath });+ } else {+ results.push({ name: skillName, status: `failed: ${error.message}`, path: skillPath });+ }+ }+ }++ return results;+}++async function uninstallAgent(+ agentName: SetupAgent,+ scope: Scope,+ modes: UninstallMode[]+): Promise<AgentCleanupResult> {+ const result: AgentCleanupResult = { agent: getAgent(agentName).displayName };+ const skillNames = Array.from(new Set(modes.flatMap((mode) => [...MODE_SKILLS[mode]])));+ const shouldRemoveRule = modes.includes("mcp") || modes.includes("cli");++ if (modes.includes("mcp")) {+ result.mcp = await uninstallMcp(agentName, scope);+ }++ if (shouldRemoveRule) {+ result.rule = await uninstallRule(agentName, scope);+ }++ if (skillNames.length > 0) {+ result.skills = await uninstallSkills(agentName, scope, skillNames);+ }++ return result;+}++function iconForStatus(status: string): string {+ if (status === "removed") return pc.green("-");+ if (status === "not found") return pc.dim("~");+ return pc.red("!");+}++function printResults(results: AgentCleanupResult[], modes: UninstallMode[]): void {+ log.blank();+ const shouldPrintRule = modes.includes("mcp") || modes.includes("cli");+ let hasVisibleResults = false;++ for (const result of results) {+ const visibleSkills = result.skills?.filter((skill) => skill.status !== "not found") ?? [];+ const showMcp = modes.includes("mcp") && result.mcp && result.mcp.status !== "not found";+ const showRule = shouldPrintRule && result.rule && result.rule.status !== "not found";++ if (!showMcp && !showRule && visibleSkills.length === 0) {+ continue;+ }++ hasVisibleResults = true;+ log.plain(` ${pc.bold(result.agent)}`);++ if (showMcp && result.mcp) {+ log.plain(` ${iconForStatus(result.mcp.status)} MCP config ${result.mcp.status}`);+ log.plain(` ${pc.dim(result.mcp.path)}`);+ }++ if (showRule && result.rule) {+ log.plain(` ${iconForStatus(result.rule.status)} Rule ${result.rule.status}`);+ log.plain(` ${pc.dim(result.rule.path)}`);+ }++ for (const skill of visibleSkills) {+ log.plain(` ${iconForStatus(skill.status)} Skill ${skill.name} ${skill.status}`);+ log.plain(` ${pc.dim(skill.path)}`);+ }+ }++ if (hasVisibleResults) {+ log.blank();+ } else {+ log.plain(` ${pc.dim("No matching Context7 setup was found to remove.")}`);+ log.blank();+ }+}++async function removeCommand(options: UninstallOptions): Promise<void> {+ trackEvent("command", { name: "remove" });++ const scope: Scope = options.project ? "project" : "global";+ const agents = await resolveAgents(options, scope);+ if (agents.length === 0) return;+ const modes = await resolveModes(options, agents, scope);+ if (modes.length === 0) return;++ log.blank();+ const spinner = ora("Removing Context7 setup...").start();++ const results: AgentCleanupResult[] = [];+ for (const agentName of agents) {+ spinner.text = `Cleaning up ${getAgent(agentName).displayName}...`;+ results.push(await uninstallAgent(agentName, scope, modes));+ }++ spinner.succeed("Context7 cleanup complete");+ printResults(results, modes);++ trackEvent("remove", { agents, scope, modes });+}diff --git a/packages/cli/src/index.ts b/packages/cli/src/index.tsindex dffaafa7..76b69ac3 100644--- a/packages/cli/src/index.ts+++ b/packages/cli/src/index.ts@@ -4,6 +4,7 @@ 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 { registerRemoveCommand } from "./commands/remove.js";import { registerDocsCommands } from "./commands/docs.js";import { maybeShowUpgradeNotice, registerUpgradeCommand } from "./commands/upgrade.js";import { setBaseUrl } from "./utils/api.js";@@ -54,6 +55,12 @@ Examples:${brand.primary("npx ctx7 skills list --claude")}${brand.primary("npx ctx7 skills remove pdf")}+ ${brand.dim("# Remove Context7 setup")}+ ${brand.primary("npx ctx7 remove --cursor")}+ ${brand.primary("npx ctx7 remove --cursor --all")}+ ${brand.primary("npx ctx7 remove --cursor --cli")}+ ${brand.primary("npx ctx7 remove --claude --mcp")}+${brand.dim("# Query library documentation")}${brand.primary('npx ctx7 library react "how to use hooks"')}${brand.primary('npx ctx7 docs /facebook/react "useEffect examples"')}@@ -66,6 +73,7 @@ registerSkillCommands(program);registerSkillAliases(program);registerAuthCommands(program);registerSetupCommand(program);+registerRemoveCommand(program);registerDocsCommands(program);registerUpgradeCommand(program);diff --git a/packages/cli/src/setup/mcp-writer.ts b/packages/cli/src/setup/mcp-writer.tsindex 517f89f2..884f588d 100644--- a/packages/cli/src/setup/mcp-writer.ts+++ b/packages/cli/src/setup/mcp-writer.ts@@ -61,6 +61,33 @@ export function mergeServerEntry(};}+export function removeServerEntry(+ existing: Record<string, unknown>,+ configKey: string,+ serverName: string+): { config: Record<string, unknown>; removed: boolean } {+ const section = existing[configKey];+ if (!section || typeof section !== "object" || Array.isArray(section)) {+ return { config: existing, removed: false };+ }++ const current = section as Record<string, unknown>;+ if (!(serverName in current)) {+ return { config: existing, removed: false };+ }++ const rest = Object.fromEntries(Object.entries(current).filter(([key]) => key !== serverName));+ const next = { ...existing };++ if (Object.keys(rest).length === 0) {+ delete next[configKey];+ } else {+ next[configKey] = rest;+ }++ return { config: next, removed: true };+}+export async function resolveMcpPath(candidates: string[]): Promise<string> {for (const candidate of candidates) {try {@@ -158,3 +185,44 @@ export async function appendTomlServer(return { alreadyExists };}++export async function removeTomlServer(+ filePath: string,+ serverName: string+): Promise<{ removed: boolean }> {+ let existing = "";+ try {+ existing = await readFile(filePath, "utf-8");+ } catch {+ return { removed: false };+ }++ const sectionHeader = `[mcp_servers.${serverName}]`;+ const startIdx = existing.indexOf(sectionHeader);+ if (startIdx === -1) {+ return { removed: false };+ }++ const subPrefix = `[mcp_servers.${serverName}.`;+ const rest = existing.slice(startIdx + sectionHeader.length);++ let endOffset = rest.length;+ const re = /^\[/gm;+ let match: RegExpExecArray | null;+ while ((match = re.exec(rest)) !== null) {+ const lineEnd = rest.indexOf("\n", match.index);+ const line = rest.slice(match.index, lineEnd === -1 ? undefined : lineEnd);+ if (!line.startsWith(subPrefix)) {+ endOffset = match.index;+ break;+ }+ }++ const rawBefore = existing.slice(0, startIdx).replace(/\n+$/, "");+ const rawAfter = existing.slice(startIdx + sectionHeader.length + endOffset).replace(/^\n+/, "");+ const content = [rawBefore, rawAfter].filter(Boolean).join("\n\n");++ await mkdir(dirname(filePath), { recursive: true });+ await writeFile(filePath, content.length > 0 ? `${content}\n` : "", "utf-8");+ return { removed: true };+}diff --git a/packages/cli/tsconfig.json b/packages/cli/tsconfig.jsonindex c8192424..d9da7951 100644--- a/packages/cli/tsconfig.json+++ b/packages/cli/tsconfig.json@@ -4,6 +4,7 @@"module": "ESNext","moduleResolution": "bundler","lib": ["ES2022"],+ "types": ["node"],"outDir": "./dist","rootDir": "./src","strict": true,