feat: improve error handling and response types for library search and documentation fetch

This commit is contained in:
Abdusshh 2025-06-07 00:20:52 +03:00
parent 2f74fa3893
commit a7b11bbee7
3 changed files with 37 additions and 25 deletions

View File

@ -5,6 +5,7 @@ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js"
import { z } from "zod"; import { z } from "zod";
import { searchLibraries, fetchLibraryDocumentation } from "./lib/api.js"; import { searchLibraries, fetchLibraryDocumentation } from "./lib/api.js";
import { formatSearchResults } from "./lib/utils.js"; import { formatSearchResults } from "./lib/utils.js";
import { SearchResponse } from "./lib/types.js";
import dotenv from "dotenv"; import dotenv from "dotenv";
import { createServer } from "http"; import { createServer } from "http";
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
@ -70,25 +71,16 @@ For ambiguous queries, request clarification before proceeding with a best-guess
.describe("Library name to search for and retrieve a Context7-compatible library ID."), .describe("Library name to search for and retrieve a Context7-compatible library ID."),
}, },
async ({ libraryName }) => { async ({ libraryName }) => {
const searchResponse = await searchLibraries(libraryName); const searchResponse: SearchResponse = await searchLibraries(libraryName);
if (!searchResponse || !searchResponse.results) { if (!searchResponse.results || searchResponse.results.length === 0) {
return { return {
content: [ content: [
{ {
type: "text", type: "text",
text: "Failed to retrieve library documentation data from Context7", text: searchResponse.error
}, ? searchResponse.error
], : "Failed to retrieve library documentation data from Context7",
};
}
if (searchResponse.results.length === 0) {
return {
content: [
{
type: "text",
text: "No documentation libraries available",
}, },
], ],
}; };
@ -143,12 +135,12 @@ ${resultsText}`,
), ),
}, },
async ({ context7CompatibleLibraryID, tokens = DEFAULT_MINIMUM_TOKENS, topic = "" }) => { async ({ context7CompatibleLibraryID, tokens = DEFAULT_MINIMUM_TOKENS, topic = "" }) => {
const documentationText = await fetchLibraryDocumentation(context7CompatibleLibraryID, { const fetchDocsResponse = await fetchLibraryDocumentation(context7CompatibleLibraryID, {
tokens, tokens,
topic, topic,
}); });
if (!documentationText) { if (!fetchDocsResponse) {
return { return {
content: [ content: [
{ {
@ -163,7 +155,7 @@ ${resultsText}`,
content: [ content: [
{ {
type: "text", type: "text",
text: documentationText, text: fetchDocsResponse,
}, },
], ],
}; };

View File

@ -8,19 +8,30 @@ const DEFAULT_TYPE = "txt";
* @param query The search query * @param query The search query
* @returns Search results or null if the request fails * @returns Search results or null if the request fails
*/ */
export async function searchLibraries(query: string): Promise<SearchResponse | null> { export async function searchLibraries(query: string): Promise<SearchResponse> {
try { try {
const url = new URL(`${CONTEXT7_API_BASE_URL}/v1/search`); const url = new URL(`${CONTEXT7_API_BASE_URL}/v1/search`);
url.searchParams.set("query", query); url.searchParams.set("query", query);
const response = await fetch(url); const response = await fetch(url);
if (!response.ok) { if (!response.ok) {
console.error(`Failed to search libraries: ${response.status}`); const errorCode = response.status;
return null; if (errorCode === 429) {
console.error(`Rate limited due to too many requests. Please try again later.`);
return {
results: [],
error: `Rate limited due to too many requests. Please try again later.`,
} as SearchResponse;
}
console.error(`Failed to search libraries. Please try again later. Error code: ${errorCode}`);
return {
results: [],
error: `Failed to search libraries. Please try again later. Error code: ${errorCode}`,
} as SearchResponse;
} }
return await response.json(); return await response.json();
} catch (error) { } catch (error) {
console.error("Error searching libraries:", error); console.error("Error searching libraries:", error);
return null; return { results: [], error: `Error searching libraries: ${error}` } as SearchResponse;
} }
} }
@ -51,8 +62,15 @@ export async function fetchLibraryDocumentation(
}, },
}); });
if (!response.ok) { if (!response.ok) {
console.error(`Failed to fetch documentation: ${response.status}`); const errorCode = response.status;
return null; if (errorCode === 429) {
const errorMessage = `Rate limited due to too many requests. Please try again later.`;
console.error(errorMessage);
return errorMessage;
}
const errorMessage = `Failed to fetch documentation. Please try again later. Error code: ${errorCode}`;
console.error(errorMessage);
return errorMessage;
} }
const text = await response.text(); const text = await response.text();
if (!text || text === "No content available" || text === "No context data available") { if (!text || text === "No content available" || text === "No context data available") {
@ -60,7 +78,8 @@ export async function fetchLibraryDocumentation(
} }
return text; return text;
} catch (error) { } catch (error) {
console.error("Error fetching library documentation:", error); const errorMessage = `Error fetching library documentation. Please try again later. ${error}`;
return null; console.error(errorMessage);
return errorMessage;
} }
} }

View File

@ -14,6 +14,7 @@ export interface SearchResult {
} }
export interface SearchResponse { export interface SearchResponse {
error?: string;
results: SearchResult[]; results: SearchResult[];
} }