Context7 Platform -- Up-to-date docs for AI agents
feat: parse error messages from API response body (#1250)
Enes Gulesaa123909babd
diff --git a/.changeset/nice-bottles-rule.md b/.changeset/nice-bottles-rule.mdnew file mode 100644index 00000000..85ab1dfa--- /dev/null+++ b/.changeset/nice-bottles-rule.md@@ -0,0 +1,5 @@+---+"@upstash/context7-mcp": patch+---++Improve error message handling by using the responses from the server.diff --git a/packages/mcp/src/lib/api.ts b/packages/mcp/src/lib/api.tsindex 1b8174ca..05a75f89 100644--- a/packages/mcp/src/lib/api.ts+++ b/packages/mcp/src/lib/api.ts@@ -34,27 +34,36 @@ 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)+ * Parses error response from the Context7 API+ * Extracts the server's error message, falling back to status-based messages if parsing fails+ * @param response The fetch Response object+ * @param apiKey Optional API key (used for fallback messages)* @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. API keys should start with 'ctx7sk'`;- default:- return `Failed to fetch documentation. Please try again later. Error code: ${errorCode}`;+async function parseErrorResponse(response: Response, apiKey?: string): Promise<string> {+ try {+ const json = (await response.json()) as { message?: string };+ if (json.message) {+ return json.message;+ }+ } catch {+ // JSON parsing failed, fall through to default+ }++ // Fallback for non-JSON responses+ const status = response.status;+ if (status === 429) {+ return apiKey+ ? "Rate limited or quota exceeded. Upgrade your plan at https://context7.com/plans for higher limits."+ : "Rate limited or quota exceeded. Create a free API key at https://context7.com/dashboard for higher limits.";+ }+ if (status === 404) {+ return "The library you are trying to access does not exist. Please try with a different library ID.";+ }+ if (status === 401) {+ return "Invalid API key. Please check your API key. API keys should start with 'ctx7sk' prefix.";}+ return `Request failed with status ${status}. Please try again later.`;}// Pick up proxy configuration in a variety of common env var names.@@ -101,8 +110,7 @@ export async function searchLibraries(const response = await fetch(url, { headers });if (!response.ok) {- const errorCode = response.status;- const errorMessage = createErrorMessage(errorCode, apiKey);+ const errorMessage = await parseErrorResponse(response, apiKey);console.error(errorMessage);return {results: [],@@ -157,8 +165,7 @@ export async function fetchLibraryDocumentation(const response = await fetch(url, { headers });if (!response.ok) {- const errorCode = response.status;- const errorMessage = createErrorMessage(errorCode, apiKey);+ const errorMessage = await parseErrorResponse(response, apiKey);console.error(errorMessage);return errorMessage;}diff --git a/packages/sdk/src/client.test.ts b/packages/sdk/src/client.test.tsindex 98045714..42a858df 100644--- a/packages/sdk/src/client.test.ts+++ b/packages/sdk/src/client.test.ts@@ -49,8 +49,6 @@ describe("Context7 Client", () => {expect(result.results).toBeDefined();expect(Array.isArray(result.results)).toBe(true);expect(result.results.length).toBeGreaterThan(0);- expect(result.metadata).toBeDefined();- expect(result.metadata.authentication).toBeDefined();});test("should return results with correct structure", async () => {diff --git a/packages/sdk/src/commands/get-docs/index.test.ts b/packages/sdk/src/commands/get-docs/index.test.tsindex 502b4dcf..923c9ca0 100644--- a/packages/sdk/src/commands/get-docs/index.test.ts+++ b/packages/sdk/src/commands/get-docs/index.test.ts@@ -61,7 +61,6 @@ describe("GetDocsCommand", () => {expect(result).toHaveProperty("snippets");expect(Array.isArray((result as CodeDocsResponse).snippets)).toBe(true);expect(result).toHaveProperty("pagination");- expect(result).toHaveProperty("metadata");});test("should get library code docs using client with pagination and totalTokens", async () => {diff --git a/packages/sdk/src/commands/search-library/index.test.ts b/packages/sdk/src/commands/search-library/index.test.tsindex df3523ae..786711db 100644--- a/packages/sdk/src/commands/search-library/index.test.ts+++ b/packages/sdk/src/commands/search-library/index.test.ts@@ -14,8 +14,6 @@ describe("SearchLibraryCommand", () => {expect(result.results).toBeDefined();expect(Array.isArray(result.results)).toBe(true);expect(result.results.length).toBeGreaterThan(0);- expect(result.metadata).toBeDefined();- expect(typeof result.metadata.authentication).toBe("string");});test("should search for a library using client", async () => {@@ -29,7 +27,5 @@ describe("SearchLibraryCommand", () => {expect(result.results).toBeDefined();expect(Array.isArray(result.results)).toBe(true);expect(result.results.length).toBeGreaterThan(0);- expect(result.metadata).toBeDefined();- expect(typeof result.metadata.authentication).toBe("string");});});