
Security News
RubyGems Adds Cooldown Feature to Bundler for Newly Published Gems
RubyGems and Bundler 4.0.13 introduced an opt-in cooldown feature that delays newly published gems during dependency resolution.
@multiplayer-app/ai-agent-mongo
Advanced tools
Shared MongoDB schemas and connection for Multiplayer AI agent services
MongoDB implementation of the database repository interfaces for Multiplayer AI agent services. This library provides concrete Mongoose-based implementations of AgentChatRepository and AgentMessageRepository, along with MongoDB connection management and client-side encryption support.
import mongo from '@multiplayer-app/ai-agent-mongo';
import { MongoAgentChatRepository, MongoAgentMessageRepository } from '@multiplayer-app/ai-agent-mongo';
// Connect to MongoDB
await mongo.connect();
// Initialize repositories
const chatRepository = new MongoAgentChatRepository();
const messageRepository = new MongoAgentMessageRepository();
// Use repositories
const chat = await chatRepository.findById('chat-id');
const messages = await messageRepository.findByChatId('chat-id');
// Disconnect when done
await mongo.disconnect();
Configure MongoDB connection and encryption via environment variables:
# MongoDB Connection
MONGODB_URI=mongodb://localhost:27017/ai-agent
# MongoDB Debug Mode (optional)
MONGO_DEBUG=false
# Encryption Configuration
MONGODB_ENCRYPTION_KEY_VAULT_DB_NAME=encryption
MONGODB_ENCRYPTION_KEY_VAULT_COLLECTION_NAME=__keyVault
MONGODB_ENCRYPTION_DEK_NAME=data-key
MONGODB_ENCRYPTION_MASTER_KEY_PROVIDER=local # or 'aws'
# AWS KMS Configuration (if using AWS KMS)
AWS_KMS_KEY_ARN=arn:aws:kms:region:account:key/key-id
AWS_REGION=us-east-1
This library implements the abstract repository interfaces from @multiplayer-app/ai-agent-db using Mongoose as the ODM (Object Document Mapper) for MongoDB.
MongoAgentChatRepository: Implements AgentChatRepository interfaceMongoAgentMessageRepository: Implements AgentMessageRepository interfaceAgentChatSchema: Mongoose schema for AgentChat entitiesAgentMessageSchema: Mongoose schema for AgentMessage entitiesmongo.connect(): Establishes MongoDB connection with encryption setupmongo.disconnect(): Closes MongoDB connectionmongo.connected(): Checks connection statusmongo.encryption.encrypt(): Encrypt data using client-side encryptionmongo.encryption.decrypt(): Decrypt encrypted dataimport mongo from '@multiplayer-app/ai-agent-mongo';
// Connect to MongoDB
await mongo.connect();
// Check connection status
if (mongo.connected()) {
console.log('Connected to MongoDB');
}
// Disconnect
await mongo.disconnect();
import { MongoAgentChatRepository } from '@multiplayer-app/ai-agent-mongo';
import { SortOrder } from '@multiplayer-app/ai-agent-types';
const chatRepository = new MongoAgentChatRepository();
// Find chat by ID
const chat = await chatRepository.findById('chat-id');
// Find chats by user
const userChats = await chatRepository.findByUserId('user-123');
// Find chats by context
const contextChats = await chatRepository.findByContextKey('context-key');
// Find chats with pagination and sorting
const recentChats = await chatRepository.find(
{ contextKey: 'my-context' },
{
sort: { field: 'updatedAt', order: SortOrder.Desc },
limit: 10
}
);
// Find chats with messages (aggregation)
const chatsWithMessages = await chatRepository.findWithMessages(
{ userId: 'user-123' },
{ sort: { field: 'createdAt', order: SortOrder.Desc } }
);
// Create a new chat
const newChat = await chatRepository.create({
title: 'New Chat',
contextKey: 'context-key',
userId: 'user-123',
status: AgentStatus.Active,
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
});
// Update chat title
await chatRepository.updateTitle('chat-id', 'Updated Title');
// Delete chat
await chatRepository.delete('chat-id');
import { MongoAgentMessageRepository } from '@multiplayer-app/ai-agent-mongo';
import { MessageRole } from '@multiplayer-app/ai-agent-types';
const messageRepository = new MongoAgentMessageRepository();
// Find messages by chat ID
const messages = await messageRepository.findByChatId('chat-id');
// Find messages by role
const assistantMessages = await messageRepository.findByRole(MessageRole.Assistant);
// Find messages by chat and role
const userMessages = await messageRepository.findByChatIdAndRole(
'chat-id',
MessageRole.User
);
// Find messages with tool calls
const toolCallMessages = await messageRepository.findWithToolCalls('chat-id');
// Find messages with attachments
const messagesWithAttachments = await messageRepository.findWithAttachments('chat-id');
// Create a new message
const newMessage = await messageRepository.create({
chat: 'chat-id',
role: MessageRole.User,
content: 'Hello, AI!',
createdAt: new Date().toISOString(),
updatedAt: new Date().toISOString()
});
// Delete messages by chat
await messageRepository.deleteByChatId('chat-id');
You can also use the Mongoose models directly for advanced operations:
import { AgentChatModel, AgentMessageModel } from '@multiplayer-app/ai-agent-mongo';
// Direct Mongoose queries
const chat = await AgentChatModel.findOne({ userId: 'user-123' });
// Aggregation pipelines
const stats = await AgentChatModel.aggregate([
{ $match: { contextKey: 'context-key' } },
{ $group: { _id: '$status', count: { $sum: 1 } } }
]);
The library supports MongoDB client-side field-level encryption (CSFLE):
import mongo from '@multiplayer-app/ai-agent-mongo';
// Encrypt sensitive data
const encrypted = await mongo.encryption.encrypt('sensitive-data');
// Decrypt data
const decrypted = await mongo.encryption.decrypt(encrypted);
Local Key Provider (Development):
MONGODB_ENCRYPTION_MASTER_KEY_PROVIDER=local
AWS KMS (Production):
MONGODB_ENCRYPTION_MASTER_KEY_PROVIDER=aws
AWS_KMS_KEY_ARN=arn:aws:kms:region:account:key/key-id
AWS_REGION=us-east-1
The library automatically creates indexes for optimal query performance:
contextKey (single field)userId (single field, sparse)userId + contextKey (compound)chat (single field)role (single field)chat + role (compound)All operations are fully typed using TypeScript:
import type { AgentChat, AgentMessage } from '@multiplayer-app/ai-agent-types';
import { MongoAgentChatRepository } from '@multiplayer-app/ai-agent-mongo';
const chatRepository = new MongoAgentChatRepository();
// TypeScript ensures type safety
const chat: AgentChat | null = await chatRepository.findById('id');
const chats: AgentChat[] = await chatRepository.findByUserId('user-id');
The library handles MongoDB connection errors and provides logging:
import mongo from '@multiplayer-app/ai-agent-mongo';
try {
await mongo.connect();
} catch (error) {
console.error('Failed to connect to MongoDB:', error);
}
The library includes test utilities using mongodb-memory-server for in-memory MongoDB testing:
# Run tests
npm test
# Watch mode
npm run test:watch
# Coverage
npm run test:coverage
mongo.connect() before using repositories and mongo.disconnect() when shutting down@multiplayer-app/ai-agent-db: Abstract repository interfaces@multiplayer-app/ai-agent-types: Type definitions for AgentChat, AgentMessage, etc.@multiplayer-app/ai-agent-node: Node.js library that uses these repositoriesMIT
FAQs
Shared MongoDB schemas and connection for Multiplayer AI agent services
We found that @multiplayer-app/ai-agent-mongo demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 5 open source maintainers collaborating on the project.
Did you know?

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Security News
RubyGems and Bundler 4.0.13 introduced an opt-in cooldown feature that delays newly published gems during dependency resolution.

Security News
pnpm 11.5 now recognizes npm staged publish approvals in release metadata, preventing those releases from being mistaken for lower-trust package publishes.

Security News
Federal audit finds NIST lacked a plan to clear the NVD backlog, wasted funds on duplicate work, and delayed use of CISA data.