Context7 MCP server package
Overview
packages/mcp is the published @upstash/context7-mcp package. Its executable entrypoint is packages/…/index.ts, built to dist/index.js by packages/…/package.json and exposed as the context7-mcp bin. The same entrypoint serves two transports: --transport stdio for local MCP clients and --transport http for the hosted Streamable HTTP server. HTTP defaults to port 3000, retries adjacent ports on EADDRINUSE, and rejects stdio-only flags such as --api-key and --experimental; stdio rejects --port and reads credentials from --api-key or CONTEXT7_API_KEY after filtering unresolved shell placeholders via usableApiKey in packages/…/mcp-http-auth.ts.
Server construction lives in createMcpServer inside packages/…/index.ts. It creates an McpServer with static prompts/resources capability declarations, explicit cache hints, server metadata from packages/…/constants.ts, and two stable tools:
resolve-library-id, which sendsqueryandlibraryNametosearchLibrariesin packages/…/api.ts, formats matches withformatSearchResultsin packages/…/utils.ts, and marks upstream failures as MCP tool errors while treating empty matches as normal answers.query-docs, which sendslibraryId,query, and optionallanguagetofetchLibraryContextin packages/…/api.ts, returns Context7 API text, and setsisErroronly when the API request failed.
Tool names and the experimental catalog are centralized in packages/…/tool-names.ts. Argument compatibility is handled at the schema boundary: packages/…/tool-args.ts rewrites common hallucinated argument names before Zod validation, and packages/…/query-code-tool.ts has extra preprocessing to reject docs-style multi-word query values unless they can safely become a source-code pattern. Experimental tools are registered by packages/…/experimental-tools.ts: query-code calls /v2/code, get-upgrade-guide calls /v2/version-upgrade-guide, and submit-docs-feedback posts to /v2/feedback. They are listed only when enabled by --experimental, CONTEXT7_EXPERIMENTAL=1/CONTEXT7_RESEARCH_PREVIEW=1, HTTP ?experimental=1/?research_preview=1, or a signed-in user's dashboard choice fetched through fetchExperimentalTools in packages/…/api.ts.
HTTP mode in packages/…/index.ts builds an Express app around createMcpHandler and toNodeHandler. It sets proxy trust for private infrastructure, global CORS headers for browser MCP clients, and mounts JSON parsing only under the /mcp router. The MCP endpoints are /mcp and the compatibility alias /mcp/oauth; /mcp/server-card serves the SEP-2127 server card from mcpServerCard in packages/…/constants.ts; /ping is a health endpoint; .well-known/oauth-protected-resource routes advertise resource metadata from packages/…/mcp-http-auth.ts; .well-known/oauth-authorization-server proxies Clerk metadata; and .well-known/openai-apps-challenge serves OPENAI_APPS_CHALLENGE_TOKEN when configured. packages/…/mcp-body-error-handler.ts is the MCP-router error boundary that converts body-parser failures into sanitized JSON-RPC errors instead of Express HTML.
HTTP authentication is decided before a request reaches the MCP transport. packages/…/index.ts extracts bearer/API-key credentials from Authorization, X-Context7-API-Key, Context7-API-Key, X-API-Key, and underscore variants, determines /mcp versus /mcp/oauth with canonicalMcpEndpoint, then calls evaluateMcpAuthentication in packages/…/mcp-http-auth.ts. MCP_AUTH_ENFORCEMENT defaults to required, but observe can allow anonymous /mcp traffic while keeping /mcp/oauth and non-empty Claude Code plugin auth challengeable. API keys pass through to the Context7 API for authoritative validation; opaque Clerk OAuth tokens (oat_...) are checked against /v2/auth/check by packages/…/oauth-token-validation.ts; JWTs are verified in packages/…/jwt.ts for Clerk OAuth access tokens, Context7 EMA, Microsoft Entra, or Vercel Marketplace OIDC. OAuth audience normalization and rollout modes are in packages/…/oauth-audience.ts.
Both transports build a ClientContext that is later turned into Context7 API headers by packages/…/encryption.ts. The API layer adds X-Context7-Source, package version, transport, client IDE/version, plugin name, API key, experimental marker, stdio session ID, and optionally an encrypted mcp-client-ip-assertion when MCP_CLIENT_IP_ASSERTION_KEY is a valid 32-byte hex key. Outbound API calls in packages/…/api.ts target CONTEXT7_API_URL or https://context7.com/api, have bounded timeouts, honor HTTPS_PROXY/HTTP_PROXY, and can load custom CAs from NODE_EXTRA_CA_CERTS.
Telemetry is opt-out through OTEL_SDK_DISABLED=true. packages/…/telemetry-runtime.ts dynamically loads telemetry modules so disabled stdio processes avoid importing OpenTelemetry. packages/…/mcp-telemetry.ts instruments MCP operations and spans, packages/…/mcp-subscription-telemetry.ts tracks modern subscription lifecycles, packages/…/telemetry.ts records upstream/authentication metrics, and packages/…/telemetry-provider.ts starts the embedded Prometheus exporter for HTTP mode when OTEL_METRICS_EXPORTER is unset or includes prometheus. The Docker image in packages/mcp/Dockerfile exposes 8080 for HTTP and 9464 for metrics, sets OTEL_EXPORTER_PROMETHEUS_HOST=0.0.0.0, and starts node dist/index.js --transport http --port 8080.
Shutdown is coordinated by packages/…/process-shutdown.ts. HTTP mode first marks responses with Connection: close, drains and closes the Node HTTP server, then closes the MCP handler and flushes telemetry. Stdio mode installs the same bounded shutdown around the SDK stdio handle and also treats stdin EOF as termination. packages/…/index.ts additionally filters legacy HTTP JSON-RPC batches where a request cancels itself in the same batch, returning 202 for a fully consumed batch to avoid hung response accounting.
Package assets under this doc's scope include the public configuration schema at packages/…/context7.json, the MCP Bundle manifest at packages/…/manifest.json, Smithery HTTP metadata in packages/…/smithery.yaml, and user-facing installation/runtime guidance in packages/…/README.md. Tests under packages/mcp/test/** are a mix of focused unit tests and a real-binary integration suite: packages/…/integration.test.ts builds dist/index.js, spawns HTTP and stdio servers against a stub Context7 API, and exercises both modern and legacy MCP protocol eras; auth, OAuth audience/JWT, telemetry, shutdown, query-code, certificate, and utility behavior each have dedicated files named after the library module they protect.
Coupling
- If a tool is added, renamed, or removed in packages/…/tool-names.ts, update all registration sites in packages/…/index.ts, packages/…/experimental-tools.ts, or packages/…/query-code-tool.ts, plus telemetry allowlists in packages/…/mcp-telemetry.ts, the MCPB manifest in packages/…/manifest.json, and the integration expectations in packages/…/integration.test.ts.
- If tool argument names change in packages/…/index.ts, packages/…/experimental-tools.ts, or packages/…/query-code-tool.ts, keep packages/…/tool-args.ts aliases and the cache-hint comment in
createMcpServeraligned; clients may cachetools/listfor up to an hour and keep calling with old names. - If Context7 API routes or response semantics change, update packages/…/api.ts and the stub server in packages/…/integration.test.ts together. The MCP tools intentionally distinguish upstream failures (
isError) from actionable answers such as empty docs, code indexing, unavailable upgrade guides, invalid pages, and unknown versions. - If OAuth issuer, audience, or protected-resource metadata changes in packages/…/constants.ts, packages/…/mcp-http-auth.ts, packages/…/oauth-audience.ts, or packages/…/jwt.ts, verify the
.well-knownroutes in packages/…/index.ts and the OAuth tests in packages/…/oauth-audience.test.ts, packages/…/clerk-oauth-jwt.test.ts, and packages/…/mcp-http-auth.test.ts; clients depend on the 401WWW-Authenticateresource metadata to refresh sign-ins. - If MCP SDK protocol handling changes, check packages/…/index.ts, packages/…/utils.ts, packages/…/mcp-telemetry.ts, and packages/…/mcp-subscription-telemetry.ts together. They inspect protocol-era metadata, client-info envelopes, JSON-RPC cancellation messages, subscription acknowledgements, and trace propagation keys that are not all enforced by TypeScript types.
- If package versioning or packaging changes in packages/…/package.json, also check packages/…/constants.ts,
packages/mcp/Dockerfile, and packages/…/manifest.json: the runtime reads package version from package.json, Docker and MCPB bundle different entrypoints, and tests spawn the built dist/index.js.
Risks
- packages/…/index.ts has several production-proven edge cases around HTTP lifecycle and JSON-RPC batching. Recent history includes fixes for strict port validation (
6a54ec3,66e4771), draining HTTP on shutdown (1b00727), and consuming self-cancelling batches (7cbd5fd). Regressions here can make the hosted server fail startup, drop kept-alive requests during deploys, or leave MCP streams hanging until gateway timeouts. - Authentication rollout code spans packages/…/mcp-http-auth.ts, packages/…/oauth-token-validation.ts, packages/…/oauth-audience.ts, and packages/…/jwt.ts. A bad enforcement default or audience normalization change can either reject valid OAuth clients or admit tokens issued for another MCP resource; warning logs are throttled by token hash, so low-volume test coverage may miss high-volume log or challenge loops.
- packages/…/api.ts intentionally fails open for some auth-check outages and fails closed for remembered invalid OAuth tokens. If error-code handling around
invalid_oauth_tokenchanges, HTTP clients may receive tool-text errors instead of an HTTP 401 and never refresh their sign-in. - Experimental tool listing is per credential and cached in packages/…/api.ts. If cache keys, TTLs, or the
X-Context7-Experimentalheader drift from packages/…/tool-names.ts and packages/…/experimental-tools.ts, one user's dashboard choice can be stale or invisible, and clients can cache the wrongtools/listscope.