@portkey ai/mcp工具过滤器
使用嵌入相似性对MCP(模型上下文协议)服务器进行超快速语义工具过滤。将您的工具上下文从1000多个工具减少到最相关的10-20个工具 10ms以下.
特性
- ⚡ 迅速的:1000多种内置优化工具的过滤延迟\`
使用MCP服务器初始化筛选器。这将预计算并缓存所有工具嵌入。
备注:在启动时调用一次。这是一个异步操作,可能需要几秒钟,具体取决于工具的数量。
await filter.initialize(servers);filter(input: FilterInput, options?: FilterOptions): Promise
基于输入上下文的过滤工具。
输入类型:
// String input
await filter.filter("Search my emails about the project");
// Chat messages
await filter.filter([
{ role: 'user', content: 'What meetings do I have today?' },
{ role: 'assistant', content: 'Let me check your calendar.' }
]);选项 (全部可选,覆盖默认值):
{
topK?: number, // Max tools to return
minScore?: number, // Minimum similarity score (0-1)
contextMessages?: number, // How many recent messages to use
alwaysInclude?: string[], // Tool names to always include
exclude?: string[], // Tool names to exclude
maxContextTokens?: number, // Max context size
}退货:
{
tools: ScoredTool[], // Filtered and ranked tools
metrics: {
totalTime: number, // Total time in ms
embeddingTime: number, // Time to embed context
similarityTime: number, // Time to compute similarities
toolsEvaluated: number, // Total tools evaluated
}
}getStats()
获取有关筛选器状态的统计信息。
const stats = filter.getStats();
// {
// initialized: true,
// toolCount: 25,
// cacheSize: 5,
// embeddingDimensions: 1536
// }clearCache()
清除上下文嵌入缓存。
filter.clearCache();性能优化
内置优化
该库包括几个开箱即用的性能优化:
- 🚀 环形无卷点产品 -通过CPU流水线优化,向量相似度计算速度提高了6-8倍
- 📊 智能Top-K选择 -混合算法对典型工作负载使用快速内置排序,对500多种工具切换到基于堆的选择
- 💾 真正的LRU缓存 -基于访问模式的智能缓存驱逐,而不仅仅是插入顺序
- 🎯 就地操作 -通过就地向量归一化减少内存分配
- ⚡ 基于集合的查找 -O(1)排除检查,而不是O(n)阵列扫描
这些优化是自动和透明的,不需要配置!
延迟故障
1000个工具的典型性能:
Building context: ({
type: 'function',
function: {
name: t.toolName,
description: t.tool.description,
parameters: t.tool.inputSchema,
}
}));
// Make LLM request with filtered tools
const completion = await portkey.chat.completions.create({
model: 'gpt-4',
messages: messages,
tools: openaiTools,
});与LangChain合作
import { ChatOpenAI } from 'langchain/chat_models/openai';
import { MCPToolFilter } from '@portkey-ai/mcp-tool-filter';
const filter = new MCPToolFilter({ /* ... */ });
await filter.initialize(mcpServers);
// Create a custom tool selector
async function selectTools(messages) {
const { tools } = await filter.filter(messages);
return tools.map(t => convertToLangChainTool(t));
}
// Use in your agent
const model = new ChatOpenAI();
const tools = await selectTools(messages);
const response = await model.invoke(messages, { tools });缓存策略
// Recommended: Initialize once at startup
let filterInstance: MCPToolFilter;
async function getFilter() {
if (!filterInstance) {
filterInstance = new MCPToolFilter({ /* ... */ });
await filterInstance.initialize(mcpServers);
}
return filterInstance;
}
// Use in request handlers
app.post('/chat', async (req, res) => {
const filter = await getFilter();
const result = await filter.filter(req.body.messages);
// ... use filtered tools
});基准测试
各种刀具数量的性能(M1 Max):
局部嵌入(Xenova/全MiniLM-L6-v2):
| 工具 | 初始化 | 筛选器(冷) | 筛选器(缓存) |
|---|---|---|---|
| 10 | ~100ms | 2ms | \ 5000) { |
logger.warn('Slow filter request', result.metrics); }
## 高级用法
### 两级过滤
对于非常大的工具集,使用分层过滤:
// Stage 1: Filter by server categories const relevantServers = mcpServers.filter(server => server.categories?.some(cat => userIntent.includes(cat)) );
// Stage 2: Filter tools within relevant servers const result = await filter.filter(messages);
### 自定义评分
将嵌入相似性与关键字匹配相结合:
const { tools } = await filter.filter(input);
// Boost tools with exact keyword matches const boostedTools = tools.map(tool => { const hasKeywordMatch = tool.tool.keywords?.some(kw => input.toLowerCase().includes(kw.toLowerCase()) ); return { ...tool, score: hasKeywordMatch ? tool.score * 1.2 : tool.score }; }).sort((a, b) => b.score - a.score);
### 始终包括电动工具
始终包括某些基本工具:
const filter = new MCPToolFilter({ // ... defaultOptions: { alwaysInclude: [ 'web_search', // Always useful 'conversation_search', // Access to context ], } });
## 故障排除
### 首次请求缓慢
**问题**:第一次筛选器调用缓慢。
**解决方案**:嵌入API调用需要3-5ms。具有类似上下文的后续调用会被缓存,而且速度更快。
// Warm up the cache await filter.filter("hello"); // ~5ms await filter.filter("hello"); // ~1ms (cached)
### 工具选择不当
**问题**:选择了错误的工具。
**解决方案**:
1. 使用更多关键字和用例改进工具描述
1. 降低 `minScore` 阈值
1. 增加 `topK` 包含更多工具
1. 添加重要工具 `alwaysInclude`
### 内存使用
**问题**:许多工具的内存使用率很高。
**解决方案**:使用较小的嵌入尺寸:
embedding: { dimensions: 512 // Instead of 1536 }
这将内存减少约66%,同时精度损失最小。
## 许可证
麻省理工学院
## 贡献
欢迎投稿!请打开问题或PR。
## 支持
- GitHub问题:
- 电子邮件:support@portkey.ai