Skip to content
GitHub (opens in a new tab)

Databases · MCP Firewall integration

Scope MongoDB reads. Approve updates. Verify the result.

Place a scoped MongoDB connection behind GateRook’s MCP Firewall. Follow the illustrated walkthrough to restrict database and collection access, find documents, summarize a collection, approve one update, and verify both its result and the recorded decisions in Activity.

Step-by-step walkthrough

Control AI operations in MongoDB with GateRook’s MCP Firewall

GateRook’s MCP Firewall gives an AI app controlled access to MongoDB. You configure the database credential once, expose the connection through an endpoint, and choose which tools can read immediately and which require a person to approve a change. Activity links each request to its policy decision and execution result.

This walkthrough uses GateRook 0.7.0 on macOS, MongoDB 7.0.34 in Docker Desktop, and Codex's existing showcase development endpoint. It creates a separate mongodb-demo connection and four fictional orders, then demonstrates a document query, an aggregation, and an update with approval.

New to GateRook? Set up your endpoint and AI app first.

1. Start an isolated MongoDB server

Keep Docker Desktop and GateRook running. This example assumes that showcase already exists and your AI app is connected to it. The container uses host port 17017, so another MongoDB instance on 27017 can continue running.

Create a private working directory and generate separate passwords for the administrator and tutorial user:

Shell commands
mkdir -p ~/gaterook-mongodb-demo
cd ~/gaterook-mongodb-demo
umask 077

python3 - <<'PY'
from pathlib import Path
import secrets

path = Path("mongo.env")
with path.open("x") as output:
    output.write(
        "MONGO_INITDB_ROOT_USERNAME=demo_admin\n"
        "MONGO_INITDB_ROOT_PASSWORD=" + secrets.token_hex(24) + "\n"
        "MONGO_INITDB_DATABASE=gaterook_demo\n"
        "DEMO_PASSWORD=" + secrets.token_hex(24) + "\n"
    )
path.chmod(0o600)
PY

Keep mongo.env outside version control. Create init.js alongside it:

MongoDB initialization script
const demo = db.getSiblingDB('gaterook_demo');
demo.orders.insertMany([
  { _id: 1001, customer_name: 'Avery Stone', status: 'pending', total_cents: 12990 },
  { _id: 1002, customer_name: 'Morgan Reed', status: 'paid', total_cents: 8900 },
  { _id: 1003, customer_name: 'Riley Chen', status: 'pending', total_cents: 24900 },
  { _id: 1004, customer_name: 'Jordan Lee', status: 'shipped', total_cents: 4950 }
]);
demo.createRole({
  role: 'orderUpdater',
  privileges: [{
    resource: { db: 'gaterook_demo', collection: 'orders' },
    actions: ['update']
  }],
  roles: []
});
demo.createUser({
  user: 'demo_agent',
  pwd: process.env.DEMO_PASSWORD,
  roles: [
    { role: 'read', db: 'gaterook_demo' },
    { role: 'orderUpdater', db: 'gaterook_demo' }
  ]
});

The tutorial account can read this database and update documents in orders. It has no insert, delete, or administrator privileges. The custom update privilege makes it possible to demonstrate approval without using the root account. Amounts are stored as integer cents to keep the arithmetic straightforward.

Start the container:

Shell commands
docker run -d \
  --name gaterook-mongodb-showcase \
  -p 127.0.0.1:17017:27017 \
  --env-file mongo.env \
  --mount "type=bind,source=$(pwd)/init.js,target=/docker-entrypoint-initdb.d/01-demo.js,readonly" \
  --health-cmd='mongosh --quiet --eval '\''const d = db.getSiblingDB("gaterook_demo"); d.auth("demo_agent", process.env.DEMO_PASSWORD); if (d.orders.countDocuments({}) !== 4) quit(1)'\''' \
  --health-interval=2s \
  --health-timeout=5s \
  --health-retries=30 \
  mongo:7.0.34-jammy

docker inspect --format '{{.State.Health.Status}}' \
  gaterook-mongodb-showcase

Wait for healthy. This check authenticates as demo_agent and verifies that the collection contains four documents. Choose another container name or host port if either is already in use.

The published port is bound to loopback. The official image creates the root account in admin; our script creates demo_agent in gaterook_demo. Initialization scripts run only for an empty data directory, so editing the script or environment file does not reinitialize an existing database. See the official MongoDB image documentation.

2. Choose the MongoDB connector

Open Connections. For these screenshots, the list is filtered to mongodb-demo to keep unrelated connections out of view. No match is expected before the connection exists.

Connections filtered to mongodb-demo before adding the connection.
Connections filtered to mongodb-demo before adding the connection.

Select Add connection → MongoDB → Continue. The built-in connector provides four tools: two for reading documents and two for updating them.

MongoDB selected in the Add connection wizard.
MongoDB selected in the Add connection wizard.

3. Enter the server and credentials

Use these connection settings:

FieldValue
Namemongodb-demo
Connect usingHost and port
Host127.0.0.1
Port17017
Connection typeWithout TLS, for this disposable loopback-only server

The name identifies the connection in tool calls, policies, and Activity. A saved connection cannot be renamed. GateRook connects from the computer running its core, so use the published host port, not the container's internal port.

MongoDB server settings with the tutorial's loopback address and port.
MongoDB server settings with the tutorial's loopback address and port.

Under Credentials, keep Encrypted here, enter demo_agent, and paste only the DEMO_PASSWORD value from your private environment file. Do not use MONGO_INITDB_ROOT_PASSWORD or paste passwords into your AI conversation.

GateRook stores the password encrypted with its local master key. Later MCP calls identify the connection by name; the MongoDB password is supplied inside the connector and is not part of the AI's query arguments.

Encrypted here selected, demo_agent entered, and the password masked.
Encrypted here selected, demo_agent entered, and the password masked.

This local fixture does not configure TLS. For a remote server, choose TLS and use certificate and host-name verification; supply a CA certificate when the server uses a private CA. Do not carry the local fixture's unencrypted setting into a remote deployment.

4. Set the authentication database and collection scope

Expand Advanced before loading databases:

FieldValue
CA certificateEmpty for this local fixture
Skip the host name checkUnchecked
Read preferenceprimary
Auth databasegaterook_demo
Mechanismauto
Collections the agent may readAdd gaterook_demo.orders with the + button
Query time limitEmpty, to inherit the environment policy
Pool size2
Server selection timeout5000 ms

Auth database is where the user was created. Leaving the default admin would authenticate this tutorial user against the wrong database. It is separate from the database selection that controls what the agent may use.

The collection entry is a complete namespace: database plus collection. Check that it appears as a chip after pressing +. The selected database and collection allowlist further restrict what this connection exposes; they do not grant MongoDB privileges.

Advanced settings with gaterook_demo as the authentication database and gaterook_demo.orders as the allowed namespace.
Advanced settings with gaterook_demo as the authentication database and gaterook_demo.orders as the allowed namespace.

5. Load and select the database

Select Load databases, then tick gaterook_demo. The wizard should show 1 databases available · 1 selected. Discovering a database and selecting it are separate steps.

Keep DEV Development selected. Its description states that mutations still wait for approval. Reload the database list if you change the server, credentials, or authentication settings.

The tutorial database selected and the DEV environment retained.
The tutorial database selected and the DEV environment retained.

6. Test the connection

Select Continue. GateRook connects with the entered settings and reports the server version, identity, and permissions.

This run returned Connected · MongoDB 7.0.34, identified demo_agent@gaterook_demo, and reported update on gaterook_demo.orders through the custom orderUpdater role.

Successful MongoDB connection test showing read access and the narrowly scoped update privilege.
Successful MongoDB connection test showing read access and the narrowly scoped update privilege.

The write warning is expected because the walkthrough includes an approved update. For read-only use, omit the custom update role. An approval does not grant permissions that the database account lacks; for example, this account cannot insert a document through an upsert.

7. Attach the connection to showcase

Continue to Add to endpoint. Untick default and tick only showcase. Review the default tool modes and select Save connection.

The saved page confirms Healthy, 1 endpoint, and 4 tools on showcase · Codex. The saved credential is write-only: its settings show an encrypted version and offer replacement, not a readable password.

The saved mongodb-demo connection is healthy and used by showcase.
The saved mongodb-demo connection is healthy and used by showcase.

8. Understand the route and tool modes

Open Endpoints → showcase. The diagram shows the route from Codex to the endpoint, its policy and limits, and the connections behind it. The endpoint now includes mongodb-demo alongside the existing tutorial connections.

The showcase endpoint diagram with Codex connected and mongodb-demo healthy.
The showcase endpoint diagram with Codex connected and mongodb-demo healthy.

In Tools & policies, search for mongo_ and inspect the four tools:

ToolMode in this walkthroughBehavior
mongo_findRead onlyFinds documents with a filter, projection, sort, and result limit.
mongo_aggregateRead onlyRuns a read aggregation pipeline; $out and $merge are refused.
mongo_updateApprovalUpdates the first matching document after a person approves the exact action.
mongo_update_manyApprovalUpdates every matching document after approval. The read result limit does not cap the number of updates.
MongoDB read tools in Read only and update tools in Approval mode.
MongoDB read tools in Read only and update tools in Approval mode.

Keep the update tools in Approval for this walkthrough. A call names the connection, database, and collection. GateRook checks access, tool mode, policy, and limits, then uses the stored credential and records the outcome. The advertised read limits here are 1,000 documents and five seconds; our requests ask for at most ten documents.

If the AI app still shows its previous tool list, refresh its MCP connection. All five demonstration tool calls passed through the authenticated showcase endpoint. Activity identifies the client as Codex.

9. Find documents and summarize the collection

Ask your AI app:

Through showcase, use mongodb-demo, database gaterook_demo, collection orders. Show all four orders sorted by _id. Then show pending orders with only _id, status, and total_cents. Finally, summarize the order count and total_cents by status.

The initial mongo_find arguments were:

JSON
{
  "connection": "mongodb-demo",
  "database": "gaterook_demo",
  "collection": "orders",
  "filter": {},
  "sort": { "_id": 1 },
  "limit": 10
}

The result contained four documents, with truncated: false:

_idcustomer_namestatustotal_cents
1001Avery Stonepending12990
1002Morgan Reedpaid8900
1003Riley Chenpending24900
1004Jordan Leeshipped4950

Open Activity → Agent calls, enter the following filter, and press Enter:

Activity filter
endpoint:showcase connection:mongodb-demo

Open the first mongo_find event. Request identifies the client, endpoint, and transport. Arguments records the exact filter, sort, and limit.

The initial mongo_find request in Activity with its exact arguments.
The initial mongo_find request in Activity with its exact arguments.

Scroll down to Policy decision, Result, and Timing. This read was Allowed and ran immediately. The event shows four documents in its result summary, the response size and hash, and zero masked fields for this fictional dataset.

The allowed read decision and four-document result summary in Activity.
The allowed read decision and four-document result summary in Activity.

The second mongo_find used a filter and projection:

JSON
{
  "connection": "mongodb-demo",
  "database": "gaterook_demo",
  "collection": "orders",
  "filter": { "status": "pending" },
  "projection": { "_id": 1, "status": 1, "total_cents": 1 },
  "sort": { "_id": 1 },
  "limit": 10
}

It returned orders 1001 and 1003, without customer_name. The projection selects fields explicitly; it is not evidence that an automatic personal-data masking rule matched.

The filtered read returns only the two pending orders and the three requested fields.
The filtered read returns only the two pending orders and the three requested fields.

The mongo_aggregate call grouped the documents by status:

JSON
{
  "connection": "mongodb-demo",
  "database": "gaterook_demo",
  "collection": "orders",
  "pipeline": [
    {
      "$group": {
        "_id": "$status",
        "order_count": { "$sum": 1 },
        "total_cents": { "$sum": "$total_cents" }
      }
    },
    { "$sort": { "_id": 1 } }
  ],
  "limit": 10
}
_id (status)order_counttotal_cents
paid18900
pending237890
shipped14950
The aggregation's allowed policy decision and three status totals in Activity.
The aggregation's allowed policy decision and three status totals in Activity.

10. Request an update and review the exact action

Ask the AI to change order 1001 from pending to shipped, only if it is still pending. The mongo_update request is:

JSON
{
  "connection": "mongodb-demo",
  "database": "gaterook_demo",
  "collection": "orders",
  "filter": { "_id": 1001, "status": "pending" },
  "update": { "$set": { "status": "shipped" } },
  "upsert": false
}

GateRook returns a pending approval handle: the update has not executed. The AI displays the approval card once and polls approval_status with that handle. It must not repeat the original mutation while waiting.

The chat approval card is waiting for a person to review mongo_update.
The chat approval card is waiting for a person to review mongo_update.
The mongo_update event is waiting for approval, with its exact filter and update arguments.
The mongo_update event is waiting for approval, with its exact filter and update arguments.

In Approvals, review mongo_update on mongodb-demo, endpoint showcase, environment DEV. The matched rule is dev.mongodb.write-approval. The exact action is the prepared MongoDB command, including the filter, $set, multi: false, upsert: false, write concern, and a five-second time limit.

The impact panel identifies database gaterook_demo, collection orders, at most one affected document, and upsert disabled. This describes the operation's scope; the completed result establishes how many documents actually matched and changed.

Add an optional comment, then select Approve and run, or Deny to refuse the action. Only a person can approve in GateRook. Opening the chat card does not approve anything, and an unanswered request expires at its displayed deadline. Leave temporary bypass unused so future changes still require approval.

Activity links the pending update to dev.mongodb.write-approval and records the approval request and desktop notification.
Activity links the pending update to dev.mongodb.write-approval and records the approval request and desktop notification.

In this run, the operator approved request ap_t8c7tu481u0x at 10:54:12 on November 3, 2026 (Europe/Madrid), after a wait of four minutes and fifteen seconds. The card changed to Completed.

The same approval card shows Completed after the operator approved the update.
The same approval card shows Completed after the operator approved the update.

The completed tool result was:

JSON
{
  "tool": "mongo_update",
  "connection": "mongodb-demo",
  "database": "gaterook_demo",
  "collection": "orders",
  "acknowledged": true,
  "matchedCount": 1,
  "modifiedCount": 1,
  "upsertedId": null,
  "elapsedMs": 32
}

One existing document matched and changed. No document was inserted. The event is now Approved, with the original arguments still visible.

The completed update is marked Approved in Activity, with the original conditional update arguments.
The completed update is marked Approved in Activity, with the original conditional update arguments.

11. Read the document again to verify the change

Ask the AI to retrieve order 1001 through the same connection. This is a new mongo_find call:

JSON
{
  "connection": "mongodb-demo",
  "database": "gaterook_demo",
  "collection": "orders",
  "filter": { "_id": 1001 },
  "limit": 1
}

The call returned one document with truncated: false:

JSON
{
  "_id": 1001,
  "customer_name": "Avery Stone",
  "status": "shipped",
  "total_cents": 12990
}

The update acknowledgement and this subsequent read provide two separate checks: MongoDB reported one modification, and the document now has the requested status.

A separate allowed read confirms that order 1001 now has status shipped.
A separate allowed read confirms that order 1001 now has status shipped.

The update uses a conditional filter. Repeating it after this change would match zero documents because order 1001 is no longer pending.

12. Follow the complete operation history

Return to Activity → Agent calls and keep the filter endpoint:showcase connection:mongodb-demo. The completed walkthrough has five events, shown newest first:

CallDecisionObserved outcome
Verify order 1001 with mongo_findAllowedOne document, status shipped.
Change its status with mongo_updateApprovedOne matched, one modified.
Summarize with mongo_aggregateAllowedThree status groups before the update.
Filter pending orders with mongo_findAllowedTwo projected documents before the update.
Read all orders with mongo_findAllowedFour documents before the update.
Activity filtered to showcase and mongodb-demo shows all five successful calls, including the approved update.
Activity filtered to showcase and mongodb-demo shows all five successful calls, including the approved update.

Open the approved update and scroll to Approval. The timeline records the request, desktop notification, human decision, and execution. It also records the approved action's SHA-256 and confirms that the executed command matches the approved action, byte for byte. Approval waiting time is separate from execution time: this event waited four minutes and fifteen seconds and then executed in 33 ms total.

The approval timeline records the human decision, execution, matching action hash, and one modified document.
The approval timeline records the human decision, execution, matching action hash, and one modified document.

Use the event panels to answer specific questions:

PanelWhat to check
RequestWhich client and token alias called which endpoint. The alias is not the token secret.
ArgumentsThe connection, namespace, filter, projection, pipeline, or update requested.
Policy decisionWhich rules and limits were evaluated, and why the operation ran or waited.
ApprovalWhen a person decided, what action was approved, and whether that exact action executed.
ResultExecution status, a result summary, response size and hash, and masked-field count.
TimingTime spent in the gateway and the resource, separate from the approval wait.

View raw or Show JSON exposes the stored event; Copy link gives a local link back to it. Filter by this tool and View in Insights help investigate related calls. Treat Activity as an audit record with result summaries and metadata, rather than a complete archive of every returned document. Masking depends on the configured rules; the fictional data in this walkthrough matched zero masking fields.

Keep or stop the demo

The connection is attached only to showcase. You can keep the container running to repeat reads and inspect Activity.

To pause access while retaining the connection, turn its On switch off. This affects the connection across endpoints. Turning an endpoint off pauses access through that endpoint; past Activity remains available.

Stop the fixture without deleting its data:

Shell commands
docker stop gaterook-mongodb-showcase

Resume it later:

Shell commands
docker start gaterook-mongodb-showcase

Wait for healthy, then use Test connection in GateRook. The health check expects the original four documents; the demonstrated status update does not change their count. Keep the private environment and initialization files for this fixture, and do not commit the generated passwords.

Useful access. Explicit control.

What you can do with MongoDB and AI

Investigate one document

Filter by an application identifier and project only the fields needed for the question. Verify the requested arguments and returned summary in Activity.

Summarize a collection

Group orders by status and sum integer amounts with mongo_aggregate. Read aggregations run without a mutation approval; write stages are refused.

Make a reviewed change

Ask for a conditional update, inspect the exact action, and approve it in GateRook. Read the document again and follow the human decision and execution in Activity.

Connection settings

Configure MongoDB in GateRook

These are example values for the connection form. Enter credentials into GateRook’s secret fields, not into an AI prompt. Requirements and alternatives are noted per field.

MongoDB connection configuration
SettingExampleHow to use it
Name / environmentmongodb-demo / DEVChoose MongoDB. The connection name identifies it in tool calls and Activity; changes still require approval in this walkthrough.
Connect using / host / portHost and port / 127.0.0.1 / 17017Use the Docker port published on the GateRook computer. Connection strings are also supported; enter credentials separately.
Credentials / user / passwordEncrypted here / demo_agent / Enter in GateRookUse DEMO_PASSWORD from the private environment file. The account has read access to gaterook_demo and update access only to orders.
Auth database / mechanismgaterook_demo / autoAuthenticate against the database where demo_agent was created. The default admin is wrong for this fixture.
Connection type / read preferenceWithout TLS / primaryWithout TLS is only for this loopback-only fixture. Use TLS with certificate and host-name verification for a remote server.
Database / collectionsgaterook_demo / gaterook_demo.ordersLoad and select the database. Add the full collection namespace with the + button in Advanced; account privileges remain a separate boundary.
Query time / pool / server selection timeoutInherit environment / 2 / 5000 msThis walkthrough inherits a five-second query limit. Server selection timeout controls how long the driver waits to find a server.
Endpoint / tool modesshowcase / Read only and ApprovalAttach only to showcase. Keep mongo_find and mongo_aggregate in Read only; keep both update tools in Approval.

Know what you expose

MongoDB tools and access boundaries

The connector defines available operations. GateRook’s MCP Firewall enforces endpoint modes and connection policies before an AI client can use them.

Available tools and access behavior
ToolPurposeAccess behavior
mongo_findFind documents using a filter, projection, sort, limit and skip.Read only in this walkthrough
mongo_aggregateRun a bounded read aggregation pipeline. Write stages such as $out and $merge are refused.Read only in this walkthrough
mongo_updateUpdate the first matching document. Review the exact filter, update, and upsert setting.Approval in this walkthrough; database update privileges are also required
mongo_update_manyUpdate every matching document. The read result limit does not cap the number of updates.Approval in this walkthrough; scope the filter before approving

Before you enable access

  • The connector exposes mongo_find, mongo_aggregate, mongo_update and mongo_update_many. This walkthrough keeps reads in Read only and updates in Approval.
  • Approval does not grant database privileges. The demo account can update existing orders but has no insert or delete privilege; it cannot create a document through an upsert.
  • Selected databases and the collection allowlist restrict the connection. Keep the database account scoped as well; use a complete namespace such as gaterook_demo.orders.
  • Aggregation stages $out and $merge are refused. Read document limits do not cap the number of documents changed by mongo_update_many.
  • An approval request is not an execution result. Poll the existing handle, inspect matchedCount and modifiedCount after completion, then verify the document with a separate read.
  • Activity records policy decisions, approval history, result summaries and response metadata. Masking follows configured rules; a projection alone does not establish automatic masking.

GateRook stores local connection secrets encrypted and resolves them for connectors. Allowed tool results are returned to your AI client and may be processed by its provider. Scope the data you expose as well as the actions you allow.

Practical answers

MongoDB connection questions

Use Test connection to isolate service access problems. Use Playground and Activity to inspect endpoint permissions and tool calls.

Why does authentication fail even with the right password?

Set Auth database to the database where the user was created. This tutorial creates demo_agent in gaterook_demo, not admin. Use the host port 17017, then run Test connection.

Can I use a MongoDB Atlas connection string?

The connector accepts mongodb+srv:// as well as mongodb://. Supply credentials separately, allow the GateRook computer to reach the deployment, use TLS, and test your configuration.

Can the AI update documents?

Yes. mongo_update changes the first match and mongo_update_many changes every match. Keep them in Approval, review the filter and exact action, and use an account with only the required privileges.

How do I expose only one collection?

Select gaterook_demo and add gaterook_demo.orders under Collections the agent may read in Advanced. Confirm the namespace appears as a chip, and scope the database account to the same data.

Why does Codex still show the old tool list?

Confirm that the connection is attached to showcase and the tools are enabled, then refresh the AI app’s MCP connection. The endpoint’s Tools & policies view shows the current tool modes.

How do I confirm an approved update actually ran?

Check the completed result for acknowledged, matchedCount and modifiedCount. Read the document again, then filter Activity by endpoint:showcase connection:mongodb-demo to inspect the decision, exact-action match and outcome.

Keep exploring

PostgreSQL

Put PostgreSQL behind GateRook’s MCP Firewall. Follow the illustrated setup, scope AI queries, approve an UPDATE and inspect its Activity audit trail.

Redis

Protect Redis access with scoped, read-only MCP tools. Follow the GateRook Docker tutorial to approve a value read and inspect its Activity record.

Loki

Control AI access to Loki logs with GateRook. Configure tenant and source scope, keep credentials local and bound LogQL results and time ranges.

Browse all integration guides

Your MCP Firewall. Your access rules.

Control AI access to MongoDB.

Start with read-only access. Approve changes. Inspect the audit trail.

Read the getting started guide

Get GateRook

Download GateRook 0.9.2 for your Mac, or get the Windows app from Microsoft Store.

macOS

Version 0.9.2 for Apple Silicon (arm64). This download does not support Intel Macs.

Open the DMG and drag GateRook to Applications.

Windows

Available for free from Microsoft Store. Install GateRook and receive updates through the Store.

macOS release notes and checksums (opens in a new tab)