Context7 Platform -- Up-to-date docs for AI agents
refactor: centralize error message generation and simplify code (#1071)
Enes Gulesa57d497bc107
diff --git a/src/index.ts b/src/index.tsindex f87de1af..3ad7d122 100644--- a/src/index.ts+++ b/src/index.ts@@ -5,7 +5,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"import { z } from "zod";import { searchLibraries, fetchLibraryDocumentation } from "./lib/api.js";import { formatSearchResults } from "./lib/utils.js";-import { SearchResponse } from "./lib/types.js";+import { SearchResponse, DOCUMENTATION_MODES } from "./lib/types.js";import express from "express";import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";import { Command } from "commander";@@ -224,13 +224,13 @@ server.registerTool(),},},- async ({ context7CompatibleLibraryID, mode = "code", page = 1, topic = "" }) => {+ async ({ context7CompatibleLibraryID, mode = DOCUMENTATION_MODES.CODE, page = 1, topic }) => {const ctx = requestContext.getStore();const apiKey = ctx?.apiKey || globalApiKey;const fetchDocsResponse = await fetchLibraryDocumentation(context7CompatibleLibraryID,+ mode,{- mode,page,limit: DEFAULT_RESULTS_LIMIT,topic,@@ -360,14 +360,9 @@ async function main() {});const startServer = (port: number, maxAttempts = 10) => {- const httpServer = app.listen(port, () => {- actualPort = port;- console.error(- `Context7 Documentation MCP Server running on HTTP at http://localhost:${actualPort}/mcp`- );- });+ const httpServer = app.listen(port);- httpServer.on("error", (err: NodeJS.ErrnoException) => {+ httpServer.once("error", (err: NodeJS.ErrnoException) => {if (err.code === "EADDRINUSE" && port < initialPort + maxAttempts) {console.warn(`Port ${port} is in use, trying port ${port + 1}...`);startServer(port + 1, maxAttempts);@@ -376,6 +371,13 @@ async function main() {process.exit(1);}});++ httpServer.once("listening", () => {+ actualPort = port;+ console.error(+ `Context7 Documentation MCP Server running on HTTP at http://localhost:${actualPort}/mcp`+ );+ });};startServer(initialPort);diff --git a/src/lib/api.ts b/src/lib/api.tsindex bb294424..6c21e184 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1,10 +1,10 @@import { SearchResponse } from "./types.js";import { generateHeaders } from "./encryption.js";import { ProxyAgent, setGlobalDispatcher } from "undici";+import { DocumentationMode, DOCUMENTATION_MODES } from "./types.js";+import { maskApiKey } from "./utils.js";const CONTEXT7_API_BASE_URL = "https://context7.com/api";-const CONTEXT7_API_V1_URL = CONTEXT7_API_BASE_URL + "/v1";-const CONTEXT7_API_V2_URL = CONTEXT7_API_BASE_URL + "/v2";const DEFAULT_TYPE = "txt";/**@@ -34,6 +34,30 @@ function parseLibraryId(libraryId: string): {};}+/**+ * Generates appropriate error messages based on HTTP status codes+ * @param errorCode The HTTP error status code+ * @param apiKey Optional API key (used for rate limit message)+ * @returns Error message string+ */+function createErrorMessage(errorCode: number, apiKey?: string): string {+ switch (errorCode) {+ case 429:+ return apiKey+ ? "Rate limited due to too many requests. Please try again later."+ : "Rate limited due to too many requests. You can create a free API key at https://context7.com/dashboard for higher rate limits.";+ case 404:+ return "The library you are trying to access does not exist. Please try with a different library ID.";+ case 401:+ if (!apiKey) {+ return "Unauthorized. Please provide an API key.";+ }+ return `Unauthorized. Please check your API key. The API key you provided (possibly incorrect) is: ${maskApiKey(apiKey)}. API keys should start with 'ctx7sk'`;+ default:+ return `Failed to fetch documentation. Please try again later. Error code: ${errorCode}`;+ }+}+// Pick up proxy configuration in a variety of common env var names.const PROXY_URL: string | null =process.env.HTTPS_PROXY ??@@ -71,7 +95,7 @@ export async function searchLibraries(apiKey?: string): Promise<SearchResponse> {try {- const url = new URL(`${CONTEXT7_API_V1_URL}/search`);+ const url = new URL(`${CONTEXT7_API_BASE_URL}/v2/search`);url.searchParams.set("query", query);const headers = generateHeaders(clientIp, apiKey);@@ -79,28 +103,7 @@ export async function searchLibraries(const response = await fetch(url, { headers });if (!response.ok) {const errorCode = response.status;- if (errorCode === 429) {- const errorMessage = apiKey- ? "Rate limited due to too many requests. Please try again later."- : "Rate limited due to too many requests. You can create a free API key at https://context7.com/dashboard for higher rate limits.";- console.error(errorMessage);- return {- results: [],- error: errorMessage,- } as SearchResponse;- }- if (errorCode === 401) {- const errorMessage =- "Unauthorized. Please check your API key. The API key you provided (possibly incorrect) is: " +- apiKey +- ". API keys should start with 'ctx7sk'";- console.error(errorMessage);- return {- results: [],- error: errorMessage,- } as SearchResponse;- }- const errorMessage = `Failed to search libraries. Please try again later. Error code: ${errorCode}`;+ const errorMessage = createErrorMessage(errorCode, apiKey);console.error(errorMessage);return {results: [],@@ -118,15 +121,16 @@ export async function searchLibraries(/*** Fetches documentation context for a specific library* @param libraryId The library ID to fetch documentation for- * @param options Options for the request+ * @param docMode Documentation mode (CODE for API references and code examples, INFO for conceptual guides)+ * @param options Optional request parameters (page, limit, topic)* @param clientIp Optional client IP address to include in headers* @param apiKey Optional API key for authentication* @returns The documentation text or null if the request fails*/export async function fetchLibraryDocumentation(libraryId: string,+ docMode: DocumentationMode,options: {- mode?: "code" | "info";page?: number;limit?: number;topic?: string;@@ -137,11 +141,8 @@ export async function fetchLibraryDocumentation(try {const { username, library, tag } = parseLibraryId(libraryId);- // Determine endpoint based on mode (default to 'code')- const endpoint = options.mode === "info" ? "info" : "code";-// Build URL path- let urlPath = `${CONTEXT7_API_V2_URL}/docs/${endpoint}/${username}/${library}`;+ let urlPath = `${CONTEXT7_API_BASE_URL}/v2/docs/${docMode}/${username}/${library}`;if (tag) {urlPath += `/${tag}`;}@@ -157,36 +158,17 @@ export async function fetchLibraryDocumentation(const response = await fetch(url, { headers });if (!response.ok) {const errorCode = response.status;- if (errorCode === 429) {- const errorMessage = apiKey- ? "Rate limited due to too many requests. Please try again later."- : "Rate limited due to too many requests. You can create a free API key at https://context7.com/dashboard for higher rate limits.";- console.error(errorMessage);- return errorMessage;- }- if (errorCode === 404) {- const errorMessage =- "The library you are trying to access does not exist. Please try with a different library ID.";- console.error(errorMessage);- return errorMessage;- }- if (errorCode === 401) {- const errorMessage =- "Unauthorized. Please check your API key. The API key you provided (possibly incorrect) is: " +- apiKey +- ". API keys should start with 'ctx7sk'";- console.error(errorMessage);- return errorMessage;- }- const modeType = endpoint === "info" ? "informational" : "code";- const errorMessage = `Failed to fetch ${modeType} documentation. Please try again later. Error code: ${errorCode}`;+ const errorMessage = createErrorMessage(errorCode, apiKey);console.error(errorMessage);return errorMessage;}const text = await response.text();if (!text || text === "No content available" || text === "No context data available") {- const modeType = endpoint === "info" ? "informational" : "code";- return `No ${modeType} documentation available for this library.${endpoint === "code" ? " Try mode='info' for guides and tutorials." : " Try mode='code' for API references and code examples."}`;+ const suggestion =+ docMode === DOCUMENTATION_MODES.CODE+ ? " Try mode='info' for guides and tutorials."+ : " Try mode='code' for API references and code examples.";+ return `No ${docMode} documentation available for this library.${suggestion}`;}return text;} catch (error) {diff --git a/src/lib/encryption.ts b/src/lib/encryption.tsindex ea0950da..95410288 100644--- a/src/lib/encryption.ts+++ b/src/lib/encryption.ts@@ -1,10 +1,13 @@import { createCipheriv, randomBytes } from "crypto";-const ENCRYPTION_KEY =- process.env.CLIENT_IP_ENCRYPTION_KEY ||- "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";+const DEFAULT_ENCRYPTION_KEY = "000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f";+const ENCRYPTION_KEY = process.env.CLIENT_IP_ENCRYPTION_KEY || DEFAULT_ENCRYPTION_KEY;const ALGORITHM = "aes-256-cbc";+if (ENCRYPTION_KEY === DEFAULT_ENCRYPTION_KEY) {+ console.warn("WARNING: Using default CLIENT_IP_ENCRYPTION_KEY.");+}+function validateEncryptionKey(key: string): boolean {// Must be exactly 64 hex characters (32 bytes)return /^[0-9a-fA-F]{64}$/.test(key);diff --git a/src/lib/types.ts b/src/lib/types.tsindex c1935a53..05bd154a 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -21,3 +21,13 @@ export interface SearchResponse {// Version state is still needed for validating search resultsexport type DocumentState = "initial" | "finalized" | "error" | "delete";++/**+ * Documentation modes for fetching library documentation+ */+export const DOCUMENTATION_MODES = {+ CODE: "code",+ INFO: "info",+} as const;++export type DocumentationMode = (typeof DOCUMENTATION_MODES)[keyof typeof DOCUMENTATION_MODES];diff --git a/src/lib/utils.ts b/src/lib/utils.tsindex 814a4a81..eeef7836 100644--- a/src/lib/utils.ts+++ b/src/lib/utils.ts@@ -67,3 +67,22 @@ export function formatSearchResults(searchResponse: SearchResponse): string {const formattedResults = searchResponse.results.map(formatSearchResult);return formattedResults.join("\n----------\n");}++/**+ * Masks an API key by showing only the first 10 characters and last 4 characters.+ * This prevents full API keys from being exposed in logs while maintaining some+ * identifiability for debugging.+ *+ * @param apiKey The API key to mask+ * @returns Masked API key string (e.g., "ctx7sk-abc...xyz1") or "[NO-API-KEY]" if no key provided+ */+export function maskApiKey(apiKey: string): string {+ if (apiKey.length <= 14) {+ // If the key is too short to mask meaningfully, just show first part+ return apiKey.substring(0, 7) + "...";+ }++ const firstPart = apiKey.substring(0, 10);+ const lastPart = apiKey.substring(apiKey.length - 4);+ return `${firstPart}...${lastPart}`;+}