Merge pull request #143 from upstash/feat/improve-library-id-fetching

feat: increase default minimum tokens, improve library search
This commit is contained in:
Enes Akar 2025-05-02 08:46:33 -07:00 committed by GitHub
commit db9d37c5bc
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
12 changed files with 52 additions and 26 deletions

View File

@ -207,7 +207,7 @@ If you prefer to run the MCP server in a Docker container:
docker build -t context7-mcp .
```
2. **Configure Your MCP Client:**
2. **Configure Your MCP Client:**
Update your MCP client's configuration to use the Docker command.
@ -227,13 +227,15 @@ If you prefer to run the MCP server in a Docker container:
}
}
```
*Note: This is an example configuration. Please refer to the specific examples for your MCP client (like Cursor, VS Code, etc.) earlier in this README to adapt the structure (e.g., `mcpServers` vs `servers`). Also, ensure the image name in `args` matches the tag used during the `docker build` command.*
### Environment Variables
- `DEFAULT_MINIMUM_TOKENS`: Set the minimum token count for documentation retrieval (default: 5000).
- `DEFAULT_MINIMUM_TOKENS`: Set the minimum token count for documentation retrieval (default: 10000).
Examples:
```json
{
"mcpServers": {
@ -255,7 +257,7 @@ Examples:
- `get-library-docs`: Fetches documentation for a library using a Context7-compatible library ID.
- `context7CompatibleLibraryID` (required)
- `topic` (optional): Focus the docs on a specific topic (e.g., "routing", "hooks")
- `tokens` (optional, default 5000): Max number of tokens to return. Values less than the configured `DEFAULT_MINIMUM_TOKENS` value are automatically increased to that value.
- `tokens` (optional, default 10000): Max number of tokens to return. Values less than the configured `DEFAULT_MINIMUM_TOKENS` value or the default value of 10000 are automatically increased to that value.
## Development
@ -339,6 +341,7 @@ If you encounter an error like: `Error: Cannot find module 'uriTemplate.js'` try
4. Make sure you are using Node v18 or higher to have native fetch support with `npx`.
## Disclaimer
Context7 projects are community-contributed and while we strive to maintain high quality, we cannot guarantee the accuracy, completeness, or security of all library documentation. Projects listed in Context7 are developed and maintained by their respective owners, not by Context7. If you encounter any suspicious, inappropriate, or potentially harmful content, please use the "Report" button on the project page to notify us immediately. We take all reports seriously and will review flagged content promptly to maintain the integrity and safety of our platform. By using Context7, you acknowledge that you do so at your own discretion and risk.
## Context7 In Media
@ -349,6 +352,8 @@ Context7 projects are community-contributed and while we strive to maintain high
- [Julian Goldie SEO: "Context7: New MCP AI Agent Update"](https://www.youtube.com/watch?v=CTZm6fBYisc)
- [JeredBlu: "Context 7 MCP: Get Documentation Instantly + VS Code Setup"](https://www.youtube.com/watch?v=-ls0D-rtET4)
- [Income stream surfers: "Context7: The New MCP Server That Will CHANGE AI Coding"](https://www.youtube.com/watch?v=PS-2Azb-C3M)
- [AICodeKing: "Context7 + Cline & RooCode: This MCP Server Makes CLINE 100X MORE EFFECTIVE!"](https://www.youtube.com/watch?v=qZfENAPMnyo)
- [Sean Kochel: "5 MCP Servers For Vibe Coding Glory (Just Plug-In & Go)"](https://www.youtube.com/watch?v=LqTQi8qexJM)
## Star History

View File

@ -234,7 +234,7 @@ Wenn du den MCP-Server lieber in einem Docker-Container ausführen möchtest:
- `get-library-docs`: Ruft die Dokumentation für eine Bibliothek mit einer Context7-kompatiblen Bibliotheks-ID ab.
- `context7CompatibleLibraryID` (erforderlich)
- `topic` (optional): Fokussiert die Dokumentation auf ein bestimmtes Thema (z.B. "routing", "hooks")
- `tokens` (optional, Standard 5000): Maximale Anzahl von zurückzugebenden Tokens. Werte unter 5000 werden automatisch auf 5000 erhöht.
- `tokens` (optional, Standard 10000): Maximale Anzahl von zurückzugebenden Tokens. Werte unter 10000 werden automatisch auf 10000 erhöht.
## Entwicklung

View File

@ -160,7 +160,7 @@ Añade esto a tu archivo `claude_desktop_config.json` de Claude Desktop. Consult
- `get-library-docs`: Obtiene documentación para una biblioteca utilizando un ID de biblioteca compatible con Context7.
- `context7CompatibleLibraryID` (requerido)
- `topic` (opcional): Enfoca la documentación en un tema específico (p. ej., "routing", "hooks")
- `tokens` (opcional, por defecto 5000): Número máximo de tokens a devolver. Los valores inferiores a 5000 se aumentan automáticamente a 5000.
- `tokens` (opcional, por defecto 10000): Número máximo de tokens a devolver. Los valores inferiores a 10000 se aumentan automáticamente a 10000.
## Desarrollo

View File

@ -234,7 +234,7 @@ Si vous préférez exécuter le serveur MCP dans un conteneur Docker :
- `get-library-docs` : Récupère la documentation dune bibliothèque via un ID Context7.
- `context7CompatibleLibraryID` (obligatoire)
- `topic` (optionnel) : Focaliser la doc sur un sujet précis (ex : "routing", "hooks")
- `tokens` (optionnel, par défaut 5000) : Nombre max de tokens à retourner. Les valeurs < 5000 sont automatiquement augmentées à 5000.
- `tokens` (optionnel, par défaut 10000) : Nombre max de tokens à retourner. Les valeurs < 10000 sont automatiquement augmentées à 10000.
## Développement

View File

@ -238,7 +238,7 @@ Jika Anda lebih suka menjalankan server MCP dalam kontainer Docker:
- `get-library-docs`: Mengambil dokumentasi untuk library menggunakan ID library yang kompatibel dengan Context7.
- `context7CompatibleLibraryID` (wajib)
- `topic` (opsional): Fokuskan dokumentasi pada topik tertentu (misalnya, "routing", "hooks")
- `tokens` (opsional, default 5000): Jumlah maksimum token yang akan dihasilkan. Nilai kurang dari 5000 secara otomatis ditingkatkan menjadi 5000.
- `tokens` (opsional, default 10000): Jumlah maksimum token yang akan dihasilkan. Nilai kurang dari 10000 secara otomatis ditingkatkan menjadi 10000.
## Pengembangan

View File

@ -237,7 +237,7 @@ Se preferisci eseguire il server MCP in un contenitore Docker:
- `get-library-docs`: Recupera la documentazione per una libreria utilizzando un ID di libreria compatibile con Context7.
- `context7CompatibleLibraryID` (obbligatorio)
- `topic` (opzionale): Concentra la documentazione su un argomento specifico (es., "routing", "hooks")
- `tokens` (opzionale, predefinito 5000): Numero massimo di token da restituire. I valori inferiori a 5000 vengono automaticamente aumentati a 5000.
- `tokens` (opzionale, predefinito 10000): Numero massimo di token da restituire. I valori inferiori a 10000 vengono automaticamente aumentati a 10000.
## Sviluppo

View File

@ -156,7 +156,7 @@ Claude Desktop의 `claude_desktop_config.json` 파일에 다음을 추가하세
- `get-library-docs`: Context7이 인식하는 라이브러리 ID를 사용하여 해당 라이브러리의 문서를 가져옵니다.
- `context7CompatibleLibraryID` (필수)
- `topic` (선택): 특정 주제의 문서만 가져오기 (예: "routing", "hooks")
- `tokens` (선택, 기본값 5000): 가져올 문서의 최대 토큰 수. 5000 미만으로 설정하면 자동으로 5000으로 조정됨
- `tokens` (선택, 기본값 10000): 가져올 문서의 최대 토큰 수. 10000 미만으로 설정하면 자동으로 10000으로 조정됨
## 개발

View File

@ -237,7 +237,7 @@ Se você preferir executar o servidor MCP em um contêiner Docker:
- `get-library-docs`: Busca documentação para uma biblioteca usando um ID de biblioteca compatível com Context7.
- `context7CompatibleLibraryID` (obrigatório)
- `topic` (opcional): Concentra a documentação em um tópico específico (por exemplo, "routing", "hooks")
- `tokens` (opcional, padrão 5000): Número máximo de tokens a retornar. Valores menores que 5000 são automaticamente aumentados para 5000.
- `tokens` (opcional, padrão 10000): Número máximo de tokens a retornar. Valores menores que 10000 são automaticamente aumentados para 10000.
## Desenvolvimento

View File

@ -216,7 +216,7 @@ claude mcp add context7 -- npx -y @upstash/context7-mcp@latest
- `get-library-docs`: 使用Context7兼容的库ID获取库的文档。
- `context7CompatibleLibraryID` (必需)
- `topic` (可选): 将文档集中在特定主题上(例如"routing"、"hooks"
- `tokens` (可选,默认5000): 返回的最大令牌数。小于5000的值会自动增加到5000。
- `tokens` (可选,默认10000): 返回的最大令牌数。小于10000的值会自动增加到10000。
## 开发

View File

@ -11,14 +11,14 @@ import dotenv from "dotenv";
dotenv.config();
// Get DEFAULT_MINIMUM_TOKENS from environment variable or use default
let DEFAULT_MINIMUM_TOKENS = 5000;
let DEFAULT_MINIMUM_TOKENS = 10000;
if (process.env.DEFAULT_MINIMUM_TOKENS) {
const parsedValue = parseInt(process.env.DEFAULT_MINIMUM_TOKENS, 10);
if (!isNaN(parsedValue) && parsedValue > 0) {
DEFAULT_MINIMUM_TOKENS = parsedValue;
} else {
console.error(
`Warning: Invalid DEFAULT_MINIMUM_TOKENS value provided in environment variable. Using default value of 5000`
console.warn(
`Warning: Invalid DEFAULT_MINIMUM_TOKENS value provided in environment variable. Using default value of 10000`
);
}
}
@ -37,7 +37,17 @@ const server = new McpServer({
// Register Context7 tools
server.tool(
"resolve-library-id",
"Required first step: Resolves a general package name into a Context7-compatible library ID. Must be called before using 'get-library-docs' to retrieve a valid Context7-compatible library ID.",
`Resolves a package name to a Context7-compatible library ID and returns a list of matching libraries.
You MUST call this function before 'get-library-docs' to obtain a valid Context7-compatible library ID.
When selecting the best match, consider:
- Name similarity to the query
- Description relevance
- Code Snippet count (documentation coverage)
- GitHub Stars (popularity)
Return the selected library ID and explain your choice. If there are multiple good matches, mention this but proceed with the most relevant one.`,
{
libraryName: z
.string()
@ -74,7 +84,20 @@ server.tool(
content: [
{
type: "text",
text: "Available libraries and their Context7-compatible library IDs:\n\n" + resultsText,
text: `Available Libraries (top matches):
Each result includes:
- Library ID: Context7-compatible identifier (format: /org/repo)
- Name: Library or package name
- Description: Short summary
- Code Snippets: Number of available code examples
- GitHub Stars: Popularity indicator
For best results, select libraries based on name match, popularity (stars), snippet coverage, and relevance to your use case.
---
${resultsText}`,
},
],
};

View File

@ -8,6 +8,7 @@ export interface SearchResult {
totalTokens: number;
totalSnippets: number;
totalPages: number;
stars: number;
}
export interface SearchResponse {
@ -15,11 +16,4 @@ export interface SearchResponse {
}
// Version state is still needed for validating search results
export type DocumentState =
| "initial"
| "parsed"
| "finalized"
| "invalid_docs"
| "error"
| "stop"
| "delete";
export type DocumentState = "initial" | "finalized" | "error" | "delete";

View File

@ -6,7 +6,11 @@ import { SearchResponse, SearchResult } from "./types.js";
* @returns Formatted search result string
*/
export function formatSearchResult(result: SearchResult): string {
return `Title: ${result.title}\n\nContext7-compatible library ID: ${result.id}\n\nDescription: ${result.description}`;
return `- Title: ${result.title}
- Context7-compatible library ID: ${result.id}
- Description: ${result.description}
- Code Snippets: ${result.totalSnippets}
- GitHub Stars: ${result.stars}`;
}
/**
@ -20,5 +24,5 @@ export function formatSearchResults(searchResponse: SearchResponse): string {
}
const formattedResults = searchResponse.results.map(formatSearchResult);
return formattedResults.join("\n\n--------------------\n");
return formattedResults.join("\n---\n");
}