Report this

What is the reason for this report?

Building a Scalable App with MongoDB Using DigitalOcean's MCP Server

Published on March 10, 2026
Nestor DazaAnish Singh Walia

By Nestor Daza and Anish Singh Walia

Building a Scalable App with MongoDB Using DigitalOcean's MCP Server

Introduction

The Model Context Protocol (MCP) lets you manage cloud infrastructure through natural language commands by connecting AI tools to external services. Instead of clicking through dashboards and running manual commands, you provision databases, deploy applications, and scale resources by describing your intent to an AI assistant.

In this tutorial, you will build a task management API using Node.js and MongoDB, then deploy the database and application to DigitalOcean using the DigitalOcean MCP server. You will use a single MCP server to automate infrastructure provisioning: creating a MongoDB database cluster, deploying your application to App Platform, and managing both services through conversational commands. This article will show developers how to build and deploy an application by combining both DigitalOcean’s Managed MongoDB and App Platform through DigitalOcean’s MCP automation.

Why use MongoDB with DigitalOcean’s MCP Server?

Instead of navigating multiple dashboards and running manual commands, you can provision databases, deploy applications, and manage infrastructure using natural language commands through AI tools like Claude Code or Cursor. This tutorial will demonstrate real-world automation workflows while highlighting MongoDB’s flexibility alongside DigitalOcean’s zero-configuration deployment experience.

By the end, developers will have a functional Node.js API deployed to production and the knowledge to manage their entire cloud stack conversationally, reducing operational overhead and eliminating context-switching between platforms.

Key Takeaways

  • The DigitalOcean MCP server exposes database and App Platform APIs to AI clients, letting you provision and manage infrastructure through natural language.
  • You limit the MCP server to specific service scopes (like databases,apps) to reduce context size and improve response accuracy.
  • MongoDB’s document model stores data in flexible JSON-like documents, so you add fields without running schema migrations.
  • DigitalOcean App Platform detects your application runtime, installs dependencies, provisions SSL certificates, and handles zero-downtime deployments automatically.
  • A single MCP server replaces multiple dashboard workflows for tasks like scaling resources, creating staging environments, and configuring database firewalls.
  • Connection pooling through the MongoDB Node.js driver reuses database connections across requests, reducing overhead for high-traffic applications.

Prerequisites

Before you begin this guide, you will need:

Configuring the DigitalOcean MCP Server

In this step, you will configure the DigitalOcean MCP server on your local machine. This MCP server runs as a background process that exposes DigitalOcean’s APIs to AI clients through a standardized protocol. Once configured, your AI client will be able to manage both databases and applications through natural language commands.

On macOS with Claude Desktop, open the configuration file in your text editor:

nano ~/Library/Application\ Support/Claude/claude_desktop_config.json

On Linux, the file is located at ~/.config/Claude/claude_desktop_config.json. On Windows, the path is %APPDATA%\Claude\claude_desktop_config.json.

Add the following configuration to the file:

{
  "mcpServers": {
    "digitalocean": {
      "command": "npx",
      "args": ["-y", "@digitalocean/mcp", "--services", "databases,apps"],
      "env": {
        "DIGITALOCEAN_API_TOKEN": "<your-digitalocean-token>"
      }
    }
  }
}

Replace <your-digitalocean-token> with your DigitalOcean Personal Access Token from the prerequisites.

The --services databases,apps argument limits the MCP server to only database and application management tools, reducing context size and improving response accuracy. The npx command runs the MCP server without requiring a separate installation, pulling the latest version of @digitalocean/mcp automatically. For the full list of available MCP services, see the DigitalOcean MCP Server documentation.

Restart your MCP client for the configuration to take effect. In Claude Desktop, fully quit the application (not just close the window) and reopen it. You can verify the MCP server is working by sending a test message like:

List my DigitalOcean database clusters

Your AI assistant should be able to access the DigitalOcean API through the MCP server, and have access to tools for creating databases, managing database users, deploying applications, viewing logs, and scaling resources.

Provisioning a MongoDB Database Cluster

In this step, you will create a DigitalOcean Managed MongoDB database cluster using natural language commands through your MCP client. Open your MCP client and send the following message to your AI assistant:

Create a MongoDB database cluster named "mdb-do-mcp" in the NYC3 region using a 2GB RAM node size. Once created, show me the connection details.

The MCP server will execute the database creation operation through DigitalOcean’s API. The process takes approximately 5-7 minutes. Your AI assistant will provide status updates and return connection details when the cluster is ready.

DigitalOcean Managed MongoDB clusters are created with the following default configuration:

  • A primary node for read and write operations
  • Automatic daily backups with 7-day point-in-time recovery
  • Data encryption at rest using LUKS and in transit with SSL
  • Deployment in a VPC network for secure connections

When the creation is finished, the AI Assistant will return the connection details with a connection string similar to this:

mongodb+srv://doadmin:<password>@mdb-do-mcp-do-user-xxxxx-0.xxx.db.ondigitalocean.com/admin?tls=true&authSource=admin&replicaSet=mdb-do-mcp

Copy this connection string and save it securely. You will use it in the next step when configuring your application. The connection string includes:

  • The default doadmin user with administrative privileges
  • The cluster hostname ending in .db.ondigitalocean.com
  • TLS encryption enabled by default
  • The admin authentication database
  • The replica set name matching your cluster name

MongoDB’s document-oriented data model provides several advantages for application development. Unlike relational databases that require fixed schemas, MongoDB allows you to store data in flexible JSON-like documents. This means you can add new fields to your data structures without running migrations or modifying existing records. For a task management application, you could start with basic title and priority fields, then later add tags, assignedTo, or subtasks without disrupting your existing data.

DigitalOcean’s Managed MongoDB service handles infrastructure management automatically. The fully-managed service monitors cluster health, applies security patches, and manages failover if a node becomes unavailable, all automatically. This means you can focus on building your application without worrying about the underlying infrastructure.

Building the Task Management API

Your application will provide a REST API for creating, listing, and updating tasks, using the Express framework for HTTP routing and the official MongoDB Node.js driver for database operations.

First, create a new directory for your project and navigate into it:

mkdir task-api
cd task-api

Initialize a new Node.js project:

npm init -y

The -y flag accepts all default values for the project configuration.

Install the required dependencies:

npm install express mongodb dotenv

This command installs three packages: express for creating the web server, mongodb for connecting to your DigitalOcean MongoDB cluster, and dotenv for managing environment variables. For background on MongoDB document operations, see How To Perform CRUD Operations in MongoDB.

Create a file named server.js in your project directory with this code:

import express from 'express';
import { MongoClient } from 'mongodb';
import 'dotenv/config';

const app = express();
app.use(express.json());

const client = new MongoClient(process.env.MONGODB_URI);
let db;

client.connect().then(() => {
  db = client.db('tasks');
  console.log('Connected to MongoDB');
});

app.post('/tasks', async (req, res) => {
  const { title, priority = 'medium' } = req.body;
  const result = await db.collection('tasks').insertOne({
    title,
    priority,
    completed: false,
    createdAt: new Date()
  });
  res.json({ id: result.insertedId, title, priority });
});

app.get('/tasks', async (req, res) => {
  const { priority, completed } = req.query;
  const filter = {};
  if (priority) filter.priority = priority;
  if (completed !== undefined) filter.completed = completed === 'true';
  
  const tasks = await db.collection('tasks')
    .find(filter)
    .sort({ createdAt: -1 })
    .toArray();
  res.json(tasks);
});

app.patch('/tasks/:id', async (req, res) => {
  const { ObjectId } = await import('mongodb');
  const result = await db.collection('tasks').updateOne(
    { _id: new ObjectId(req.params.id) },
    { $set: req.body }
  );
  res.json({ modified: result.modifiedCount });
});

app.get('/health', (req, res) => {
  res.json({ status: 'healthy', timestamp: new Date() });
});

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server running on port ${PORT}`);
});

This application defines four API endpoints. The POST /tasks endpoint creates new tasks by inserting documents into the MongoDB tasks collection. Each task document includes a title, priority, completed status, and createdAt timestamp. The GET /tasks endpoint retrieves tasks with optional filtering by priority or completion status using MongoDB’s query operators. The PATCH /tasks/:id endpoint updates existing tasks using MongoDB’s $set operator, which modifies only the specified fields without replacing the entire document. The GET /health endpoint provides a health check for monitoring.

Create a .env file to store your database connection string:

MONGODB_URI=<your-mongodb-connection-string>
PORT=3000

Replace the entire MONGODB_URI value with the connection string you received when creating the server using DigitalOcean’s MCP server, don’t forget to include the actual password for the doadmin account.

Update your package.json to enable ES modules by adding the "type": "module" line after the "main" field (remove any other “type” lines if they exist):

{
  "name": "task-api",
  "version": "1.0.0",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...
}

Test your application locally by starting the server:

node server.js

You will see the following output:

Server running on port 3000
Connected to MongoDB

Open a second terminal window and create a test task:

curl -X POST http://localhost:3000/tasks \
  -H "Content-Type: application/json" \
  -d '{"title":"Deploy to DigitalOcean","priority":"high"}'

The API will return the created task:

{"id":"67abc123def456789","title":"Deploy to DigitalOcean","priority":"high"}

Retrieve all tasks to verify the data was stored:

curl http://localhost:3000/tasks

You will see an array containing your task:

[{"_id":"67abc123def456789","title":"Deploy to DigitalOcean","priority":"high","completed":false,"createdAt":"2025-11-25T10:30:00.000Z"}]

The _id field is automatically generated by MongoDB as a unique identifier for each document. It provides distributed uniqueness without requiring a central ID generator, making it ideal for scalable applications.

You have now created a functional task management API that connects to your DigitalOcean MongoDB cluster. In the next step, you will deploy this application to DigitalOcean App Platform.

Deploying to DigitalOcean App Platform

In this step, you will deploy your application to DigitalOcean App Platform using the MCP server. App Platform automatically detects your application’s runtime and handles the deployment process without requiring Docker configuration or deployment scripts. Learn more about the deployment process in the DigitalOcean App Platform documentation.

First, initialize a Git repository in your project directory:

git init

Create a .gitignore file to exclude sensitive files from version control:

node_modules/
.env

Add all files to the repository and create an initial commit:

git add .
git commit -m "Initial commit: Task management API"

Create a new public repository on GitHub by visiting https://github.com/new. Name the repository task-api and do not initialize it with a README or license.

Add the GitHub repository as a remote and push your code, replacing <<your-github-username>> with your actual GitHub username:

# Using HTTPS (works for all users):
git remote add origin https://github.com/<<your-github-username>>/task-api.git

# Or using SSH (if you have SSH keys configured):
# git remote add origin git@github.com:<<your-github-username>>/task-api.git

git branch -M main
git push -u origin main

Now you will use the DigitalOcean MCP server to deploy the application. Copy your MongoDB connection string to your clipboard. Open your MCP client and send the following message:

Create a DigitalOcean app from my GitHub repository "<<your-github-username>>/task-api" using the main branch. 
Set the environment variable MONGODB_URI to the connection string 
from my local .env file. 
Deploy to the NYC3 region with 512MB of RAM.

The DigitalOcean MCP server will then perform the requested operations and return something like this:

I'll create a DigitalOcean App Platform application from your GitHub repository with the MongoDB connection string and deploy it to NYC3 with 512MB of RAM.

Apps-create-app-from-spec

Perfect! Your app has been successfully created and is now deploying. Here are the details:

App Information:

App ID: xxxxxxxx-xxxxx-4b87-aa9c-d9c706232908
Name: task-api
Region: NYC (New York)
Instance Size: basic-xxs (512MB RAM)
Repository: xxxxx/task-api (main branch)
Auto-deploy: Enabled

[.....]

The deployment typically takes 3-5 minutes. Once complete, you'll receive a URL in the format: https://task-api-<random-hash>.ondigitalocean.app

Would you like me to check the deployment status?

DigitalOcean App Platform provides several features that simplify application deployment and management. The platform automatically detects your application type and installs dependencies, eliminating manual configuration. It provisions SSL certificates automatically for both default and custom domains. Additionally, Built-in monitoring displays application logs and runtime metrics in a single dashboard, making it easy to monitor cluster health. The platform handles zero-downtime deployments when you push changes to your repository.

Verify your deployment by making a request to the live API. Copy the full URL provided by your AI assistant (for example, https://task-api-<random-hash>.ondigitalocean.app) and use it in the following command:

curl <app-url>/health

The API will return a health check response:

{"status":"healthy","timestamp":"2026-02-02T21:39:27.981Z"}

Create a task on your deployed application:

curl -X POST <<app-url>>.ondigitalocean.app/tasks \
  -H "Content-Type: application/json" \
  -d '{"title":"Production deployment successful","priority":"high"}'

The API will return the created task with an automatically generated ID.

Your application is now deployed and connected to your MongoDB cluster. Both services are running in the NYC3 region, which minimizes network latency between the application and database. DigitalOcean’s VPC networking ensures that traffic between your app and database travels over a private network without traversing the public internet.

Automating Infrastructure Operations

In this step, you will use the DigitalOcean MCP server to automate common infrastructure tasks. By managing your database and application through a single MCP server, you can execute complex multi-service operations through natural language commands instead of navigating separate dashboards.

Scaling Application Resources

When your application experiences increased traffic, you can scale your compute resources. Open your MCP client and send the following message:

My application is experiencing high load. Increase the app resources to 1GB RAM containers.

The MCP server will execute this operation through DigitalOcean’s API and trigger a new deployment with larger containers.

Creating Staging Environments

You can create isolated staging environments to test changes before deploying to production. Before creating a staging environment, ensure you have a separate branch for development deployments. Create a dev branch in your repository by running:

git checkout -b dev 
git push origin dev

Then send the following message to your AI assistant:

Create a staging environment: create a new MongoDB cluster named "tasks-staging" in NYC3, duplicate my production app with the name "task-api-staging" using the dev branch, and connect the staging app to the staging database.

Your AI assistant will orchestrate the following operations:

  1. Create a new MongoDB cluster with the staging name
  2. Create a database user for the staging environment
  3. Create a new App Platform application using your dev branch
  4. Configure the staging application’s MONGODB_URI environment variable to point to the staging database
  5. Deploy the staging application

This workflow enables you to test database schema changes and application updates in isolation. You can verify changes in staging before promoting them to production, reducing the risk of production incidents.

This ability is valuable to a DevOps team, as simple production incidents can often delay time-to-market.

Managing Database Access and Security

You can configure database access controls through conversational commands. To add your application’s trusted source, you can ask:

Configure my mdb-do-mcp database firewall to allow connections from my task-api App Platform application.

The MCP server will add your application to your database cluster’s trusted sources list. This configuration ensures that only your specific application can connect to the database, following the principle of least privilege access.

For additional database users with limited permissions, you can request:

Create a new MongoDB user named "analytics-reader" on my production cluster with read-only access to the tasks database.

The MCP server will create a user with the appropriate predefined role for read-only access. This separation of concerns allows analytics tools to query data without risking accidental modifications.

Implementing Production Best Practices

In this step, you will implement configuration improvements for production deployments. These practices improve security, reliability, and performance for your application and database.

Implementing High Availability

For production deployments, you should configure your MongoDB cluster with multiple nodes to ensure high availability. A three-node cluster configuration includes one primary node and two secondary nodes. If the primary node fails, one of the secondary nodes is automatically promoted to primary and begins serving requests while DigitalOcean provisions a replacement secondary node in the background. When creating a production MongoDB cluster, specify the desired node count during the initial setup. Open your MCP client and send the following message:

Create a new MongoDB database cluster named tasks-prod-ha in NYC3 with 3 nodes for high availability. Use the 2GB RAM node size. Once created, show me the connection details.

MongoDB’s driver automatically handles failover by maintaining connections to all nodes in the replica set. When a primary node fails, the driver detects the failover and routes subsequent operations to the newly promoted primary node. This process typically completes within seconds, minimizing disruption to your application.

To move your data from the existing single-node cluster to your new high-availability cluster, you will need to manually migrate the data using MongoDB’s native tools. Your AI assistant can provide detailed migration instructions. Ask:

Help me migrate data from my existing mdb-do-mcp cluster to the new mdb-do-mcp-ha cluster using mongodump and mongorestore.

Your AI assistant will provide the exact commands to run, connection strings to use, and verification steps for the manual migration process. Additionally, you leverage both product documentation and tutorials for manual migrations.

Implementing Connection Pooling

Your current application code creates a single MongoClient instance that is reused for all requests. This approach implements connection pooling automatically. The MongoDB driver maintains a pool of connections to the database, reusing them across requests instead of creating new connections. To understand how indexes affect MongoDB query speed, see How To Use Indexes in MongoDB.

You can verify your application’s connection settings by asking:

Show me the current environment variables and configuration for my task-api application.

For high-traffic applications, consider adjusting the connection pool size by adding configuration to your MongoClient instantiation:

const client = new MongoClient(process.env.MONGODB_URI, {
  maxPoolSize: 50,
  minPoolSize: 10
});

These settings maintain at least 10 connections and allow up to 50 concurrent connections to the database. DigitalOcean’s Managed MongoDB handles thousands of concurrent connections, and proper pooling ensures your application efficiently uses available capacity.

You have implemented some production best practices for your MongoDB database and application deployment. These configurations follow DigitalOcean’s database best practices and App Platform deployment guidelines.

Frequently Asked Questions

1. What is the DigitalOcean MCP server?

The DigitalOcean MCP server is a background process that exposes DigitalOcean’s APIs to AI clients through the Model Context Protocol. It lets you manage databases, applications, and other cloud resources using natural language commands in tools like Claude Desktop, Cursor, or Claude Code.

2. How does MCP differ from using the DigitalOcean API directly?

MCP wraps the API behind a natural language interface. Instead of writing API calls or clicking through dashboards, you describe what you want in plain English. The MCP server translates your request into the appropriate API operations. The underlying API actions are the same.

3. Is the DigitalOcean MCP server free to use?

The MCP server itself is free and open source. You install it with npx @digitalocean/mcp. The DigitalOcean resources you create through it (databases, apps, Droplets) follow standard DigitalOcean pricing.

4. What happens if my MongoDB cluster node fails?

With a single-node cluster, your database becomes unavailable until the node recovers. A three-node cluster (one primary, two secondaries) provides automatic failover. When the primary fails, MongoDB promotes a secondary to primary within seconds. DigitalOcean provisions a replacement node in the background.

5. How do I connect my App Platform application to a DigitalOcean Managed MongoDB cluster?

Set the MONGODB_URI environment variable in your App Platform application configuration. Use the connection string from your database cluster, which includes the hostname, authentication credentials, and TLS settings. Traffic between App Platform and the database travels over DigitalOcean’s private VPC network.

Conclusion

You built and deployed a task management API using MongoDB and DigitalOcean App Platform. You configured the DigitalOcean MCP server to automate infrastructure provisioning, deployed a Node.js application with database connectivity, and set up production configurations through natural language commands.

DigitalOcean’s Managed MongoDB provided automatic backups, high availability options, and encryption at rest. The MCP server automated workflows that typically require multiple dashboards and API call sequences. All services stayed within DigitalOcean’s ecosystem, simplifying billing, support, and network configuration.

For more information about the services used in this tutorial, visit:

Build Your Next App on DigitalOcean

Ready to deploy your own application with MongoDB and the MCP server? Sign up for DigitalOcean and get $200 in free credit. Start with Managed MongoDB for your database and App Platform for your application deployment. Use the DigitalOcean MCP server to manage both from your AI-enabled editor.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Nestor Daza
Nestor Daza
Author
Anish Singh Walia
Anish Singh Walia
Editor
Sr Technical Writer
See author profile

I help Businesses scale with AI x SEO x (authentic) Content that revives traffic and keeps leads flowing | 3,000,000+ Average monthly readers on Medium | Sr Technical Writer @ DigitalOcean | Ex-Cloud Consultant @ AMEX | Ex-Site Reliability Engineer(DevOps)@Nutanix

Still looking for an answer?

Was this helpful?


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

Creative CommonsThis work is licensed under a Creative Commons Attribution-NonCommercial- ShareAlike 4.0 International License.
Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

The developer cloud

Scale up as you grow — whether you're running one virtual machine or ten thousand.

Get started for free

Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

*This promotional offer applies to new accounts only.