### Generate MCP Server Installation Guide from GitHub (TypeScript) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Generates comprehensive installation guides by extracting README content from GitHub repositories. The service automatically detects installation patterns, formats instructions for MCP-specific configurations, and provides fallback guidance if the README is unavailable. ```typescript import { InstallationGuideService } from './services/core/installation/installationGuideService.js'; const installService = new InstallationGuideService(); // Generate installation guide from GitHub repository const guide = await installService.generateInstallationGuide( 'https://github.com/example/mcp-server', 'example-mcp' ); // Returns formatted installation guide with steps: console.log(guide); // "我将指导你如何安装和配置 example-mcp MCP 服务器。 // // GitHub 仓库地址:https://github.com/example/mcp-server // // ## 安装步骤 // // 1. **克隆仓库**: // ```bash // git clone https://github.com/example/mcp-server // ``` // // 2. **进入项目目录**: // ```bash // cd mcp-server // ``` // ... (continues with installation steps)" ``` -------------------------------- ### Example Usage - Install MCP Server Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Shows a natural language prompt used by a user to install a discovered MCP server, highlighting the ease of integration for end-users. ```text Install this MCP: https://github.com/Deepractice/PromptX ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Installs all necessary dependencies for the project using pnpm. This is a standard step in setting up the development environment. ```bash pnpm install ``` -------------------------------- ### Replace hardcoded Chinese assertion with flexible content check Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/bugfix/issue-16-test-failures-fix.md Updates the unit test to verify that the generated installation guide contains any relevant installation instructions, supporting multiple languages and fallback scenarios. Removes reliance on a specific Chinese phrase. ```TypeScript // Before (incorrect)\nexpect(guide).toContain('克隆仓库');\n\n// After (flexible and correct)\nconst hasInstallationContent = \n guide.includes('克隆仓库') || // Chinese fallback scenario\n guide.includes('git clone') || // English git command\n guide.includes('npm install') || // npm install command\n guide.includes('Installation') || // English installation heading\n guide.includes('Setup') || // Setup heading\n guide.includes('Getting Started') || // Getting started heading\n guide.includes('配置') || // Chinese configuration\n guide.includes('Config'); // English configuration\n\nexpect(hasInstallationContent).toBe(true); ``` -------------------------------- ### Install MCP Advisor with Smithery CLI Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Installs the Advisor for Claude Desktop automatically using the Smithery CLI. This is the primary method for automated installation. ```bash npx -y @smithery/cli install @istarwyh/mcpadvisor --client claude ``` -------------------------------- ### Start Local Meilisearch Instance Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Starts a local Meilisearch instance to improve recommendation quality. This command bootstraps the 'mcp_servers' index and persists environment variables. ```bash pnpm meilisearch:start ``` -------------------------------- ### Install MCP Advisor with NPM Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md This snippet shows how to install the MCP Advisor package using npm. It's a direct command-line installation for integrating the service into an AI assistant's MCP configuration. ```json { "mcpServers": { "mcpadvisor": { "command": "npx", "args": ["-y", "@xiaohui-wang/mcpadvisor"] } } } ``` -------------------------------- ### Start Meilisearch with Config File or Environment Variables (Bash) Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202507/meilisearch-self-hosted-integration.md This snippet shows two methods for starting the Meilisearch service. The first method uses a configuration file path with the `--config-file-path` argument. The second method demonstrates setting various Meilisearch parameters as environment variables, such as master key, environment type, database path, HTTP address, log level, and memory/thread limits, before starting the `meilisearch` binary. ```bash # Directly start meilisearch --config-file-path ./meilisearch.toml # Or use environment variables export MEILI_MASTER_KEY="your-secure-master-key-here" export MEILI_ENV="development" export MEILI_DB_PATH="./meili_data" export MEILI_HTTP_ADDR="0.0.0.0:7700" export MEILI_LOG_LEVEL="INFO" export MEILI_MAX_INDEXING_MEMORY="100MB" export MEILI_MAX_INDEXING_THREADS="2" meilisearch ``` -------------------------------- ### Build the Project Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Compiles and builds the project. This command should be run after installing dependencies and before running the application or tests. ```bash pnpm run build ``` -------------------------------- ### Manage MCP Server Lifecycle with Transport Options (TypeScript) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Manages the lifecycle of MCP servers and handles tool requests for server recommendations and installations. Supports starting the server with different transport types like stdio (default for CLI) and SSE (for web integration), with configurable transport settings. ```typescript import { ServerService, TransportType, TransportConfig } from './services/core/server/index.js'; import { SearchService } from './services/searchService.js'; // Initialize server with search service const searchService = new SearchService([]); const serverService = new ServerService(searchService); // Start with stdio transport (default for CLI) await serverService.start(TransportType.STDIO); // Start with SSE transport for web integration const sseConfig: TransportConfig = { port: 3000, host: 'localhost', ssePath: '/sse', messagePath: '/messages', endpoint: '/rest' }; await serverService.start(TransportType.SSE, sseConfig); // The server exposes two main tools: // 1. recommend-mcp-servers - Find suitable MCP servers // 2. install-mcp-server - Generate installation guides // Example tool request handling (internal): // { // "name": "recommend-mcp-servers", // "arguments": { // "taskDescription": "vector database integration", // "keywords": ["vector", "database"], // "capabilities": ["similarity-search"] // } // } ``` -------------------------------- ### Install Nacos MCP Provider via npm Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Install the Nacos MCP Provider package using npm. This is required to use the provider in your Node.js project. ```bash npm install @xiaohui-wang/mcpadvisor ``` -------------------------------- ### Initialize Nacos MCP Provider programmatically in TypeScript Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Create a new instance of the NacosMcpProvider with configuration options. This allows programmatic setup instead of using environment variables. ```typescript import { NacosMcpProvider } from '@xiaohui-wang/mcpadvisor'; const provider = new NacosMcpProvider({ serverAddr: 'http://localhost:8848', username: 'nacos', password: 'nacos', mcpHost: 'localhost', mcpPort: 3000, authToken: 'your-auth-token', debug: true, // Optional, enables debug logging }); ``` -------------------------------- ### MCPAdvisor CLI Usage (Bash) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Demonstrates various ways to run the MCPAdvisor command-line interface, including default setup, enabling local Meilisearch, and configuring different transport modes (SSE, REST) and ports. Also shows environment variable configuration for services like Meilisearch and Nacos. ```bash # Default stdio transport npx @xiaohui-wang/mcpadvisor # Enable local Meilisearch (auto-start if available) npx @xiaohui-wang/mcpadvisor --local-meilisearch # Start with SSE transport npx @xiaohui-wang/mcpadvisor --mode=sse --port=3000 --host=localhost # Start with REST transport npx @xiaohui-wang/mcpadvisor --mode=rest --port=3000 --endpoint=/rest # Environment variable configuration export MEILISEARCH_INSTANCE=local export MEILISEARCH_LOCAL_HOST=http://localhost:7700 export NACOS_SERVER_ADDR=http://nacos:8848 export NACOS_USERNAME=admin export NACOS_PASSWORD=secret npx @xiaohui-wang/mcpadvisor ``` -------------------------------- ### Example Usage - Natural Language Query Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Demonstrates how to query MCP Advisor using natural language to find relevant MCP servers. This showcases the core functionality of discovering tools based on task descriptions. ```text Find MCP servers for insurance risk analysis ``` -------------------------------- ### Example Usage - Specific Search Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Illustrates a more specific natural language query to find MCP servers with particular capabilities, such as natural language processing. ```text Search for MCP servers with natural language processing capabilities ``` -------------------------------- ### Install Dependencies (Bash) Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202506/nacos-mcp-provider-integration.md Command to install the necessary @xenova/transformers library using npm. This is a prerequisite for using the NacosMcpProvider. ```bash npm install @xenova/transformers ``` -------------------------------- ### Search MCP Servers using TypeScript Library Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Demonstrates how to use the MCP Advisor TypeScript library to search for MCP servers. It involves importing the SearchService, initializing it, performing a search query with a keyword, and logging the results. Requires the '@xiaohui-wang/mcpadvisor' package to be installed. ```typescript import { SearchService } from '@xiaohui-wang/mcpadvisor'; // Initialize search service const searchService = new SearchService(); // Search for MCP servers const results = await searchService.search('vector database integration'); console.log(results); ``` -------------------------------- ### TypeScript Functional Programming Example Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Illustrates functional programming principles in TypeScript, focusing on pure functions and immutability. It shows a good practice example of normalizing a vector and an avoided practice of a function performing multiple operations. ```typescript // Good practice function normalizeVector(vector: number[]): number[] { const magnitude = calculateMagnitude(vector); return vector.map(value => value / magnitude); } // Avoid function processVector(vector: number[]): number[] { // doing multiple things: calculate, normalize, filter, etc. } ``` -------------------------------- ### Configure MCPAdvisor for Local Meilisearch Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md A JSON configuration snippet to enable local Meilisearch automatically when launching MCPAdvisor. This avoids manual environment variable setup. ```json { "mcpServers": { "mcpadvisor": { "command": "npx", "args": ["-y", "@xiaohui-wang/mcpadvisor", "--local-meilisearch"] } } } ``` -------------------------------- ### Pre-commit Hook Troubleshooting Guide Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Provides troubleshooting steps for common issues encountered with pre-commit hooks, including type checking failures, linting errors, and incorrect commit message formats. It suggests specific commands to run for each scenario to resolve the problems. ```bash # Type checking failure pnpm run check pnpm run build git commit -m "fix: Resolve type errors" # Linting failure pnpm run lint:fix git add . git commit -m "style: Fix linting issues" # Commit message format error # Fix the commit message format git commit --amend -m "feat: Add proper commit message" ``` -------------------------------- ### MCP Configuration for Claude Desktop Integration (JSON) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Defines the configuration structure for integrating MCPAdvisor with Claude Desktop and other MCP clients. It specifies commands, arguments, and environment variables for different MCP server setups, including default, local Meilisearch, and Nacos integration. ```json { "mcpServers": { "mcpadvisor": { "command": "npx", "args": ["-y", "@xiaohui-wang/mcpadvisor"] }, "mcpadvisor-with-local-meilisearch": { "command": "npx", "args": ["-y", "@xiaohui-wang/mcpadvisor", "--local-meilisearch"], "env": { "MEILISEARCH_INSTANCE": "local", "MEILISEARCH_LOCAL_HOST": "http://localhost:7700" } }, "mcpadvisor-with-nacos": { "command": "npx", "args": ["-y", "@xiaohui-wang/mcpadvisor"], "env": { "NACOS_SERVER_ADDR": "http://localhost:8848", "NACOS_USERNAME": "nacos", "NACOS_PASSWORD": "nacos", "MCP_HOST": "localhost", "MCP_PORT": "3000" } } } } ``` -------------------------------- ### Run tests for Nacos MCP Provider Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Execute the test suite for the Nacos MCP Provider. You can run all tests or specific test files. ```bash # Run all tests npm test # Run Nacos provider tests only npm test src/services/search/__tests__/NacosMcpProvider.test.ts ``` -------------------------------- ### Docker Compose Health Check Configuration Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Provides a sample Docker Compose health check configuration. It uses `curl` to hit a health endpoint, defines intervals, timeouts, retries, and a start period. This ensures that Docker only considers the container healthy after it has successfully started and responded to the health check. ```yaml # Good practice - Health check with proper timeout healthcheck: test: ["CMD", "curl", "-f", "http://localhost:7700/health"] interval: 30s timeout: 10s retries: 3 start_period: 40s ``` -------------------------------- ### Async Testing with Vitest in TypeScript Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Demonstrates a robust test structure for a UserService using Vitest, emphasizing environment isolation with `beforeEach` and `afterEach` to save and restore environment variables. It includes tests for successful user creation and error handling for invalid input, alongside an example of smart waiting in E2E tests. ```typescript import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; // Assume UserService and MockRepository are defined elsewhere interface UserData { name: string; email: string; } interface User { id: string; name: string; } interface Repository { findUser(id: string): Promise; saveUser(user: UserData): Promise; } class UserService { private repository: Repository; constructor(repository: Repository) { this.repository = repository; } async createUser(userData: UserData): Promise { if (!userData.name) { throw new Error('Username cannot be empty'); } // Simulate API key usage const apiKey = process.env.API_KEY; if (!apiKey) { throw new Error('API Key is missing'); } return this.repository.saveUser(userData); } } type MockRepository = { findUser: vi.Mock, saveUser: vi.Mock }; describe('UserService', () => { let service: UserService; let mockRepository: MockRepository; let originalEnvVars: Record = {}; beforeEach(() => { // Save original environment variables originalEnvVars = { API_KEY: process.env.API_KEY, DATABASE_URL: process.env.DATABASE_URL }; mockRepository = { findUser: vi.fn(), saveUser: vi.fn().mockResolvedValue({ id: '1', name: 'Test' }) }; service = new UserService(mockRepository); // Mock environment variables for testing process.env.API_KEY = 'mock-api-key'; }); afterEach(() => { // Restore original environment variables Object.entries(originalEnvVars).forEach(([key, value]) => { if (value === undefined) { delete process.env[key]; } else { process.env[key] = value; } }); }); describe('createUser', () => { it('should successfully create user and return user data', async () => { // Given const userData = { name: 'Test', email: 'test@example.com' }; // When const result = await service.createUser(userData); // Then expect(result).toHaveProperty('id'); expect(mockRepository.saveUser).toHaveBeenCalledWith(expect.objectContaining(userData)); }); it('should throw error when name is empty', async () => { await expect(service.createUser({ name: '', email: 'test@example.com' })) .rejects .toThrow('Username cannot be empty'); }); it('should throw error when API_KEY is not set', async () => { delete process.env.API_KEY; const userData = { name: 'Test', email: 'test@example.com' }; await expect(service.createUser(userData)) .rejects .toThrow('API Key is missing'); }); }); }); // Example: Smart waiting in E2E tests describe('Search functionality', () => { // Mocking Page object for demonstration purposes if not running in a real test environment const mockPage = { getByRole: vi.fn().mockReturnThis(), click: vi.fn().mockResolvedValue(undefined), waitForFunction: vi.fn().mockResolvedValue(undefined), locator: vi.fn().mockReturnThis(), count: vi.fn().mockResolvedValue(5) }; it('should display search results', async () => { await mockPage.getByRole('button', { name: 'Search' }).click(); // Good practice - Wait for content to appear await mockPage.waitForFunction(() => { const content = document.body.textContent || ''; return content.includes('Results:') || content.includes('No results'); }, { timeout: 15000 }); // Verify content quality, not just presence const results = await mockPage.locator('[data-testid="search-results"]').count(); expect(results).toBeGreaterThan(0); }); }); ``` -------------------------------- ### Example JSON Response for MCP Servers Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Illustrates a typical JSON response when querying for MCP servers. The response is an array of objects, where each object contains details about an MCP server, including its title, description, GitHub URL, and a similarity score. This format is used to present search results. ```json [ { "title": "NLP Toolkit", "description": "Comprehensive natural language processing toolkit with sentiment analysis, entity recognition, and text summarization capabilities.", "github_url": "https://github.com/example/nlp-toolkit", "similarity": 0.92 }, { "title": "Text Processor", "description": "Efficient text processing MCP server with multi-language support.", "github_url": "https://github.com/example/text-processor", "similarity": 0.85 } ] ``` -------------------------------- ### Run Comprehensive Tests for MCP Advisor Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Execute all defined tests for the MCP Advisor project, including unit, integration, and end-to-end tests. This involves running specific package manager commands and a shell script for automated end-to-end testing. Ensure all dependencies are installed before running. ```bash # Run all tests pnpm run check && pnpm run test && pnpm run test:e2e # Automated E2E testing script ./scripts/run-e2e-test.sh ``` -------------------------------- ### Vitest and Playwright Test Configuration (TypeScript) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Sets up Vitest for unit and integration testing, including environment configuration and code coverage reporting. Also includes examples for running E2E tests using Playwright to interact with MCP servers via SSE. ```typescript // vitest.config.ts import { defineConfig } from 'vitest/config'; export default defineConfig({ test: { environment: 'node', coverage: { provider: 'v8', reporter: ['text', 'json', 'html'] }, setupFiles: ['./src/tests/setup.ts'] } }); // Running tests // Unit tests import { describe, it, expect, beforeEach, vi } from 'vitest'; describe('SearchService', () => { let searchService: SearchService; beforeEach(() => { searchService = new SearchService([]); }); it('should search across multiple providers', async () => { const results = await searchService.search({ taskDescription: 'test query', keywords: ['test'] }); expect(results).toBeDefined(); expect(Array.isArray(results)).toBe(true); }); }); // Integration tests with real services describe('Meilisearch Integration', () => { it('should connect to local Meilisearch', async () => { const provider = new MeilisearchSearchProvider(); const healthy = await provider.healthCheck(); expect(healthy).toBe(true); }); }); // E2E tests with Playwright import { test, expect } from '@playwright/test'; test('should recommend MCP servers via SSE', async ({ page }) => { await page.goto('http://localhost:3000'); const response = await page.request.post('/sse', { data: { name: 'recommend-mcp-servers', arguments: { taskDescription: 'vector database' } } }); expect(response.ok()).toBeTruthy(); }); ``` -------------------------------- ### Initialize and Search with NacosMcpProvider in TypeScript Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202506/nacos-mcp-provider-integration.md Demonstrates how to instantiate NacosMcpProvider with configuration, initialize the connection, perform a search with task description and keywords, and handle cleanup. Shows proper error handling with try-catch-finally pattern and includes console logging for results and errors. Assumes NacosMcpProvider is installed and Nacos server is accessible. ```typescript import { NacosMcpProvider } from './services/search/NacosMcpProvider'; async function main() { // Initialize the provider const provider = new NacosMcpProvider({ serverAddr: 'http://localhost:8848', username: 'nacos', password: 'nacos', mcpHost: 'localhost', mcpPort: 3000, debug: true }); try { // Initialize the provider await provider.init(); // Perform a search const results = await provider.search({ taskDescription: 'Find MCP servers for data analysis', keywords: ['analytics', 'visualization'] }); console.log('Search results:', results); } catch (error) { console.error('Search failed:', error); } finally { // Clean up await provider.close(); } } main().catch(console.error); ``` -------------------------------- ### Use Nacos MCP Provider with SearchMcpFactory Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Integrate the Nacos MCP Provider with SearchMcpFactory for simplified usage. The factory provides a pre-configured search function. ```typescript import { getSearchFunction } from '@xiaohui-wang/mcpadvisor'; // Using environment variables const search = getSearchFunction('nacos'); // Or with explicit configuration const searchWithConfig = getSearchFunction('nacos', { serverAddr: 'http://localhost:8848', // ... other options }); // Use the search function const results = await search({ taskDescription: 'Find MCP servers', }); ``` -------------------------------- ### Configure Nacos MCP Provider with environment variables Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Set up the required and optional environment variables for the Nacos MCP Provider. These variables configure the connection to Nacos and MCP servers. ```env # Required\nNACOS_SERVER_ADDR=http://localhost:8848\nNACOS_USERNAME=nacos\nNACOS_PASSWORD=nacos\nMCP_HOST=localhost\nMCP_PORT=3000\nMCP_AUTH_TOKEN=your-auth-token\n\n# Optional\nNACOS_DEBUG=true # Enable debug logging ``` -------------------------------- ### Search for MCP servers using Nacos MCP Provider Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Perform a search for MCP servers using either keywords or task description. The provider returns an array of matching MCP servers. ```typescript // Using keywords const results1 = await provider.search({ taskDescription: 'Find MCP servers for testing', keywords: ['test', 'mcp'], }); // Using task description only const results2 = await provider.search({ taskDescription: 'Find MCP servers for testing without keywords', }); ``` -------------------------------- ### Enable debug logging in Nacos MCP Provider Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Configure the Nacos MCP Provider to output debug logs for troubleshooting and development purposes. ```typescript const provider = new NacosMcpProvider({ // ... other options debug: true, }); ``` -------------------------------- ### Error handling with Nacos MCP Provider Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Implement error handling when using the Nacos MCP Provider to catch and log any errors that occur during the search operation. ```typescript try { const results = await provider.search({ taskDescription: 'Find MCP servers', }); console.log('Search results:', results); } catch (error) { console.error('Search failed:', error instanceof Error ? error.message : String(error)); } ``` -------------------------------- ### Docker Compose Environment Variable Enforcement Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Demonstrates how to enforce the presence of environment variables in Docker Compose using the `${VAR:?Error message}` syntax. If `MEILI_MASTER_KEY` is not set in the host environment, the container will fail to start with a helpful error message, ensuring proper configuration. ```yaml # Good practice - Force environment variable environment: MEILI_MASTER_KEY: ${MEILI_MASTER_KEY:?Please set MEILI_MASTER_KEY environment variable} ``` -------------------------------- ### Close Nacos MCP Provider to release resources Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/guides/nacos-provider-integration.md Properly close the Nacos MCP Provider instance to release resources when it is no longer needed. This should be done in a finally block to ensure execution. ```typescript try { // Use the provider... } finally { await provider.close(); } ``` -------------------------------- ### Configuration Management - Environment Settings (TypeScript) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Demonstrates centralized configuration loading for an application, supporting multiple environments and validation. It prioritizes configuration from environment variables, config files, and default values. Dependencies include the 'config' module and a custom 'getMeilisearchConfig' function. ```typescript import config from 'config'; import { getMeilisearchConfig } from './config/meilisearch.js'; // Access configuration values with type safety const meilisearchConfig = getMeilisearchConfig(); console.log(meilisearchConfig); // { // instance: 'cloud' | 'local', // cloudHost: 'https://cloud.meilisearch.io', // cloudApiKey: '***', // localHost: 'http://localhost:7700', // localApiKey: '***', // indexName: 'mcp_servers' // } // Configuration sources (in priority order): // 1. Environment variables (MEILISEARCH_INSTANCE, MEILISEARCH_LOCAL_HOST, etc.) // 2. Config files (config/default.json, config/production.json) // 3. Default values // Use in application if (meilisearchConfig.instance === 'local') { console.log(`Connecting to local Meilisearch at ${meilisearchConfig.localHost}`); } else { console.log(`Connecting to cloud Meilisearch`); } ``` -------------------------------- ### Refactor test to use public generateInstallationGuide method Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/bugfix/issue-16-test-failures-fix.md Modifies the single-repository test to avoid accessing a removed private method and instead uses the service's public generateInstallationGuide function, ensuring compatibility with the refactored architecture. ```TypeScript // Before (trying to access private method)\nconst service = installationGuideService as any;\nconst extractedSection = service.extractInstallationSection(readmeContent);\n\n// After (using public interface)\nconst guide = await installationGuideService.generateInstallationGuide(\n repo.url,\n repo.name,\n); ``` -------------------------------- ### TypeScript Path Handling Utility Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Shows recommended practices for handling file paths in a TypeScript project, emphasizing the use of utility functions and relative paths. It contrasts this with the less maintainable approach of using hardcoded absolute paths. ```typescript // Good practice import { getMcpServerListPath } from '../utils/pathUtils.js'; const dataPath = getMcpServerListPath(import.meta.url); // Avoid const dataPath = path.resolve(__dirname, '../../../../data/file.json'); ``` -------------------------------- ### Initialize Meilisearch Index and Load Data (TypeScript) Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202507/meilisearch-self-hosted-integration.md This TypeScript code defines a Command pattern for initializing a Meilisearch index. It includes `InitializeIndexCommand` to create an index, configure searchable, displayed, sortable, and filterable attributes, and load initial documents. A `CommandManager` is provided to execute commands and handle undo operations. Dependencies include a `MeilisearchClient` and a `DataLoader` class. ```typescript // Data Loader with Command Pattern interface Command { execute(): Promise; undo(): Promise; } class InitializeIndexCommand implements Command { constructor( private client: MeilisearchClient, private config: MeilisearchInstanceConfig ) {} async execute(): Promise { // Create index await this.client.createIndex(this.config.indexName, { primaryKey: 'id' }); // Configure search attributes await this.configureSearchAttributes(); // Load initial data await this.loadInitialData(); } async undo(): Promise { await this.client.deleteIndex(this.config.indexName); } private async configureSearchAttributes(): Promise { const index = this.client.index(this.config.indexName); await Promise.all([ index.updateSearchableAttributes([ 'title', 'description', 'categories', 'tags', 'github_url' ]), index.updateDisplayedAttributes([ 'id', 'title', 'description', 'github_url', 'categories', 'tags', 'installations' ]), index.updateSortableAttributes(['title']), index.updateFilterableAttributes(['categories', 'tags']) ]); } private async loadInitialData(): Promise { const dataLoader = new DataLoader(); const mcpData = await dataLoader.loadMCPData(); const documents = this.transformData(mcpData); const index = this.client.index(this.config.indexName); const task = await index.addDocuments(documents); await this.client.waitForTask(task.taskUid); } private transformData(data: any): any[] { return Object.entries(data).map(([id, server]: [string, any]) => ({ id, title: server.display_name, description: server.description, github_url: server.repository.url, categories: server.categories.join(','), tags: server.tags.join(','), installations: server.installations })); } } // Command Manager class CommandManager { private commands: Command[] = []; async executeCommand(command: Command): Promise { await command.execute(); this.commands.push(command); } async undoLastCommand(): Promise { const command = this.commands.pop(); if (command) { await command.undo(); } } async undoAllCommands(): Promise { while (this.commands.length > 0) { await this.undoLastCommand(); } } } ``` -------------------------------- ### Source Meilisearch Environment Variables Source: https://github.com/istarwyh/mcpadvisor/blob/main/README.md Loads Meilisearch environment variables into the current shell session. This is necessary if you are manually managing the Meilisearch instance. ```bash source ~/.meilisearch/env ``` -------------------------------- ### Vitest Integration Tests for Local Meilisearch Provider (TypeScript) Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202507/meilisearch-self-hosted-integration.md These Vitest integration tests verify the functionality of the local Meilisearch provider. They cover setting up a local Meilisearch instance, performing searches, checking the health status, and adding documents. Dependencies include Vitest, TestEnvironment, LocalMeilisearchController, and MeilisearchConfigManager. ```typescript // src/tests/integration/providers/meilisearch-local.test.ts import { describe, it, expect, beforeAll, afterAll } from 'vitest'; import { TestEnvironment } from '../../setup/test-environment.js'; import { LocalMeilisearchController } from '../../../services/providers/meilisearch/localController.js'; import { MeilisearchConfigManager } from '../../../config/meilisearch.js'; describe('Local Meilisearch Provider Integration', () => { let controller: LocalMeilisearchController; let testConfig: any; beforeAll(async () => { // Setup test Meilisearch instance using existing TestEnvironment const { host, masterKey } = await TestEnvironment.setupMeilisearch(); await TestEnvironment.loadTestData(host, masterKey); testConfig = { type: 'local', host, masterKey, indexName: 'mcp_servers_test' }; controller = new LocalMeilisearchController(testConfig); }, 60000); afterAll(async () => { await TestEnvironment.teardownMeilisearch(); }); it('should perform basic search with local controller', async () => { const results = await controller.search('file management'); expect(results).toBeDefined(); expect(results.hits).toBeInstanceOf(Array); expect(results.hits.length).toBeGreaterThan(0); }); it('should pass health check for local instance', async () => { const isHealthy = await controller.healthCheck(); expect(isHealthy).toBe(true); }); it('should handle document addition for local instance', async () => { const testDoc = { id: 'test-new-doc', title: 'Test Document', description: 'A test document for verification' }; const task = await controller.addDocuments([testDoc]); expect(task).toBeDefined(); expect(task.taskUid).toBeDefined(); }); }); ``` -------------------------------- ### Meilisearch Search Provider - Full-Text Search (TypeScript) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Integrates with Meilisearch for high-performance full-text search, featuring automatic failover and result caching. It uses a custom fetcher and memory cache. The search function returns results with similarity scores converted from Meilisearch's ranking scores. Dependencies include 'MeilisearchSearchProvider', 'GetMcpResourceFetcher', and 'MemoryCache'. ```typescript import { MeilisearchSearchProvider } from './services/core/search/MeilisearchSearchProvider.js'; import { GetMcpResourceFetcher } from './services/common/api/getMcpResourceFetcher.js'; import { MemoryCache } from './services/common/cache/memoryCache.js'; // Initialize with custom fetcher and cache const fetcher = new GetMcpResourceFetcher('https://api.getmcp.io/resources'); const cache = new MemoryCache(3600000); // 1 hour TTL const meilisearchProvider = new MeilisearchSearchProvider( fetcher, cache ); // Search automatically loads data and performs search const results = await meilisearchProvider.search({ taskDescription: 'document summarization tools', keywords: ['nlp', 'summarization'] }); // Provider features: // - Automatic failover between cloud and local instances // - Result caching with configurable TTL // - Ranking score conversion to similarity // - Health check monitoring // Check provider health const isHealthy = await meilisearchProvider.healthCheck(); console.log(`Provider health: ${isHealthy}`); // Results include Meilisearch ranking scores console.log(results); // [ // { // id: "doc-summary-mcp", // title: "Document Summarizer", // description: "AI-powered document summarization", // sourceUrl: "https://github.com/example/doc-summary", // similarity: 0.78, // Converted from _rankingScore // installations: { npm: "npm install doc-summary-mcp" } // } // ] ``` -------------------------------- ### Offline Search Provider - Hybrid Search (TypeScript) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Implements an offline search provider using an in-memory vector database with a hybrid search strategy. It combines vector similarity and text matching with weighted scoring for intelligent prioritization. Dependencies include the 'OfflineSearchProvider' class. ```typescript import { OfflineSearchProvider } from './services/core/search/OfflineSearchProvider.js'; // Configure offline provider with custom settings const offlineProvider = new OfflineSearchProvider({ fallbackDataPath: './data/mcp_server_list.json', // Custom data path minSimilarity: 0.1, // Lower threshold for higher recall textMatchWeight: 0.7, // Text matching weight vectorSearchWeight: 0.3 // Vector search weight }); // Search executes hybrid strategy const results = await offlineProvider.search({ taskDescription: '小红书热点分析', keywords: ['xiaohongshu', 'social-media'], capabilities: ['trend-analysis'] }); // Hybrid search combines: // 1. Vector similarity search using text embeddings // 2. Text matching with keyword detection // 3. Weighted score merging // 4. Smart prioritization for keyword matches console.log(results); // [ // { // id: "rednote-mcp", // title: "小红书 MCP Server", // description: "小红书热点追踪和分析工具", // sourceUrl: "https://github.com/example/rednote-mcp", // similarity: 0.85, // source: "offline" // } // ] ``` -------------------------------- ### Search MCP Servers with Multiple Providers (TypeScript) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Orchestrates searches across various providers (Meilisearch, Compass, GetMCP) to find MCP servers based on natural language queries and structured parameters. It supports enabling offline fallback and setting a minimum similarity threshold for results. ```typescript import { SearchService } from '@xiaohui-wang/mcpadvisor'; import { MeilisearchSearchProvider } from './services/core/search/MeilisearchSearchProvider.js'; import { CompassSearchProvider } from './services/core/search/CompassSearchProvider.js'; import { GetMcpSearchProvider } from './services/core/search/GetMcpSearchProvider.js'; // Initialize search service with multiple providers const searchProviders = [ new MeilisearchSearchProvider(), new CompassSearchProvider(), new GetMcpSearchProvider() ]; const searchService = new SearchService(searchProviders, { enabled: true, // Enable offline fallback minSimilarity: 0.3 // Minimum similarity threshold }); // Search with structured parameters const results = await searchService.search({ taskDescription: 'Find MCP servers for natural language processing', keywords: ['nlp', 'text-processing'], capabilities: ['sentiment-analysis', 'entity-recognition'] }); // Results include server metadata with similarity scores console.log(results); // [ // { // id: "nlp-toolkit", // title: "NLP Toolkit", // description: "Comprehensive NLP toolkit with sentiment analysis...", // sourceUrl: "https://github.com/example/nlp-toolkit", // similarity: 0.92, // score: 0.92, // categories: ["natural-language", "text-processing"], // tags: ["nlp", "sentiment", "entities"] // } // ] ``` -------------------------------- ### NacosMcpProvider Class Implementation (TypeScript) Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202506/nacos-mcp-provider-integration.md The NacosMcpProvider class implements the SearchProvider interface, handling asynchronous initialization, vector database integration, and fallback search. It manages Nacos client connections and MCP synchronization. Dependencies include NacosClient, VectorDB, and McpManager. ```typescript class NacosMcpProvider implements SearchProvider { private readonly config: NacosMcpProviderConfig; private readonly nacosClient: NacosClient; private vectorDB: VectorDB | null = null; private mcpManager: McpManager | null = null; private isInitialized = false; constructor( config: NacosMcpProviderConfig, private readonly testMode: boolean = false ) { this.config = { minSimilarity: 0.3, limit: 10, debug: false, mcpHost: 'localhost', ...config }; this.nacosClient = new NacosClient({ serverAddr: this.config.serverAddr, username: this.config.username, password: this.config.password, mcpHost: this.config.mcpHost, mcpPort: this.config.mcpPort, authToken: this.config.authToken }); } async init(): Promise { if (this.isInitialized) return; try { // Initialize Nacos client await this.nacosClient.connect(); // Initialize vector database this.vectorDB = new VectorDB(); await this.vectorDB.start(); await this.vectorDB.isReady(); // Initialize MCP Manager this.mcpManager = new McpManager(this.nacosClient, this.vectorDB, 5000); // Start syncing services await this.mcpManager.startSync(); this.isInitialized = true; } catch (error) { throw new Error(`Failed to initialize NacosMcpProvider: ${error instanceof Error ? error.message : String(error)}`); } } async search(params: SearchParams): Promise { if (!this.isInitialized) { await this.init(); } // Implementation details... } async close(): Promise { try { if (this.mcpManager) { await this.mcpManager.stopSync(); } if (this.nacosClient) { await this.nacosClient.disconnect(); } } catch (error) { throw new Error(`Error during cleanup: ${error instanceof Error ? error.message : String(error)}`); } } } export interface NacosMcpProviderConfig { routerConfig?: RouterConfig; minSimilarity?: number; providerPriority?: number; } ``` -------------------------------- ### Shell Script Error Handling with Exit Codes Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Illustrates proper error handling in shell scripts. It checks the success of a curl command and exits with a non-zero status code (1) if the command fails, indicating an error. This is crucial for script automation and integration with other systems. ```shell # Shell script error handling # Good practice if ! curl -f http://localhost:7700/health; then echo 'Service not available' >&2 exit 1 # Proper error exit code fi ``` -------------------------------- ### TypeScript Interface and Function Declaration Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Demonstrates good TypeScript practices for defining interfaces and functions with explicit types. It contrasts this with less-desirable practices like using 'any' and default exports. ```typescript // Good practice export interface SearchOptions { minSimilarity?: number; limit: number; } export function search(query: string, options: SearchOptions): Promise { // implementation } // Avoid export default function search(query: any, options?: any): any { // implementation } ``` -------------------------------- ### Implement MCP Resource Handlers in TypeScript Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202507/issue-6-mcp-resources-plan.md This snippet defines the abstract base class for MCP resource handlers and a concrete LogResourceHandler implementation. It outlines the required methods for listing available log resources and reading a specific log file's content, integrating with the MCP SDK. The implementation expects proper Resource and ResourceContent types and will need actual file system logic to be functional. ```TypeScript export abstract class BaseResourceHandler { abstract listResources(): Promise; abstract readResource(uri: string): Promise; } export class LogResourceHandler extends BaseResourceHandler { async listResources(): Promise { // Discover available log files } async readResource(uri: string): Promise { // Read specific log file content } } ``` -------------------------------- ### Generate Text Embeddings and Calculate Similarity (TypeScript) Source: https://context7.com/istarwyh/mcpadvisor/llms.txt Utilizes Xenova transformers to generate vector embeddings for text and calculates cosine similarity between embeddings. It supports caching for performance and is used internally by various search and memory engines. ```typescript import { getTextEmbedding } from './utils/embedding.js'; import { calculateCosineSimilarity } from './utils/vectorUtils.js'; // Generate embedding for query text const queryEmbedding = await getTextEmbedding('natural language processing'); console.log(queryEmbedding.length); // 384 (default model dimension) // Compare similarity between two texts const text1Embedding = await getTextEmbedding('machine learning algorithms'); const text2Embedding = await getTextEmbedding('AI model training'); const similarity = calculateCosineSimilarity(text1Embedding, text2Embedding); console.log(`Similarity: ${similarity}`); // 0.85 // Used internally by vector search engines: // - OfflineSearchProvider for hybrid search // - EnhancedMemoryVectorEngine for vector storage // - XenovaVectorDB for embedding generation // Embeddings are cached for performance: const cachedEmbedding = await getTextEmbedding('natural language processing'); // Returns same result instantly from cache ``` -------------------------------- ### TypeScript Error Handling with Graceful Fallback Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Demonstrates robust error handling in TypeScript for asynchronous operations. It uses specific error types, provides context in error messages, logs errors, and implements a graceful fallback by returning an empty array on failure. This pattern helps maintain application stability. ```typescript async function loadData(): Promise { try { const response = await fetch(url); if (!response.ok) { throw new HttpError(`Request failed: ${response.status}`, response.status); } return await response.json(); } catch (error) { logger.error('Failed to load data', { error, url }); return []; // Graceful fallback } } ``` -------------------------------- ### Auto-Commit Template - Markdown Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Template format for automatic commits generated by Claude Code, including conventional commit message, optional body, signature, and issue reference. ```markdown

<type>[optional scope]: <description>

[optional body explaining the change]

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

[optional footer like "Fixes #123"]
``` -------------------------------- ### Conventional Commits Specification Source: https://github.com/istarwyh/mcpadvisor/blob/main/CLAUDE.md Defines the Conventional Commits specification for commit messages, including valid types (feat, fix, docs, etc.), format requirements for the subject line, and common mistakes to avoid. It emphasizes the use of sentence-case for descriptions and adherence to length limits. ```bash [optional scope]: [optional body] [optional footer] ``` -------------------------------- ### Configure NacosMcpProvider with Environment Variables Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202506/nacos-mcp-provider-integration.md Defines required environment variables for Nacos server connection, MCP service binding, authentication, and debugging. Includes server address, credentials, host/port settings, and debug flags. This .env file should be placed in the project root and loaded via dotenv or similar package. ```env # Nacos Configuration NACOS_SERVER_ADDR=http://localhost:8848 NACOS_USERNAME=nacos NACOS_PASSWORD=nacos # MCP Configuration MCP_HOST=localhost MCP_PORT=3000 AUTH_TOKEN=your-auth-token # Debugging NACOS_DEBUG=true ``` -------------------------------- ### SearchProvider Interface Definition Source: https://github.com/istarwyh/mcpadvisor/blob/main/docs/tech/202506/nacos-mcp-provider-integration.md Defines the contract for searching MCP servers. It includes a `search` method that takes `SearchParams` and returns an array of `MCPServerResponse`. An optional `close` method is also provided for cleanup. ```typescript export interface SearchProvider { search(params: SearchParams): Promise; close?(): Promise; } ```