ZeroDB MCP客户端
用于ZeroDB MCP Bridge API的可生产类型脚本/JavaScript客户端。提供对所有ZeroDB功能的类型安全访问,包括向量搜索、量子操作、NoSQL表、文件存储、事件等。
](https://www.npmjs.com/package/@zerodb/mcp-client)  
特性
- API全面覆盖:支持所有60+ZeroDB操作
- 类型安全:完全支持TypeScript,具有全面的类型定义
- 错误处理:具有详细错误信息的自定义错误类
- 重试逻辑:针对瞬态故障的内置指数回退
- 认证:同时支持API密钥和JWT令牌
- 速率限制:自动速率限制处理,支持后重试
- 验证:矢量、UUID和其他数据的输入验证
- 框架支持:适用于Node.js、React、Next.js和其他框架
安装
npm install @zerodb/mcp-client或者用纱线:
yarn add @zerodb/mcp-client快速开始
import { ZeroDBClient } from '@zerodb/mcp-client';
// Initialize the client
const client = new ZeroDBClient({
apiKey: 'ZERODB_your_api_key',
baseURL: 'https://api.ainative.studio' // optional
});
// Search vectors
const results = await client.vectors.search({
project_id: 'your-project-uuid',
query_vector: embedding, // 1536-dimensional array
limit: 10,
threshold: 0.7
});
console.log(`Found ${results.total_count} results`);认证
客户端支持两种身份验证方法:
API密钥验证
const client = new ZeroDBClient({
apiKey: 'ZERODB_your_api_key'
});JWT令牌身份验证
const client = new ZeroDBClient({
jwtToken: 'your_jwt_token'
});更新身份验证
// Switch to JWT
client.setAuthToken('new_jwt_token', 'jwt');
// Switch to API key
client.setAuthToken('ZERODB_new_api_key', 'apiKey');配置选项
const client = new ZeroDBClient({
apiKey: 'ZERODB_your_api_key', // API key (or use jwtToken)
jwtToken: 'your_jwt_token', // JWT token (alternative to apiKey)
baseURL: 'https://api.ainative.studio', // API base URL (optional)
timeout: 30000, // Request timeout in ms (default: 30000)
retryAttempts: 3, // Number of retry attempts (default: 3)
retryDelay: 1000 // Initial retry delay in ms (default: 1000)
});API 参考
向量运算
插入矢量
const result = await client.vectors.upsert({
project_id: 'project-uuid',
embedding: [0.1, 0.2, ...], // 1536 dimensions
document: 'This is a sample document',
namespace: 'default',
metadata: {
source: 'api',
type: 'article',
tags: ['technology', 'ai']
}
});
// Returns: { vector_id: string, status: string }批量更新矢量
const result = await client.vectors.batchUpsert({
project_id: 'project-uuid',
namespace: 'documents',
vectors: [
{
embedding: [...],
document: 'Document 1',
metadata: { ... }
},
{
embedding: [...],
document: 'Document 2',
metadata: { ... }
}
]
});
// Returns: { vector_ids: string[], success_count: number, error_count: number }搜索向量
const results = await client.vectors.search({
project_id: 'project-uuid',
query_vector: [...], // 1536 dimensions
limit: 10,
threshold: 0.7,
namespace: 'default',
metadata_filter: {
category: 'technology'
}
});
// Returns: { vectors: Vector[], total_count: number, search_time_ms: number }删除矢量
const result = await client.vectors.delete('project-uuid', 'vector-id');
// Returns: { status: string, deleted: boolean }按ID获取矢量
const vector = await client.vectors.get('project-uuid', 'vector-id');
// Returns: Vector object with all fields列出向量
const vectors = await client.vectors.list({
project_id: 'project-uuid',
namespace: 'default',
limit: 100,
offset: 0
});
// Returns: Vector[]矢量统计
const stats = await client.vectors.stats('project-uuid');
// Returns: {
// total_vectors: number,
// namespaces: Array,
// storage_bytes: number,
// avg_vector_size: number
// }创建矢量索引
const index = await client.vectors.createIndex({
project_id: 'project-uuid',
namespace: 'default',
index_type: 'HNSW' // or 'IVF' or 'FLAT'
});
// Returns: { index_id: string, estimated_build_time_seconds: number, status: string }优化矢量存储
const result = await client.vectors.optimize({
project_id: 'project-uuid',
strategy: 'compression' // or 'deduplication' or 'clustering'
});
// Returns: { optimized_vectors: number, storage_saved_bytes: number, optimization_time_ms: number }导出向量
const result = await client.vectors.export({
project_id: 'project-uuid',
namespace: 'default',
format: 'json' // or 'csv' or 'parquet'
});
// Returns: { download_url: string, vector_count: number, file_size_bytes: number }量子操作
压缩矢量
const result = await client.quantum.compress({
project_id: 'project-uuid',
embedding: [...],
compression_ratio: 0.6,
preserve_semantics: true
});
// Returns: { compressed_embedding: number[], compression_achieved: number }解压缩矢量
const result = await client.quantum.decompress({
project_id: 'project-uuid',
compressed_embedding: [...]
});
// Returns: { embedding: number[], quality_score: number }混合相似性
const result = await client.quantum.hybridSimilarity({
project_id: 'project-uuid',
query_vector: [...],
candidate_vector: [...],
metadata_boost: { relevance: 0.8 }
});
// Returns: { similarity_score: number, cosine_component: number, quantum_component: number }表操作
创建表
const table = await client.tables.createTable({
project_id: 'project-uuid',
table_name: 'users',
schema: {
name: { type: 'string', nullable: false },
email: { type: 'string', nullable: false },
age: { type: 'number', nullable: true }
}
});插入行
const result = await client.tables.insertRows({
project_id: 'project-uuid',
table_name: 'users',
rows: [
{ name: 'John', email: 'john@example.com', age: 30 },
{ name: 'Jane', email: 'jane@example.com', age: 28 }
]
});查询行
const result = await client.tables.queryRows({
project_id: 'project-uuid',
table_name: 'users',
filters: { age: { $gte: 25 } },
limit: 10,
order_by: 'name'
});更新行
const result = await client.tables.updateRows({
project_id: 'project-uuid',
table_name: 'users',
filters: { email: 'john@example.com' },
updates: { age: 31 }
});删除行
const result = await client.tables.deleteRows({
project_id: 'project-uuid',
table_name: 'users',
filters: { age: { $lt: 18 } },
confirm: true
});文件操作
上传文件
const result = await client.files.uploadBuffer(
'project-uuid',
'document.pdf',
fileBuffer,
'application/pdf',
{ author: 'John Doe' }
);下载文件
const result = await client.files.download({
project_id: 'project-uuid',
file_id: 'file-uuid'
});
const content = Buffer.from(result.file_data, 'base64');列出文件
const result = await client.files.list({
project_id: 'project-uuid',
prefix: 'documents/',
limit: 50
});删除文件
const result = await client.files.delete({
project_id: 'project-uuid',
file_id: 'file-uuid'
});活动操作
创建活动
const result = await client.events.create({
project_id: 'project-uuid',
event_type: 'user.signup',
topic: 'users',
payload: { user_id: '123', email: 'user@example.com' },
source: 'web-app'
});列出事件
const result = await client.events.list({
project_id: 'project-uuid',
topic: 'users',
limit: 100
});订阅活动
const result = await client.events.subscribe({
project_id: 'project-uuid',
topic: 'users',
webhook_url: 'https://myapp.com/webhooks/events'
});项目运营
创建项目
const project = await client.projects.create({
name: 'My Project',
description: 'Project description',
tier: 'pro'
});列出项目
const result = await client.projects.list();获取项目统计信息
const stats = await client.projects.stats({
project_id: 'project-uuid'
});删除项目
const result = await client.projects.delete({
project_id: 'project-uuid',
confirm: true
});RLHF操作
收集互动
const result = await client.rlhf.collectInteraction({
type: 'click',
session_id: 'session-uuid',
element_clicked: 'search-button',
page_url: '/search'
});收集代理反馈
const result = await client.rlhf.collectAgentFeedback({
project_id: 'project-uuid',
agent_type: 'search-agent',
agent_response_id: 'response-uuid',
user_rating: 5,
feedback_text: 'Very helpful response'
});管理员操作(仅限管理员)
系统统计信息
const stats = await client.admin.getSystemStats();系统健康
const health = await client.admin.getSystemHealth();错误处理
客户端为不同的错误场景提供自定义错误类:
import {
ZeroDBError,
AuthenticationError,
AuthorizationError,
RateLimitError,
ValidationError,
NotFoundError,
NetworkError,
TimeoutError
} from '@zerodb/mcp-client';
try {
await client.vectors.search({
project_id: 'invalid-uuid',
query_vector: embedding,
limit: 10
});
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
console.error('Field errors:', error.errors);
} else if (error instanceof AuthenticationError) {
console.error('Authentication failed:', error.message);
} else if (error instanceof RateLimitError) {
console.error('Rate limited. Retry after:', error.retryAfter);
} else if (error instanceof NotFoundError) {
console.error('Resource not found:', error.message);
} else {
console.error('Unexpected error:', error);
}
}框架集成
React/Next.js
import { ZeroDBClient } from '@zerodb/mcp-client';
import { useState, useEffect } from 'react';
function SearchComponent() {
const [results, setResults] = useState([]);
const client = new ZeroDBClient({ apiKey: process.env.ZERODB_API_KEY });
const search = async (query: string) => {
const embedding = await getEmbedding(query); // Your embedding function
const results = await client.vectors.search({
project_id: process.env.ZERODB_PROJECT_ID,
query_vector: embedding,
limit: 10
});
setResults(results.vectors);
};
return (
search(e.target.value)} />
{results.map(result => (
{result.document}
))}
);
}Node.js后端
import express from 'express';
import { ZeroDBClient } from '@zerodb/mcp-client';
const app = express();
const client = new ZeroDBClient({
apiKey: process.env.ZERODB_API_KEY
});
app.post('/api/search', async (req, res) => {
try {
const { query, projectId } = req.body;
const results = await client.vectors.search({
project_id: projectId,
query_vector: query,
limit: 10
});
res.json(results);
} catch (error) {
if (error instanceof RateLimitError) {
res.status(429).json({ error: 'Rate limit exceeded' });
} else {
res.status(500).json({ error: error.message });
}
}
});
app.listen(3000);最佳实践
1.重用客户端实例
创建单个客户端实例并在整个应用程序中重用它:
// lib/zerodb.ts
import { ZeroDBClient } from '@zerodb/mcp-client';
export const zerodbClient = new ZeroDBClient({
apiKey: process.env.ZERODB_API_KEY
});2.处理速率限制
async function searchWithRetry(query: any, maxRetries = 3) {
for (let i = 0; i setTimeout(resolve, error.retryAfter * 1000));
continue;
}
throw error;
}
}
}3.验证嵌入
import { validateEmbedding } from '@zerodb/mcp-client';
try {
validateEmbedding(myEmbedding, 1536);
} catch (error) {
console.error('Invalid embedding:', error.message);
}4.使用TypeScript
充分利用全型安全:
import { VectorSearchRequest, VectorSearchResult } from '@zerodb/mcp-client';
async function typedSearch(
request: VectorSearchRequest
): Promise {
return client.vectors.search(request);
}测试
npm test示例
请参阅 examples/ 综合使用示例目录:
vectors-example.ts-矢量运算tables-example.ts-表/NoSQL操作files-example.ts-文件存储操作
许可证
麻省理工学院
支持
- 文档:https://docs.ainative.studio
- 问题:https://github.com/ainative-studio/zerodb-mcp-client/issues
- 电子邮件:support@ainative.studio
贡献
欢迎投稿!请在提交PR之前阅读我们的投稿指南。
