Context7 CLI Package
Overview
The packages/cli package builds and publishes the ctx7 executable. packages/…/package.json exposes ./…/index.js as the ctx7 bin, requires Node >=22.13.0, and runs tsup/tsc/vitest/ESLint scripts for build, typecheck, tests, and lint. packages/…/tsup.config.ts bundles src/index.ts as ESM, adds the #!/usr/bin/env node banner, emits source maps and declarations, and keeps prompt-related packages external; packages/…/vitest.config.ts runs src/…/*.test.ts in a Node environment. The package is TypeScript-only under packages/cli/src/**, with shared response types in src/types.ts and runtime package metadata loaded from src/constants.ts.
The command entrypoint is packages/…/index.ts. It creates the Commander program, sets the root --base-url global option, applies it before each action through configuredBaseUrl()/setBaseUrl() from src/…/api.ts, then runs maybeShowUpgradeNotice() before subcommand actions. It registers auth, setup, remove, docs/library/code/upgrade-guide, search, and upgrade commands from src/…/*.ts; when no subcommand is passed it prints a figlet Context7 banner and quick-start examples.
Documentation lookup commands live mostly in packages/…/docs.ts and packages/…/search.ts. library calls resolveLibrary() and prints ranked Context7 library IDs with source-code availability inferred by hasSourceCode(); docs validates and recovers slash-prefixed IDs with recoverLibraryId() before calling /api/v2/context; code validates operation and numeric flags, maps CLI flags to /api/v2/code, and treats 202 responses as retryable work with exit code 75; get-upgrade-guide similarly calls /api/v2/version-upgrade-guide and exits 75 while a guide is being prepared. search calls /api/v3/search, supports repeated --library, --library-version, language, and JSON/text output. All of these commands resolve a valid hosted login token with getValidAccessToken() before network calls, then src/…/api.ts gives CONTEXT7_API_KEY precedence over stored tokens when building Authorization headers.
Authentication is split between command UX and token storage. packages/…/auth.ts registers login, logout, and whoami; login implements the OAuth device flow with /api/oauth/device/code and /api/oauth/device/token, prints a boxed device code/link, opens the browser unless --no-browser is used, handles slow-down/transient polling, and stores approved tokens. whoami checks /api/dashboard/whoami with a 30-second timeout and prints user/teamspace details. packages/…/auth.ts owns token persistence, refresh, and recovery: credentials are saved as JSON under the XDG config path from src/…/storage-paths.ts, migrated from legacy ~/.context7, forced to mode 0600, and refreshed under a cross-process file lock from src/…/file-lock.ts so concurrent agent invocations do not reuse a rotated refresh token. Stored ctx7 login sessions are intentionally ignored for custom deployments (getValidAccessToken() returns undefined when isHostedDeployment() is false); on-prem requests authenticate through CONTEXT7_API_KEY or setup-provided API keys instead.
Setup and removal are the package's largest flow. packages/…/setup.ts registers setup with one flag per agent from ALL_AGENT_NAMES, plus --t3, --mcp, --cli, --project, --yes, --api-key, --oauth, --stdio, and a command-local --base-url so Commander accepts it after setup. The command resolves hosted versus custom deployment with src/…/deployment.ts, chooses MCP or CLI+Skills mode, detects/selects agents, resolves auth, and then writes three kinds of artifacts per agent: MCP server config, a rule/instructions file or append section, and skill files. Hosted MCP setup can use API key, OAuth endpoint, or stdio; custom --base-url setup is restricted to HTTP MCP and discovers whether /api/auth/mcp requires a key. CLI+Skills setup authenticates via resolveCliAuth(), downloads or falls back to bundled find-docs skill text from src/…/templates.ts, and installs rules that tell agents to invoke ctx7 commands.
Agent-specific paths and config shapes are centralized in packages/…/agents.ts. The supported agent map currently includes Claude Code, Cursor, VS Code, Devin, GitHub Copilot CLI, OpenCode, Codex, Antigravity, Gemini CLI, and Pi, each with MCP config candidates, rule destination/append semantics, skill directory, detection paths, and an MCP entry builder for HTTP or stdio. --t3 expands to Claude and Codex. The setup command writes JSON/JSONC configs through src/…/mcp-writer.ts, OpenCode configs through src/…/opencode-editor.ts, and Codex TOML through the TOML helpers in src/…/mcp-writer.ts and src/…/toml-editor.ts; these helpers try to patch existing files in place so comments, line endings, layout, package pins, and unrelated settings survive. Skill installation is performed by src/…/installer.ts, guarded by src/…/skill-name.ts to prevent path traversal.
packages/…/remove.ts is the inverse cleanup flow. It registers remove/uninstall, accepts the same agent selectors plus --all, --mcp, --cli, --project, and --yes, detects configured agents by looking for MCP entries, Context7 rules, and context7-mcp/find-docs skill directories, prompts for agents/modes when needed, then removes MCP entries, rules, and skills. It shares src/…/agents.ts for path definitions, src/…/mcp-writer.ts for JSON/TOML removal, and src/…/opencode-editor.ts for OpenCode v1/v2 layouts. Append-rule removal preserves the user's surrounding AGENTS/GEMINI content and line ending style while deleting only the <!-- context7 --> section.
Update checking and telemetry are utility-level background behavior. packages/…/upgrade.ts registers upgrade and exposes maybeShowUpgradeNotice() for the root pre-action hook; src/…/update-check.ts reads/writes cached npm-version state under the XDG state path, detects install method from npm/pnpm/bun environment variables, suppresses notices for JSON/version/base-url invocations, and plans either runnable global upgrades or explicit ctx7@latest commands for ephemeral runners. packages/…/tracking.ts sends fire-and-forget events to /api/v2/cli/events only for hosted Context7 and only when CTX7_TELEMETRY_DISABLED is not set.
The test suite under packages/cli/src/__tests__/** is path-routable to these subsystems: setup and removal behavior (setup*.test.ts, remove.test.ts, mcp-writer.test.ts, toml-editor.test.ts, opencode-editor.test.ts, agent-command-registry.test.ts, fixtures under fixtures/cursor), auth/session behavior (auth-commands.test.ts, auth-utils.test.ts, setup-auth.test.ts, command-auth-wiring.test.ts), API/query commands (search-command.test.ts, code-api.test.ts, library-id.test.ts, base-url.test.ts, find-docs-skill-alignment.test.ts), and background utilities (update-check.test.ts, upgrade-command.test.ts, tracking.test.ts, storage-paths.test.ts, file-lock.test.ts, installer.test.ts, plugin-manifests.test.ts).
Coupling
- If a command adds or changes a Context7 API call in packages/…/docs.ts, packages/…/search.ts, or packages/…/auth.ts, also update the corresponding request/response handling in packages/…/api.ts or packages/…/types.ts; the commands set user-facing exit codes and output formats based on those helper return shapes rather than raw
fetchresponses. - If library ID validation changes in packages/…/docs.ts, also check packages/…/library-id.ts and the
searchcommand's repeated--libraryhandling in packages/…/search.ts; both compensate for Git Bash rewriting/owner/repoarguments on Windows. - If an agent path, config key, MCP entry shape, or rule marker changes in packages/…/agents.ts, verify both packages/…/setup.ts and packages/…/remove.ts; setup and cleanup share the registry, and stale removal logic can leave orphaned MCP entries or delete the wrong rule section.
- If JSONC, TOML, or OpenCode config editing changes in packages/…/mcp-writer.ts, packages/…/toml-editor.ts, or packages/…/opencode-editor.ts, run the setup/remove tests for those editors; setup.ts deliberately patches existing files in place to preserve comments, CRLF/LF line endings, OpenCode v1/v2 layouts, and existing stdio package pins.
- If authentication storage changes in packages/…/auth.ts or packages/…/storage-paths.ts, verify packages/…/auth.ts, packages/…/setup.ts, and packages/…/file-lock.ts; setup may create API keys from OAuth sessions, commands depend on refresh before anonymous fallback, and concurrent agent processes rely on the refresh lock to avoid invalidating sessions.
- If
--base-urlor custom deployment behavior changes in packages/…/index.ts, packages/…/api.ts, or packages/…/deployment.ts, check setup validation and telemetry/update-notifier behavior too; custom deployments skip hosted login tokens, skip telemetry, suppress update notifications, and currently support only HTTP MCP setup. - If rule or skill fallback text changes in packages/…/templates.ts, verify packages/…/README.md and packages/…/find-docs-skill-alignment.test.ts; the fallback content documents CLI command names, retry semantics, source-code flags, upgrade-guide behavior, and Codex sandbox guidance that must remain aligned with the actual commands.
- If build output assumptions change in packages/…/package.json or packages/…/tsup.config.ts, verify packages/…/constants.ts; the built file reads ../package.json at runtime to expose
VERSION,NAME, and the OAuth client ID to command registration and API headers.
Risks
- packages/…/mcp-writer.ts, packages/…/toml-editor.ts, packages/…/opencode-editor.ts, packages/…/setup.ts, and packages/…/remove.ts edit user-owned agent configs. If these patchers mishandle JSONC/TOML/OpenCode layouts or line endings, setup/remove can discard comments, unrelated servers, pinned stdio package versions, or user instructions; recent CLI history includes fixes for preserving JSONC comments, CRLF AGENTS.md sections, and OpenCode 2.x
mcp.serversplacement. - packages/…/auth.ts and packages/…/file-lock.ts protect refresh-token rotation. If the lock or reread-before-refresh path is bypassed, concurrent
ctx7commands launched by an agent can reuse the same refresh token and cause the authorization server to revoke the grant, logging the user out. - packages/…/api.ts, packages/…/docs.ts, and packages/…/auth.ts rely on explicit request/body timeouts. If new API calls skip
fetchWithTimeout()or OAuth timeout helpers, a stalled Context7 host can hang an agent session instead of failing with a recoverable message; recent history added timeouts for CLI API calls and OAuth/whoami paths. - packages/…/logger.ts intentionally sends warnings/errors to stderr when stdout is piped. If command code writes diagnostics directly to stdout while also supporting text/JSON output, downstream tools consuming
ctx7 code,ctx7 docs --json, orctx7 search --jsoncan receive contaminated output.