Skip to content

Ví dụ thực tế: MongoDB MCP Server

Overview

MongoDB MCP Server là official implementation từ MongoDB team, cho phép AI agents interact với MongoDB databases và MongoDB Atlas clusters. Đây là ví dụ thực tế hoàn chỉnh về MCP server implementation.

MongoDB MCP Server Features

Core Capabilities

  1. Database Operations

    • Query collections
    • Create/update/delete documents
    • Manage indexes
    • Database administration
  2. Atlas Management

    • Create/manage clusters
    • Performance monitoring
    • User management
    • Access control
  3. Data Analysis

    • Aggregation pipelines
    • Schema analysis
    • Performance insights
    • Data statistics

Installation và Setup

Prerequisites

bash
# Node.js version requirements
node -v  # Should be >= 20.19.0

# MongoDB connection string hoặc Atlas credentials
# Có thể dùng local MongoDB hoặc Atlas cluster

Installation

bash
# Install MongoDB MCP Server
npm install -g @mongodb/mcp-server

# Hoặc dùng npx
npx @mongodb/mcp-server --help

Configuration

Method 1: Connection String

bash
# Direct connection string
mongodb-mcp-server --connection-string "mongodb://localhost:27017/myapp"

# With authentication
mongodb-mcp-server --connection-string "mongodb://user:password@host:port/database"

Method 2: Atlas API Credentials

bash
# Environment variables
export MONGODB_ATLAS_PUBLIC_KEY="your-public-key"
export MONGODB_ATLAS_PRIVATE_KEY="your-private-key"
export MONGODB_ATLAS_GROUP_ID="your-group-id"

# Run server
mongodb-mcp-server

Method 3: Configuration File

json
{
  "database": {
    "connectionString": "mongodb://localhost:27017/myapp"
  },
  "atlas": {
    "publicKey": "your-public-key",
    "privateKey": "your-private-key",
    "groupId": "your-group-id"
  }
}

Supported Tools

Database Tools

1. Query Operations

javascript
// Find documents
{
  "name": "find",
  "description": "Find documents in collection",
  "inputSchema": {
    "type": "object",
    "properties": {
      "database": { "type": "string" },
      "collection": { "type": "string" },
      "filter": { "type": "object" },
      "limit": { "type": "number" },
      "sort": { "type": "object" }
    }
  }
}

// AI usage example:
"Find all active users who signed up in the last 30 days"
→ Server executes: db.users.find({status: "active", createdAt: {$gte: date}})

2. Aggregation

javascript
{
  "name": "aggregate",
  "description": "Run aggregation pipeline",
  "inputSchema": {
    "type": "object",
    "properties": {
      "database": { "type": "string" },
      "collection": { "type": "string" },
      "pipeline": { "type": "array" }
    }
  }
}

// AI usage example:
"Show me monthly user growth for the past year"
→ Server executes: db.users.aggregate([
  {$group: {_id: {$month: "$createdAt"}, count: {$sum: 1}}},
  {$sort: {_id: 1}}
])

3. Collection Management

javascript
// Create collection
{
  "name": "create-collection",
  "description": "Create new collection",
  "inputSchema": {
    "type": "object",
    "properties": {
      "database": { "type": "string" },
      "collection": { "type": "string" },
      "options": { "type": "object" }
    }
  }
}

// Create index
{
  "name": "create-index",
  "description": "Create index on collection",
  "inputSchema": {
    "type": "object",
    "properties": {
      "database": { "type": "string" },
      "collection": { "type": "string" },
      "keys": { "type": "object" },
      "options": { "type": "object" }
    }
  }
}

Atlas Tools

1. Cluster Management

javascript
// List clusters
{
  "name": "atlas-list-clusters",
  "description": "List all Atlas clusters",
  "inputSchema": {
    "type": "object",
    "properties": {}
  }
}

// Create free cluster
{
  "name": "atlas-create-free-cluster",
  "description": "Create free MongoDB Atlas cluster",
  "inputSchema": {
    "type": "object",
    "properties": {
      "name": { "type": "string" },
      "region": { "type": "string" },
      "provider": { "type": "string" }
    }
  }
}

2. Performance Monitoring

javascript
{
  "name": "atlas-get-performance-advisor",
  "description": "Get performance recommendations",
  "inputSchema": {
    "type": "object",
    "properties": {
      "clusterName": { "type": "string" },
      "processName": { "type": "string" }
    }
  }
}

// AI usage example:
"Are there any slow queries in my database?"
→ Server analyzes Atlas Performance Advisor
→ Returns suggested indexes and optimizations

3. User Management

javascript
// Create database user
{
  "name": "atlas-create-db-user",
  "description": "Create database user",
  "inputSchema": {
    "type": "object",
    "properties": {
      "username": { "type": "string" },
      "password": { "type": "string" },
      "databaseName": { "type": "string" },
      "roles": { "type": "array" }
    }
  }
}

// List users
{
  "name": "atlas-list-db-users",
  "description": "List database users",
  "inputSchema": {}
}

Supported Resources

1. Database Schema

javascript
{
  "uri": "mongodb://localhost/myapp/schema",
  "name": "Database Schema",
  "description": "Complete database schema",
  "mimeType": "application/json"
}

// AI can read this to understand data structure
// Example usage:
"Show me the user data structure"
→ Server reads schema resource
AI understands fields, types, relationships

2. Collection Statistics

javascript
{
  "uri": "mongodb://localhost/myapp/users/stats",
  "name": "Users Collection Stats",
  "description": "Statistics about users collection",
  "mimeType": "application/json"
}

// Contains: document count, avg size, indexes, etc.

3. Index Information

javascript
{
  "uri": "mongodb://localhost/myapp/users/indexes",
  "name": "Users Collection Indexes",
  "description": "Index information for users collection",
  "mimeType": "application/json"
}

Real-world Usage Examples

Example 1: E-commerce Analytics

Scenario: AI helps analyze e-commerce data

javascript
// AI Agent: "Show me top selling products this month"

// MongoDB MCP Server executes:
const pipeline = [
  {
    $match: {
      createdAt: {
        $gte: new Date(new Date().getFullYear(), new Date().getMonth(), 1)
      },
      status: "completed"
    }
  },
  {
    $lookup: {
      from: "products",
      localField: "items.productId",
      foreignField: "_id",
      as: "product"
    }
  },
  {
    $unwind: "$items"
  },
  {
    $group: {
      _id: "$items.productId",
      productName: { $first: "$product.name" },
      totalSold: { $sum: "$items.quantity" },
      revenue: { $sum: "$items.price" }
    }
  },
  {
    $sort: { totalSold: -1 }
  },
  {
    $limit: 10
  }
];

// Result: Top 10 products with sales data

Example 2: User Behavior Analysis

Scenario: AI analyzes user patterns

javascript
// AI Agent: "What are the common user journey patterns?"

// MongoDB MCP Server executes:
const pipeline = [
  {
    $group: {
      _id: "$userId",
      sessions: { $sum: 1 },
      avgSessionDuration: { $avg: "$duration" },
      pagesPerSession: { $avg: { $size: "$pages" } },
      lastSeen: { $max: "$timestamp" }
    }
  },
  {
    $bucket: {
      groupBy: "$sessions",
      boundaries: [1, 5, 10, 20, 50],
      default: "50+",
      output: {
        count: { $sum: 1 },
        avgDuration: { $avg: "$avgSessionDuration" }
      }
    }
  }
];

// Result: User segmentation based on engagement

Example 3: Performance Optimization

Scenario: AI identifies and fixes performance issues

javascript
// AI Agent: "Check for slow queries and suggest optimizations"

// MongoDB MCP Server:
// 1. Calls Atlas Performance Advisor
// 2. Analyzes slow query logs
// 3. Suggests indexes
// 4. Creates recommended indexes

// Example output:
{
  "recommendations": [
    {
      "type": "index",
      "collection": "orders",
      "key": { "userId": 1, "createdAt": -1 },
      "reason": "Frequent queries filter by userId and sort by createdAt"
    },
    {
      "type": "query_optimization",
      "suggestion": "Use $lookup instead of separate queries"
    }
  ]
}

Example 4. Database Administration

Scenario: AI helps with database management

javascript
// AI Agent: "Create a new user for the analytics team with read-only access"

// MongoDB MCP Server executes:
{
  "username": "analytics_user",
  "password": "generated_secure_password",
  "databaseName": "production",
  "roles": [
    {
      "roleName": "read",
      "databaseName": "production"
    }
  ]
}

// Result: User created with appropriate permissions

Integration với AI IDEs

Claude Desktop Configuration

json
{
  "mcpServers": {
    "mongodb": {
      "command": "mongodb-mcp-server",
      "args": [
        "--connection-string",
        "mongodb://localhost:27017/myapp"
      ],
      "env": {
        "NODE_ENV": "production"
      }
    }
  }
}

Cursor IDE Configuration

json
{
  "mongodb": {
    "command": "mongodb-mcp-server",
    "args": ["--connection-string", "mongodb://localhost:27017/myapp"],
    "cwd": "/path/to/project"
  }
}

Advanced Usage

1. Custom Aggregations

javascript
// AI can create complex aggregations
const customerLifetimeValue = [
  {
    $group: {
      _id: "$userId",
      totalSpent: { $sum: "$total" },
      orderCount: { $sum: 1 },
      firstOrder: { $min: "$createdAt" },
      lastOrder: { $max: "$createdAt" }
    }
  },
  {
    $addFields: {
      lifetimeDays: {
        $divide: [
          { $subtract: ["$lastOrder", "$firstOrder"] },
          1000 * 60 * 60 * 24
        ]
      },
      avgOrderValue: { $divide: ["$totalSpent", "$orderCount"] }
    }
  },
  {
    $bucket: {
      groupBy: "$totalSpent",
      boundaries: [0, 100, 500, 1000, 5000],
      default: "5000+",
      output: {
        count: { $sum: 1 },
        avgLifetime: { $avg: "$lifetimeDays" }
      }
    }
  }
];

2. Real-time Monitoring

javascript
// AI can set up monitoring
{
  "name": "create-watch",
  "description": "Create database watch",
  "inputSchema": {
    "type": "object",
    "properties": {
      "collection": { "type": "string" },
      "pipeline": { "type": "array" },
      "action": { "type": "string" }
    }
  }
}

// Example: Monitor high-value orders
{
  "collection": "orders",
  "pipeline": [
    { $match: { total: { $gt: 1000 } } }
  ],
  "action": "notify_sales_team"
}

3. Data Validation

javascript
// AI can validate data integrity
{
  "name": "validate-schema",
  "description": "Validate data against schema",
  "inputSchema": {
    "type": "object",
    "properties": {
      "collection": { "type": "string" },
      "schema": { "type": "object" }
    }
  }
}

// Example validation
{
  "collection": "users",
  "schema": {
    "email": { "type": "string", "required": true },
    "age": { "type": "number", "min": 0, "max": 150 }
  }
}

Performance Considerations

1. Connection Pooling

javascript
// MongoDB MCP Server uses connection pooling
const poolConfig = {
  maxPoolSize: 10,
  minPoolSize: 2,
  maxIdleTimeMS: 30000,
  waitQueueTimeoutMS: 5000
};

2. Query Optimization

javascript
// AI can analyze and optimize queries
{
  "name": "explain-query",
  "description": "Explain query execution plan",
  "inputSchema": {
    "type": "object",
    "properties": {
      "collection": { "type": "string" },
      "filter": { "type": "object" }
    }
  }
}

// Returns execution plan with suggestions

3. Index Management

javascript
// AI can suggest optimal indexes
{
  "name": "suggest-indexes",
  "description": "Suggest indexes based on query patterns",
  "inputSchema": {
    "type": "object",
    "properties": {
      "collection": { "type": "string" },
      "queries": { "type": "array" }
    }
  }
}

Security Best Practices

1. Authentication

javascript
// Use environment variables for credentials
const config = {
  connectionString: process.env.MONGODB_URI,
  atlasPublicKey: process.env.ATLAS_PUBLIC_KEY,
  atlasPrivateKey: process.env.ATLAS_PRIVATE_KEY
};

2. Authorization

javascript
// Role-based access control
const permissions = {
  "analyst": ["read", "aggregate"],
  "developer": ["read", "write", "createIndex"],
  "admin": ["*"]
};

3. Audit Logging

javascript
// Log all operations
{
  "name": "audit-log",
  "description": "Enable audit logging",
  "inputSchema": {
    "type": "object",
    "properties": {
      "level": { "type": "string", "enum": ["info", "debug", "error"] }
    }
  }
}

Troubleshooting

Common Issues

1. Connection Failed

bash
# Check connection string
mongodb-mcp-server --connection-string "mongodb://localhost:27017/test"

# Verify MongoDB is running
mongosh --eval "db.adminCommand('ismaster')"

2. Atlas Authentication

bash
# Verify Atlas credentials
curl -u "$PUBLIC_KEY:$PRIVATE_KEY" \
  "https://cloud.mongodb.com/api/atlas/v1.0/groups/$GROUP_ID/clusters"

3. Permission Issues

javascript
// Check user permissions
{
  "name": "check-permissions",
  "description": "Check current user permissions",
  "inputSchema": {}
}

Debug Mode

bash
# Enable debug logging
DEBUG=mcp:* mongodb-mcp-server --connection-string "mongodb://localhost:27017/test"

Summary

MongoDB MCP Server:

  • ✅ Official implementation from MongoDB
  • ✅ Complete database operations
  • ✅ Atlas management integration
  • ✅ Performance monitoring
  • ✅ Security best practices
  • ✅ Production ready

Key Features:

  • 40+ tools for database operations
  • Resource access for schema and stats
  • Atlas integration for cloud management
  • Performance optimization suggestions
  • Multi-transport support (stdio, HTTP)

Use Cases:

  • Data analysis và reporting
  • Database administration
  • Performance optimization
  • Real-time monitoring
  • Application development

Benefits:

  • Standardized MongoDB access for AI
  • Reduced development time
  • Built-in security
  • Performance insights
  • Cloud integration

Tiếp theo: 5. Build MCP Server đầu tiên → Hướng dẫn thực tế

Internal documentation for iNET Portal