Context7 Platform -- Up-to-date docs for AI agents
feat: migrate to v1 API, remove reranking on client, bump version
Abdusshh23e3c8ab16f7
diff --git a/package.json b/package.jsonindex 630e6144..05c374e3 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "@upstash/context7-mcp",- "version": "1.0.0",+ "version": "1.0.4","description": "MCP server for Context7","scripts": {"test": "echo \"Error: no test specified\" && exit 1",diff --git a/src/index.ts b/src/index.tsindex 6d9aa4e4..18c6c97f 100644--- a/src/index.ts+++ b/src/index.ts@@ -3,14 +3,16 @@import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";import { z } from "zod";-import { fetchProjects, fetchLibraryDocumentation } from "./lib/api.js";-import { formatProjectsList, rerankProjects } from "./lib/utils.js";+import { searchLibraries, fetchLibraryDocumentation } from "./lib/api.js";+import { formatSearchResults } from "./lib/utils.js";++const DEFAULT_MINIMUM_TOKENS = 5000;// Create server instanceconst server = new McpServer({name: "Context7",description: "Retrieves up-to-date documentation and code examples for any library.",- version: "1.0.0",+ version: "1.0.4",capabilities: {resources: {},tools: {},@@ -28,9 +30,9 @@ server.tool(.describe("Optional library name to search for and rerank results based on."),},async ({ libraryName }) => {- const projects = await fetchProjects();+ const searchResponse = await searchLibraries(libraryName || "");- if (!projects) {+ if (!searchResponse || !searchResponse.results) {return {content: [{@@ -41,32 +43,24 @@ server.tool(};}- // Filter projects to only include those with state "finalized"- const finalizedProjects = projects.filter((project) => project.version.state === "finalized");-- if (finalizedProjects.length === 0) {+ if (searchResponse.results.length === 0) {return {content: [{type: "text",- text: "No finalized documentation libraries available",+ text: "No documentation libraries available",},],};}- // Rerank projects if a library name is provided- const rankedProjects = libraryName- ? rerankProjects(finalizedProjects, libraryName)- : finalizedProjects;-- const projectsText = formatProjectsList(rankedProjects);+ const resultsText = formatSearchResults(searchResponse);return {content: [{type: "text",- text: "Available libraries and their Context7-compatible library ID:\n\n" + projectsText,+ text: "Available libraries and their Context7-compatible library IDs:\n\n" + resultsText,},],};@@ -88,18 +82,28 @@ server.tool(.describe("Topic to focus documentation on (e.g., 'hooks', 'routing')."),tokens: z.number()- .min(5000)+ .min(DEFAULT_MINIMUM_TOKENS).optional().describe(- "Maximum number of tokens of documentation to retrieve (default: 5000). Higher values provide more context but consume more tokens."+ `Maximum number of tokens of documentation to retrieve (default: ${DEFAULT_MINIMUM_TOKENS}). Higher values provide more context but consume more tokens.`),},- async ({ context7CompatibleLibraryID, tokens = 5000, topic = "" }) => {- const documentationText = await fetchLibraryDocumentation(- context7CompatibleLibraryID,+ async ({ context7CompatibleLibraryID, tokens = DEFAULT_MINIMUM_TOKENS, topic = "" }) => {+ // Extract folders parameter if present in the ID+ let folders = "";+ let libraryId = context7CompatibleLibraryID;++ if (context7CompatibleLibraryID.includes("?folders=")) {+ const [id, foldersParam] = context7CompatibleLibraryID.split("?folders=");+ libraryId = id;+ folders = foldersParam;+ }++ const documentationText = await fetchLibraryDocumentation(libraryId, {tokens,- topic- );+ topic,+ folders,+ });if (!documentationText) {return {diff --git a/src/lib/api.ts b/src/lib/api.tsindex a3e811ff..50e74b6d 100644--- a/src/lib/api.ts+++ b/src/lib/api.ts@@ -1,57 +1,53 @@-import { Project } from "./types.js";+import { SearchResponse } from "./types.js";-const CONTEXT7_BASE_URL = "https://context7.com";+const CONTEXT7_API_BASE_URL = "https://context7.com/api";+const DEFAULT_TYPE = "txt";/**- * Fetches projects from the Context7 API- * @returns Array of projects or null if the request fails+ * Searches for libraries matching the given query+ * @param query The search query+ * @returns Search results or null if the request fails*/-export async function fetchProjects(): Promise<Project[] | null> {+export async function searchLibraries(query: string): Promise<SearchResponse | null> {try {- const response = await fetch(`${CONTEXT7_BASE_URL}/api/libraries`);+ const url = new URL(`${CONTEXT7_API_BASE_URL}/v1/search`);+ url.searchParams.set("query", query);+ const response = await fetch(url);if (!response.ok) {- console.error(`Failed to fetch projects: ${response.status}`);+ console.error(`Failed to search libraries: ${response.status}`);return null;}return await response.json();} catch (error) {- console.error("Error fetching projects:", error);+ console.error("Error searching libraries:", error);return null;}}/*** Fetches documentation context for a specific library- * @param libraryName The library name to fetch documentation for- * @param tokens Number of tokens to retrieve (default: 5000)- * @param topic Optional topic to rerank context for+ * @param libraryId The library ID to fetch documentation for+ * @param options Options for the request* @returns The documentation text or null if the request fails*/export async function fetchLibraryDocumentation(- libraryName: string,- tokens: number = 5000,- topic: string = ""+ libraryId: string,+ options: {+ tokens?: number;+ topic?: string;+ folders?: string;+ } = {}): Promise<string | null> {try {- // if libraryName has a "/" as the first character, remove it- if (libraryName.startsWith("/")) {- libraryName = libraryName.slice(1);+ if (libraryId.startsWith("/")) {+ libraryId = libraryId.slice(1);}-- // Handle folders parameter- let basePath = libraryName;- let folders = "";- if (libraryName.includes("?folders=")) {- const [path, foldersParam] = libraryName.split("?folders=");- basePath = path;- folders = foldersParam;- }- const contextURL = new URL(`${CONTEXT7_BASE_URL}/${basePath}/llms.txt`);- if (folders) contextURL.searchParams.set("folders", folders);- if (tokens) contextURL.searchParams.set("tokens", tokens.toString());- if (topic) contextURL.searchParams.set("topic", topic);-- const response = await fetch(contextURL, {+ const url = new URL(`${CONTEXT7_API_BASE_URL}/v1/${libraryId}`);+ if (options.tokens) url.searchParams.set("tokens", options.tokens.toString());+ if (options.topic) url.searchParams.set("topic", options.topic);+ if (options.folders) url.searchParams.set("folders", options.folders);+ url.searchParams.set("type", DEFAULT_TYPE);+ const response = await fetch(url, {headers: {"X-Context7-Source": "mcp-server",},diff --git a/src/lib/types.ts b/src/lib/types.tsindex ceb9bc71..6b7f0b55 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -1,36 +1,24 @@-export interface ProjectSettings {+export interface SearchResult {+ id: string;title: string;- project: string;- folders: string[];- docsRepoUrl: string;-}--export interface Version {+ branch: string;lastUpdate: string;- state: "initial" | "parsed" | "finalized" | "invalid_docs" | "error" | "stop" | "delete";- parseDuration: number;+ state: DocumentState;totalTokens: number;totalSnippets: number;- averageTokens: number;+ totalPages: number;}-export interface Project {- settings: ProjectSettings;- version: Version;+export interface SearchResponse {+ results: SearchResult[];}-export interface CodeListElement {- language: string;- code: string;-}--export interface CodeSnippet {- codeTitle: string;- codeDescription: string;- codeLanguage: string;- codeTokens: number;- codeId: string;- pageTitle: string;- codeList: CodeListElement[];- relavance: number;-}+// Version state is still needed for validating search results+export type DocumentState =+ | "initial"+ | "parsed"+ | "finalized"+ | "invalid_docs"+ | "error"+ | "stop"+ | "delete";diff --git a/src/lib/utils.ts b/src/lib/utils.tsindex 9e44908a..f64fff95 100644--- a/src/lib/utils.ts+++ b/src/lib/utils.ts@@ -1,167 +1,24 @@-import { Project } from "./types.js";+import { SearchResponse, SearchResult } from "./types.js";/**- * Format a project into a string representation- * @param project Project to format- * @returns Formatted project string+ * Format a search result into a string representation+ * @param result SearchResult to format+ * @returns Formatted search result string*/-export function formatProject(project: Project): string {- return `Title: ${project.settings.title}\nContext7-compatible library ID: ${project.settings.project}\n`;+export function formatSearchResult(result: SearchResult): string {+ return `Title: ${result.title}\n\nContext7-compatible library ID: ${result.id}`;}/**- * Format a list of projects into a string representation- * @param projects Projects to format- * @returns Formatted projects string+ * Format search results into a string representation+ * @param searchResponse The search response to format+ * @returns Formatted search results string*/-export function formatProjectsList(projects: Project[]): string {- const formattedProjects = projects.map(formatProject);- return (- formattedProjects.length +- " available documentation libraries:\n\n" +- formattedProjects.join("\n")- );-}--/**- * Rerank projects based on a search term- * @param projects Projects to rerank- * @param searchTerm Search term to rerank by- * @returns Reranked projects- */-export function rerankProjects(projects: Project[], searchTerm: string): Project[] {- if (!searchTerm) return projects;-- // Normalize the search term - remove special characters and convert to lowercase- const normalizedSearchTerm = searchTerm.toLowerCase().replace(/[^\w\s]/g, "");-- return [...projects].sort((a, b) => {- const aTitle = a.settings.title.toLowerCase();- const aProject = a.settings.project.toLowerCase();- const aProjectName = aProject.split("/").pop() || "";- const aProjectPath = aProject.split("/").slice(0, -1).join("/");-- const bTitle = b.settings.title.toLowerCase();- const bProject = b.settings.project.toLowerCase();- const bProjectName = bProject.split("/").pop() || "";- const bProjectPath = bProject.split("/").slice(0, -1).join("/");-- // Normalize project names for better matching - remove special characters- const normalizedATitle = aTitle.replace(/[^\w\s]/g, "");- const normalizedAProject = aProject.replace(/[^\w\s]/g, "");- const normalizedAProjectName = aProjectName.replace(/[^\w\s]/g, "");-- const normalizedBTitle = bTitle.replace(/[^\w\s]/g, "");- const normalizedBProject = bProject.replace(/[^\w\s]/g, "");- const normalizedBProjectName = bProjectName.replace(/[^\w\s]/g, "");-- // Calculate match scores for better ranking- const aScore = calculateMatchScore(normalizedSearchTerm, {- original: {- title: aTitle,- project: aProject,- projectName: aProjectName,- projectPath: aProjectPath,- },- normalized: {- title: normalizedATitle,- project: normalizedAProject,- projectName: normalizedAProjectName,- },- });-- const bScore = calculateMatchScore(normalizedSearchTerm, {- original: {- title: bTitle,- project: bProject,- projectName: bProjectName,- projectPath: bProjectPath,- },- normalized: {- title: normalizedBTitle,- project: normalizedBProject,- projectName: normalizedBProjectName,- },- });-- // Higher score first- if (aScore !== bScore) {- return bScore - aScore;- }-- // Default to alphabetical by project name- return aProject.localeCompare(bProject);- });-}--/**- * Calculate a match score for ranking- * Higher score means better match- */-function calculateMatchScore(- searchTerm: string,- projectData: {- original: { title: string; project: string; projectName: string; projectPath: string };- normalized: { title: string; project: string; projectName: string };- }-): number {- const { original, normalized } = projectData;- let score = 0;-- // Exact matches (highest priority)- if (- original.project === searchTerm ||- original.title === searchTerm ||- original.projectName === searchTerm- ) {- score += 100;- }-- // Normalized exact matches- if (- normalized.project === searchTerm ||- normalized.title === searchTerm ||- normalized.projectName === searchTerm- ) {- score += 90;- }-- // Starts with matches- if (- original.project.startsWith(searchTerm) ||- original.title.startsWith(searchTerm) ||- original.projectName.startsWith(searchTerm)- ) {- score += 80;- }-- // Normalized starts with matches- if (- normalized.project.startsWith(searchTerm) ||- normalized.title.startsWith(searchTerm) ||- normalized.projectName.startsWith(searchTerm)- ) {- score += 70;- }-- // Contains matches- if (- original.project.includes(searchTerm) ||- original.title.includes(searchTerm) ||- original.projectName.includes(searchTerm) ||- original.projectPath.includes(searchTerm)- ) {- score += 60;- }-- // Normalized contains matches- if (- normalized.project.includes(searchTerm) ||- normalized.title.includes(searchTerm) ||- normalized.projectName.includes(searchTerm)- ) {- score += 50;+export function formatSearchResults(searchResponse: SearchResponse): string {+ if (!searchResponse.results || searchResponse.results.length === 0) {+ return "No documentation libraries found matching your query.";}- return score;+ const formattedResults = searchResponse.results.map(formatSearchResult);+ return formattedResults.join("\n\n");}