Fetch only relevant tools for the current conversation and save cost while increasing the precision of your LLM Response
OppieAI MCP Tool Filter
A Precision-driven Tool Recommendation (PTR) system for filtering MCP (Model Context Protocol) tools based on conversation context. Fetch only relevant tool for the ongoing conversation and save cost while increasing the precision of your LLM Response.
Developed by OppieAI
๐ฅ Explainer Video
Watch the full explanation of how ToolsFilter works and its impact on LLM performance
Table of Contents
- The Tool Overload Problem - Research Evidence - Visual Evidence - Core Capabilities - Infrastructure & Performance - Real-World Impact - Search Pipeline Architecture - Search Strategies - Latest Evaluation Results - LTR Model Performance - Optimization Roadmap - Prerequisites - Installation - Running the Services - API Documentation - Main Endpoints - Response Format - Running Tests & Evaluation - Latest Evaluation Reports - Code Quality - Performance Testing - Vector Store Collections - Automatic Fallback MechanismWhy?
The Tool Overload Problem
Modern LLMs with access to large tool suites face a critical performance degradation issue: the more tools available, the lower the accuracy becomes. This phenomenon is well-documented in research and practical implementations:
๐ Research Evidence
Recent studies using MCPGauge evaluated six commercial LLMs with 30 MCP tool suites and revealed alarming findings:- 9.5% accuracy drop on average when LLMs have automated access to MCP tools
- 3.25ร to 236.5ร increase in input token volume, creating massive computational overhead
- "Non-trivial friction" between retrieved context and the model's internal reasoning
- Models struggle with instruction compliance when too many tools are available
๐ฅ Visual Evidence
This accuracy degradation with increased tool count is demonstrated in this analysis video, showing how model performance deteriorates as more tools are introduced.Solution
Core Capabilities
- ๐ Multi-Stage Search Pipeline: Semantic + BM25 + Cross-Encoder + LTR ranking
- ๐ฏ High-Performance Results: Perfect P@1 and MRR across all search strategies
- ๐ง Learning-to-Rank: XGBoost model with 46+ engineered features (NDCG@10: 0.975)
- ๐ง OpenAI Function Calling Compatible: Flat tool structure following OpenAI specification
Infrastructure & Performance
- โก Multiple Embedding Providers: Voyage AI, OpenAI, Cohere with automatic fallback
- ๐พ Intelligent Multi-Layer Caching: Redis for queries, results, and tool indices
- ๐ฏ Qdrant Vector Database: High-performance vector search with model-specific collections
- ๐ Comprehensive Evaluation: Built-in framework with F1, MRR, NDCG@k metrics
- ๐ Message Format Compatibility: Claude and OpenAI conversation formats
- ๐ Collection Metadata Tracking: Model versioning and automatic dimension handling
- ๐ Robust Fallback Mechanisms: Secondary embedding models and graceful degradation
Real-World Impact
Instead of overwhelming your LLM with 100+ tools, get precisely the 3-5 most relevant ones:
- Before: 236ร token overhead, 9.5% accuracy loss
- After: 95%+ precision, perfect recall on relevant tools, minimal token usage
Architecture
Search Pipeline Architecture
โโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโ
โ FastAPI App โโโโโโถโ Message Parser โโโโโโถโ Search Pipeline โ
โโโโโโโโโโฌโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โโโโโโโโโโโฌโโโโโโโโ
โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโ
โ โ โ โ โ
โโโโโโโโโโผโโโโโโโโโ โโโโโโโโผโโโโโโ โโโโโโโโโโโผโโโโโโโโโ โ โโโโโโโโโผโโโโโโโ
โ Redis Cache โ โ Embedding โ โ Qdrant Vector โ โ โ LTR Reranker โ
โ โ โ Service โ โ Database โ โ โ (XGBoost) โ
โ โข Query Cache โ โ (LiteLLM) โ โ โ โ โ โ
โ โข Results Cache โ โ โข Voyage โ โ โข Semantic Searchโ โ โ โข 46 Featuresโ
โ โข Tool Index โ โ โข OpenAI โ โ โข BM25 Hybrid โ โ โ โข NDCG@10 Optโ
โโโโโโโโโโโโโโโโโโโ โ โข Fallback โ โ โข Cross-Encoder โ โ โ โ
โโโโโโโโโโโโโโ โโโโโโโโโโโโโโโโโโโโ โ โโโโโโโโโโโโโโโโ
โ
โโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โโโโโโโโผโโโโโโโ
โ Multi-Stage โ
โ Filtering โ
โ โ
โ 1. Semantic โ
โ 2. BM25 โ
โ 3. Rerank โ
โ 4. LTR โ
โโโโโโโโโโโโโโโ
Search Strategies
- semantic_only: Pure vector similarity search
- hybrid_basic: BM25 + semantic search combination
- hybridcrossencoder: + Cross-encoder reranking
- hybridltrfull: + Learning-to-Rank optimization
Performance
Latest Evaluation Results (August 2025)
Search Strategy Comparison: (With 300+ noise (Genuine APIs) tools to resemble real-world)
| Strategy | F1 Score | MRR | P@1 | NDCG@10 | Best For | |----------|----------|-----|-----|---------|----------| | hybrid_basic | 0.359 โญ | 1.000 | 1.000 | 0.975 โญ | General-purpose, balanced performance | | semantic_only | 0.328 | 1.000 โญ | 1.000 โญ | 0.870 | Simple queries, exact matches | | hybridcrossencoder | 0.359 | 1.000 | 1.000 | 0.964 | Complex queries requiring reranking | | hybridltrfull | 0.359 | 1.000 | 1.000 | 0.942 | Learning-based optimization |
โญ = Best performer for that metric
๐ View Detailed Report
Key Achievements:
- Perfect Precision@1: All strategies achieve 1.000 P@1
- Perfect MRR: All strategies achieve 1.000 Mean Reciprocal Rank
- Strong NDCG Performance: Up to 0.975 NDCG@10 with hybrid_basic
- Consistent F1 Scores: 0.328-0.359 across different approaches
LTR Model Performance
Learning-to-Rank Training Results:
- Cross-Validation NDCG@10: 0.9167 ยฑ 0.0567
- Training Data: 18,354 samples with 46 features
- Top Features: actionalignment (32.7%), querytypeanalyze (33.9%), exactname_match (19.5%)
- Training Speed: <5 seconds with XGBoost
Optimization Roadmap
โ Completed:
Pre-index all tools on startup- Implemented vector store cachingImplement connection pooling- Added Redis and Qdrant connection poolingAdd batch embedding generation- Optimized embedding pipelineOptimize vector search parameters- Tuned similarity thresholds
- Improve LTR model with better class balancing
- Enhance feature engineering for interaction signals
- Optimize NDCG@5 performance for top-precision use cases
Quick Start
Prerequisites
- Python 3.11+
- Docker and Docker Compose
- API keys for embedding providers (Voyage AI, OpenAI, or Cohere)
Installation
- Clone the repository:
git clone https://github.com/yourusername/ToolsFilter.git
cd ToolsFilter
- Create a virtual environment:
python -m venv venv
source venv/bin/activate # On Windows: venv\Scripts\activate
- Install dependencies:
pip install -r requirements.txt
- Copy environment variables:
cp .env.example .env
- Edit
.envand add your API keys:
# Embedding Service Keys (at least one required)
VOYAGEAPIKEY=yourvoyageapi_key
OPENAIAPIKEY=youropenaiapi_key # Optional fallback
COHEREAPIKEY=yourcohereapi_key # Optional
Important: Include provider prefix in model names
PRIMARYEMBEDDINGMODEL=voyage/voyage-2
FALLBACKEMBEDDINGMODEL=openai/text-embedding-3-small
Running the Services
Option 1: Using Docker (Recommended)
# Start all services including the API
make up
Or manually:
docker-compose up -d
View logs
make logs
Stop services
make down
Option 2: Development Mode with Hot Reloading
# Start in development mode
make up-dev
Or manually:
docker-compose -f docker-compose.yml -f docker-compose.dev.yml up
Option 3: Run API Locally
- Start only Qdrant and Redis:
docker-compose up -d qdrant redis
- Run the API:
python -m src.api.main
The API will be available at http://localhost:8000
API Documentation
Once running, visit:
- Swagger UI:
http://localhost:8000/docs - ReDoc:
http://localhost:8000/redoc
Usage Example
import requests
Filter tools based on conversation
response = requests.post(
"http://localhost:8000/api/v1/tools/filter",
json={
"messages": [
{"role": "user", "content": "I need to search for Python files in the project"}
],
"available_tools": [
{
"type": "function",
"name": "grep",
"description": "Search for patterns in files",
"parameters": {
"type": "object",
"properties": {
"pattern": {"type": "string", "description": "Search pattern"}
},
"required": ["pattern"]
},
"strict": true
},
{
"type": "function",
"name": "find",
"description": "Find files by name",
"parameters": {
"type": "object",
"properties": {
"name": {"type": "string", "description": "File name pattern"}
},
"required": ["name"]
},
"strict": true
}
]
}
)
print(response.json())
{
"recommended_tools": [
{"tool_name": "find", "confidence": 0.95},
{"tool_name": "grep", "confidence": 0.85}
],
"metadata": {"processingtimems": 42}
}
API Endpoints
Main Endpoints
POST /api/v1/tools/filter- Filter tools based on conversation contextGET /api/v1/tools/search- Search tools by text queryPOST /api/v1/tools/register- Register new tools (for batch indexing)GET /api/v1/tools/info- Get information about indexed toolsGET /api/v1/collections- List all vector store collections with metadataGET /health- Health check endpoint
Response Format
{
"recommended_tools": [
{
"tool_name": "find",
"confidence": 0.85,
"reasoning": "High relevance to file search operations"
}
],
"metadata": {
"processingtimems": 45.2,
"embedding_model": "voyage/voyage-2",
"totaltoolsanalyzed": 20,
"conversation_messages": 3,
"request_id": "uuid-here",
"conversationpatterns": ["filesearch", "code_analysis"]
}
}
Development
Running Tests & Evaluation
# Run unit tests
pytest tests/ -v
Run comprehensive evaluation with all strategies
docker exec ptrapi python -m src.evaluation.runevaluation
Run strategy comparison
docker exec ptrapi python -m src.evaluation.evaluationframework.comparison
Train LTR model
docker exec ptrapi python -m src.scripts.trainltr
Run ToolBench evaluation
docker exec ptrapi python -m src.evaluation.toolbenchevaluator
Run simple API test
python test_api.py
Latest Evaluation Reports
Refer to the latest comparison report: evaluationresults/comparison20250823_153715.markdown
Key findings:
- hybrid_basic strategy performs best overall (F1: 0.359, NDCG@10: 0.975)
- All strategies achieve perfect P@1 and MRR (1.000)
- LTR model shows consistent performance with cross-validation NDCG@10: 0.6167 ยฑ 0.0567
Code Quality
# Linting
ruff check src/
Type checking
mypy src/
Formatting
black src/
Performance Testing
# Start the load test UI
locust -f tests/load_test.py
Configuration
Key configuration options in .env:
PRIMARYEMBEDDINGMODEL: Main embedding model (default: voyage-2)FALLBACKEMBEDDINGMODEL: Fallback model (default: text-embedding-3-small)MAXTOOLSTO_RETURN: Maximum tools to return (default: 10)SIMILARITY_THRESHOLD: Minimum similarity score (default: 0.7)
Vector Store Collections
The system automatically creates model-specific collections to handle different embedding dimensions:
- Collections are named as:
tools<modelname>(e.g.,toolsvoyagevoyage_3) - Each collection stores metadata including model name, dimension, and creation time
- Switching between models is seamless - the system will use the appropriate collection
- Use the
/api/v1/collectionsendpoint to view all collections
Automatic Fallback Mechanism
The system supports automatic fallback to a secondary embedding model when the primary model fails:
- Configure
FALLBACKEMBEDDINGMODELin your.envfile - Separate vector store collections are maintained for each model
- On primary model failure (e.g., rate limits, API errors), requests automatically use the fallback
- The
embedding_modelfield in responses indicates which model was used - Both models must be properly configured with valid API keys
Documentation
See the /documentation directory for:
References
Inspired by PTR PaperLicense
This project uses a dual licensing model:
- Non-Commercial Use: Free for research, education, and personal projects
- Commercial Use: Requires a separate commercial license
For commercial licensing, contact: sales@oppie.ai