数据存储抽象层

Sizzek MCP Data Storage 是一个独立的存储抽象层,为MCP服务器提供用户隔离、加密支持和多种存储后端,适用于需要安全数据管理的场景。

  • by Drakosfire
  • TypeScript
  • 本地部署
  • 更新于
在 GitHub 查看 drakosfire/mcp-data

使用说明

Sizzek MCP数据存储

MCP服务器的独立存储抽象层,支持用户隔离和加密

🎯 概述

Sizzek MCP Data项目为模型上下文协议(MCP)服务器提供了一个健壮、独立的存储抽象层。它最初是为LibreChat集成中的短信用户管理而开发的,旨在与任何MCP主机配合使用,同时提供用户隔离、加密和多存储后端。

主要特点

  • 🔒 用户隔离:每个用户都有自己的数据沙箱
  • 🔐 加密:为敏感数据内置AES-256-CTR加密
  • 🗄️ 多个后端:JSON文件和MongoDB支持
  • ⚡ 兼容LibreChat:与LibreChat加密系统无缝集成
  • 🏗️ 独立:适用于任何MCP主机,不依赖于特定平台
  • 📊 健康监测:内置健康检查和统计
  • 🔄 迁移支持:存储类型之间的数据迁移很容易

🚀 快速开始

安装

# In your MCP server project
npm install mcp-data

# Or with yarn
yarn add mcp-data

基本用法

import { StorageFactory } from 'mcp-data';

// Create user-isolated storage
const storage = StorageFactory.createFromEnvironment(defaultData);

// Save data for a specific user (e.g., phone number for SMS)
await storage.saveForUser('+1234567890', userData);

// Load data for that user
const data = await storage.loadForUser('+1234567890');

📋 存储类型

JSON文件存储

非常适合开发和小型部署:

import { StorageFactory } from 'mcp-data';

const storage = StorageFactory.createUserStorage({
  type: 'json',
  json: {
    baseDir: './storage',
    backupEnabled: true
  }
}, defaultData);

MongoDB存储

加密生产就绪:

import { StorageFactory } from 'mcp-data';

const storage = StorageFactory.createUserStorage({
  type: 'mongodb',
  mongodb: {
    connectionString: 'mongodb://localhost:27017/mcp-data',
    collectionName: 'user_data'
  },
  encryptionKey: process.env.ENCRYPTION_KEY
}, defaultData);

🔐 安全的API密钥存储

对于API凭据等敏感数据:

import { StorageFactory } from 'mcp-data';

// Create encrypted storage
const credentialsStorage = StorageFactory.createEncryptedFromEnvironment({
  clientId: '',
  clientSecret: '',
  accessToken: ''
});

// Store encrypted credentials per user
await credentialsStorage.saveEncrypted(userId, {
  clientId: 'google-client-id',
  clientSecret: 'google-client-secret',
  accessToken: 'oauth-token'
});

// Retrieve and decrypt
const creds = await credentialsStorage.loadDecrypted(userId);

🔧 环境配置

设置这些环境变量以进行自动配置:

# Storage type selection
MCP_STORAGE_TYPE=mongodb          # or 'json'

# MongoDB configuration
MONGODB_CONNECTION_STRING=mongodb://localhost:27017/mcp-data
MONGODB_DATABASE=mcp-data
MONGODB_COLLECTION=user_storage

# JSON configuration (fallback)
MCP_STORAGE_PATH=./storage_files

# Encryption (compatible with LibreChat)
CREDS_KEY=your-64-character-hex-encryption-key
# or
MCP_ENCRYPTION_KEY=your-encryption-key

📊 数据库体系结构

独立数据库策略

该系统使用专用 mcp-data 数据库,与主应用程序分开:

MongoDB Instance
├── your-main-app/           # Your main application database
│   └── ... (existing collections)
└── mcp-data/               # MCP data storage (isolated)
    ├── user_memory/            # Knowledge graphs per user
    ├── user_todos/             # Todo lists per user
    ├── scheduled_tasks/        # Scheduled events per user
    ├── api_credentials/        # Encrypted API keys per user
    └── [custom collections]

分离的好处

  • 界限清楚 主应用程序和MCP数据之间
  • 独立缩放 以及备份策略
  • 更容易维护 以及故障排除
  • 安全隔离 用于敏感的MCP数据

🏗️ LibreChat集成

与LibreChat加密兼容

系统自动使用LibreChat的 CREDS_KEY 如果可用:

// Automatically uses LibreChat's encryption system
const storage = StorageFactory.createForLibreChat(
  'user_memory',      // collection name
  defaultData,        // default data structure
  true               // enable encryption
);

LibreChat的环境变量

# In librechat.yaml
mcpServers:
  memory:
    env:
      MCP_STORAGE_TYPE: "mongodb"
      MCP_USER_ID: "${USER_ID}"  # LibreChat passes phone number
      MONGODB_CONNECTION_STRING: "mongodb://mongodb:27017/mcp-data"
      CREDS_KEY: "${CREDS_KEY}"  # LibreChat's encryption key

📝 示例:短信用户存储系统

import { StorageFactory } from 'mcp-data';

interface UserMemory {
  entities: Array<{name: string, type: string, facts: string[]}>;
  conversations: string[];
  preferences: Record<string, any>;
}

class SMSMemoryManager {
  private storage: UserStorageInterface<UserMemory>;

  constructor() {
    this.storage = StorageFactory.createFromEnvironment({
      entities: [],
      conversations: [],
      preferences: {}
    });
  }

  async rememberFact(phoneNumber: string, fact: string) {
    const memory = await this.storage.loadForUser(phoneNumber);
    
    // Process and store the fact
    memory.entities.push({
      name: extractEntityName(fact),
      type: 'user_fact',
      facts: [fact]
    });
    
    await this.storage.saveForUser(phoneNumber, memory);
  }

  async getMemoryForUser(phoneNumber: string): Promise<UserMemory> {
    return await this.storage.loadForUser(phoneNumber);
  }
}

🔒 安全最佳实践

✅ 安全生产

  • 加密存储 使用AES-256-CTR
  • 按用户加密 具有独特的IV
  • 关键点旋转 支持
  • 无明文敏感数据

❌ 永远不要这样做

  • 不要通过短信发送API密钥
  • 不要将加密密钥存储在代码中
  • 不要对所有数据类型使用相同的数据库
  • 不要跳过用户隔离

🛡️ API密钥的推荐流程

1. SMS: "To use Google Products, visit: "
2. User completes OAuth in browser
3. System stores encrypted tokens in database
4. SMS: "✅ Google Calendar access configured!"

🧪 测试

import { StorageFactory } from 'mcp-data';

// Create test storage (temporary)
const testStorage = StorageFactory.createTestStorage(defaultData);

// Your tests here
await testStorage.saveForUser('test-user', testData);
const retrieved = await testStorage.loadForUser('test-user');

📈 监测和健康

// Health check
const isHealthy = await storage.healthCheck();

// Get statistics
const stats = await storage.getStats();
console.log(`Total users: ${stats.totalUsers}`);
console.log(`Storage size: ${stats.totalSize} bytes`);

// Cleanup old data
await storage.cleanup();

🔄 迁移

从JSON到MongoDB

import { StorageFactory } from 'mcp-data';

const jsonStorage = StorageFactory.createUserStorage({
  type: 'json',
  json: { baseDir: './old-storage' }
}, defaultData);

const mongoStorage = StorageFactory.createUserStorage({
  type: 'mongodb',
  mongodb: { 
    connectionString: 'mongodb://localhost:27017/mcp-data',
    collectionName: 'migrated_data'
  }
}, defaultData);

// Migrate all users
const users = await jsonStorage.listUsers();
for (const userId of users) {
  const data = await jsonStorage.loadForUser(userId);
  await mongoStorage.saveForUser(userId, data);
}

🤝 贡献

  1. 分叉存储库
  2. 创建要素分支(git checkout -b feature/amazing-feature)
  3. 提交您的更改(git commit -m 'Add amazing feature')
  4. 推到分支(git push origin feature/amazing-feature)
  5. 打开拉取请求

📄 许可证

此项目根据MIT许可证获得许可-请参阅 许可证 文件以获取详细信息。

🙏 致谢

  • 灵感来自LibreChat强大的加密系统
  • 专为短信集成项目而设计
  • 专为MCP服务器开发人员而设计

📞 支持


由以下材料制成❤️ Alan Meigs