Gateway
MongoDB tools
find, count, insert, update and delete as an agent expects them, with the filters and updates that work, run in the run’s own copy.
Self-hostedChronos Gateway runs on your own servers today. Releases and install script. The engine under it: Chronos DB, self-hosted
A run beside MongoDB has MongoDB’s own tools as well as SQL: find, count, insert, update_one, update_many, delete_one and delete_many. An agent that knows MongoDB calls them as it expects to. None of them reaches MongoDB. Each call becomes SQL in the run’s own copy of the data, run as the run’s agent, so the tenant’s scope, masks and the rules apply as they do with SQL. What the run changed goes to MongoDB only when the run is proposed and merged.
This page describes gateway 0.4.4 on Chronos DB (the engine) 0.6.2.
What it needs
| Requirement | |
|---|---|
| MongoDB | 5.0 or later, as a replica set (one member is enough). 5.0 and 7.0 are tested, run locally in containers. A managed service such as Atlas is not tested: try yours on a staging copy first. |
| Not supported | A standalone server and a sharded cluster. Views, time-series collections and capped collections are refused at attach. |
| URL | mongodb://user:password@host:27017/database or mongodb+srv://.... The URL names the database. |
| Engine | An engine built with MongoDB, 0.5.0 or later. $regex, date comparisons and GATEWAY_FOLLOW need gateway 0.3.1 and engine 0.5.1. |
| Role | The connection check’s role_sql is a mongosh script. It makes a role with rights on the attached collections and on the engine’s own two (chronos_merges, chronos_merge_rows), and a user with that role. |
Connecting is the same three steps as beside any database: look, make the role, attach. See Connect a database and Postgres, MySQL, MariaDB, MongoDB.
How a collection is held
The engine keeps each attached collection as a table. A document is one row with three parts:
| Part | Holds |
|---|---|
| _id | The document’s _id, the table’s key. An ObjectId is kept as its 24 hex digits; a string or a number is kept as it is. |
| the fields you name | Each field named in fields at attach is a column of its own, holding a string, an integer or an ObjectId. The tenant’s field is always one of them. |
| doc | The rest of the document, as jsonb, in relaxed Extended JSON. |
The tools put the three parts back together. A document a tool answers has _id first, then the fields kept as columns (one that is empty is left out), then the rest. An ObjectId reads as {"$oid": "..."}.
{ "_id": {"$oid": "66f1a2b3c4d5e6f708192a3b"}, "org_id": 42, "status": "open", "name": "Acme", "address": {"city": "Pune", "zip": "411001"}, "tags": ["priority", "west"], "seen": {"$date": "2026-01-31T10:00:00Z"}}Fields at attach
POST /v1/connect takes fields beside MongoDB: the fields kept as columns of their own. With GATEWAY_SOURCE_FILE, the setting GATEWAY_FIELDS names them (comma-separated). The tenant’s field (tenant_column) is added for you.
curl -s "$GATEWAY/v1/connect" -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"url": "mongodb://chronos_gateway:ROLE_PASSWORD@db.internal:27017/app", "tables": ["leads", "notes"], "tenant_column": "org_id", "fields": ["status", "email"]}'Name a field in fields for one of three reasons:
- It is the tenant’s field. The engine holds a run to its tenant by a column. This one is added without being named.
- You mask it. A field must be a column to be masked (
PUT /v1/masks). A field insidedoccan’t be masked alone. - Agents filter by it. A run’s checked read narrows to a condition only on a column. A condition on a field inside
doccounts as a read of the whole collection, so any change to the collection in MongoDB meanwhile can hold the run’s merge (check_reads).
The connection check says which fields can be columns. POST /v1/connect/check answers source: "mongodb", each collection as a table with key ["_id"], columns (the top-level fields of its first 100 documents), and fields: for each, {name, type, in, of, column}. column is true when every one of those documents has the field as a string, an integer or an ObjectId.
Calling a tool
There are two ways in. Both take the run’s token (cgr_...), not a developer key.
Over HTTP
POST /v1/runs/:id/mongo with {tool, arguments}. tool is the name with or without mongo_: find and mongo_find are the same. The answer is the tool’s result as JSON.
curl -s "$GATEWAY/v1/runs/$RUN/mongo" -H "Authorization: Bearer $RUN_TOKEN" -H 'Content-Type: application/json' \ -d '{"tool": "find", "arguments": {"collection": "leads", "filter": {"status": "open"}, "limit": 2}}'{"documents": [ {"_id": {"$oid": "66f1a2b3c4d5e6f708192a3b"}, "org_id": 42, "status": "open", "name": "Acme"}, {"_id": {"$oid": "66f1a2b3c4d5e6f708192a3c"}, "org_id": 42, "status": "open", "name": "Hooli"} ], "limit": 2}Over MCP
The run’s MCP endpoint (mcp_url, POST /v1/runs/:id/mcp) lists the same tools beside the world tools, under these names: mongo_find, mongo_count, mongo_insert, mongo_update_one, mongo_update_many, mongo_delete_one, mongo_delete_many. An MCP client calls them as any tool:
{"jsonrpc": "2.0", "id": 1, "method": "tools/call", "params": {"name": "mongo_count", "arguments": {"collection": "leads", "filter": {"status": "open"}}}}Each document a call writes counts as one statement against GATEWAY_RUN_STATEMENTS_PER_MINUTE (120 by default), and a call that writes none as one. A call with more writes than the minute has left is refused whole (429), before the first is written. A run beside Postgres, MySQL or MariaDB doesn’t have these tools: a call answers 400 and says to use SQL.
The seven tools
| Tool | Arguments | Answers |
|---|---|---|
| find | collection, filter, projection, sort, limit (20), skip | {documents, limit} |
| count | collection, filter | {count} |
| insert | collection, documents | {inserted_ids}. Without _id, a new ObjectId each |
| update_one | collection, filter, update | {matched_count, modified_count} |
| update_many | collection, filter, update | {matched_count, modified_count} |
| delete_one | collection, filter | {deleted_count} |
| delete_many | collection, filter | {deleted_count} |
find
Finds documents in the run’s own copy, what the run has changed included. collection is required. Without a filter it matches every document of the run’s tenant. Without a sort the order is by _id. limit is 20 unless given. The answer’s limit is the limit that was used.
{"tool": "find", "arguments": { "collection": "leads", "filter": {"status": {"$in": ["open", "won"]}, "address.city": "Pune"}, "projection": {"name": 1, "status": 1}, "sort": [{"status": 1}, {"name": -1}], "limit": 50, "skip": 50}}{"documents": [{"_id": {"$oid": "66f1a2b3c4d5e6f708192a3b"}, "status": "open", "name": "Acme"}], "limit": 50}count
{"tool": "count", "arguments": {"collection": "leads", "filter": {"status": "open"}}}{"count": 17}insert
documents is an array of documents, at least one, 1,000 at most a call. A document without _id gets a new ObjectId. An _id you give is an ObjectId ({"$oid": "..."}), a string or a number. A field name may not be empty, hold a dot, or start with $. The run’s tenant field must be the run’s tenant: the engine refuses a row for another.
{"tool": "insert", "arguments": {"collection": "notes", "documents": [ {"org_id": 42, "lead": {"$oid": "66f1a2b3c4d5e6f708192a3b"}, "text": "Called, asked for a quote"}, {"_id": "note-7", "org_id": 42, "text": "Follow up on Friday"}]}}{"inserted_ids": [{"$oid": "66f1a2b3c4d5e6f708192a40"}, "note-7"]}update_one and update_many
filter and update are both required. update_one changes the first document the filter matches, by _id order. update_many changes every document it matches. matched_count is how many documents the filter matched; modified_count is how many the update changed (a document the update leaves as it was isn’t counted). _id can’t be changed. An update_many whose filter matches more than 1,000 documents is refused and changes nothing. It is not cut to the first 1,000.
{"tool": "update_one", "arguments": {"collection": "leads", "filter": {"_id": {"$oid": "66f1a2b3c4d5e6f708192a3b"}}, "update": {"$set": {"status": "won", "address.city": "Mumbai"}, "$inc": {"touches": 1}}}}{"matched_count": 1, "modified_count": 1}{"tool": "update_many", "arguments": {"collection": "leads", "filter": {"owner": "bo", "status": "open"}, "update": {"$set": {"owner": "ada"}}}}{"matched_count": 12, "modified_count": 12}delete_one and delete_many
filter is required. delete_one deletes the first document the filter matches, by _id order. delete_many deletes every one it matches, and refuses {}: delete_many with no filter would delete every document: name what to delete. A delete_many whose filter matches more than 1,000 documents is refused and deletes nothing. It is not cut to the first 1,000.
{"tool": "delete_many", "arguments": {"collection": "notes", "filter": {"lead": {"$oid": "66f1a2b3c4d5e6f708192a3b"}}}}{"deleted_count": 3}Filters
A filter is MongoDB’s, the common part. Every condition in one filter object must hold. Fields are top-level names or dotted paths into nested objects (address.city).
| Operator | Matches | Example |
|---|---|---|
| (a plain value) | Equality, the same as $eq | {"status": "open"} |
| $eq | The field equals the value. On a field inside doc, a string, number or true/false also matches an array that holds it. null matches a field that is null or not there | {"tags": {"$eq": "priority"}} |
| $ne | Every document $eq doesn’t match, those without the field included | {"status": {"$ne": "lost"}} |
| $gt, $gte, $lt, $lte | Numbers with numbers, strings with strings, dates with dates. A value of another type on that field doesn’t match | {"amount": {"$gte": 100, "$lt": 500}} |
| $in | The field equals one of the values. An empty array matches nothing | {"status": {"$in": ["open", "won"]}} |
| $nin | The field equals none of them. An empty array matches everything | {"status": {"$nin": ["lost", "spam"]}} |
| $exists | true: the field is there. false, 0 or null: it isn’t (from 0.4.3; before, 0 read as true) | {"closed_at": {"$exists": false}} |
| $regex | A string that matches the pattern, or an array with a string that does. See below | {"name": {"$regex": "^acme", "$options": "i"}} |
| $and | Every filter in the array matches | {"$and": [{"status": "open"}, {"amount": {"$gt": 0}}]} |
| $or | At least one matches | {"$or": [{"owner": "ada"}, {"owner": {"$exists": false}}]} |
| $nor | None matches | {"$nor": [{"status": "lost"}, {"status": "spam"}]} |
- Several operators on one field all hold:
{"age": {"$gte": 18, "$lt": 65}}. - The three that join filters (
$and,$or,$nor) take a non-empty array of filters, and nest. - A value that is an object or an array is compared whole:
{"address": {"city": "Pune", "zip": "411001"}}matches a document whoseaddressis exactly that. - A dotted path names a field of a nested object. A part of a path may not be empty, start with
$, or hold one of{ } , " \ '. - A field kept as a column is compared with a value of its own type: a string, an integer or an ObjectId.
$eqwith a value of another type matches nothing.$gtand the like with another type are refused (400):status is compared with a string here. - Dates are compared on fields inside
doc. A column never holds a date.
{"status": "open"} // equality{"status": {"$eq": "open"}} // the same{"status": {"$ne": "lost"}} // not lost, or no status at all{"amount": {"$gt": 100}} // a number above 100{"amount": {"$gte": 100, "$lte": 500}} // a range{"name": {"$lt": "m"}} // strings before "m"{"status": {"$in": ["open", "won"]}}{"status": {"$nin": ["lost", "spam"]}}{"closed_at": {"$exists": true}}{"address.city": "Pune"} // a dotted path{"tags": "priority"} // an array that holds "priority"{"deleted": null} // null, or not there{"$and": [{"status": "open"}, {"amount": {"$gt": 0}}]}{"$or": [{"owner": "ada"}, {"owner": {"$exists": false}}]}{"$nor": [{"status": "lost"}, {"status": "spam"}]}{"$or": [{"status": "won"}, {"$and": [{"status": "open"}, {"amount": {"$gte": 1000}}]}]}Dates
A date is relaxed Extended JSON’s {"$date": ...}. A filter compares it with $eq $ne $gt $gte $lt $lte $in $nin as the instant it is, whichever way the document holds it and whatever offset you write.
| Form | Example |
|---|---|
| An ISO-8601 time, with any offset | {"$date": "2026-01-31T10:00:00Z"}, {"$date": "2026-01-31T15:30:00+05:30"} |
Milliseconds since 1970, as $numberLong | {"$date": {"$numberLong": "1767225600000"}} |
| Milliseconds since 1970, as a bare number | {"$date": 1767225600000} |
| Before 1970: negative milliseconds | {"$date": {"$numberLong": "-86400000"}} |
Relaxed Extended JSON keeps a date between 1970 and 9999 as text, and one before 1970 or after 9999 as milliseconds. A document may hold either, or a bare number of milliseconds. All three are read as the same kind of instant, so a range that starts before 1970 works.
// seen in January 2026{"seen": {"$gte": {"$date": "2026-01-01T00:00:00Z"}, "$lt": {"$date": "2026-02-01T00:00:00Z"}}}// born before 1970{"born": {"$lt": {"$date": {"$numberLong": "0"}}}}// exactly this instant, written with another offset than the document has{"seen": {"$date": "2026-01-31T15:30:00+05:30"}}// one of two instants{"seen": {"$in": [{"$date": "2026-01-31T10:00:00Z"}, {"$date": 1767225600000}]}}A $date that is neither an ISO-8601 time nor milliseconds is refused (400). A date written as a plain string ("2026-01-31") is a string: it compares with strings, not with dates.
Regular expressions
{"name": {"$regex": "^acme", "$options": "i"}} matches a string that matches the pattern, and an array with a string that does, as MongoDB has it. $regex takes the pattern as a string. The only option is i (any case); $options without $regex is refused.
{"name": {"$regex": "^acme"}} // starts with "acme"{"name": {"$regex": "^acme", "$options": "i"}} // any case{"email": {"$regex": "@example\\.com$"}} // ends with @example.com{"tags": {"$regex": "^prio"}} // an array with a string that matches{"name": {"$regex": "corp", "$gte": "a"}} // with another operator on the same field$regex isn’t taken on _id. On a field kept as a column that holds integers or ObjectIds it matches nothing.
_id and ObjectIds
_idis compared by$eq,$ne,$inand$ninonly.$gtand the like, and$regex, are refused on it.- An
_idis an ObjectId ({"$oid": "..."}), a string or a number. Anything else is refused. - An
_idgiven in a filter as a bare string of 24 hex digits matches the ObjectId and the string. Agents often pass an ObjectId back that way. - An insert keeps a bare string a string. To insert with an ObjectId of your own, write
{"$oid": "..."}. - An ObjectId in another field is written
{"$oid": "..."}in filters and documents alike.
{"_id": {"$oid": "66f1a2b3c4d5e6f708192a3b"}}{"_id": "66f1a2b3c4d5e6f708192a3b"} // the ObjectId, or that string{"_id": "note-7"}{"_id": {"$in": [{"$oid": "66f1a2b3c4d5e6f708192a3b"}, {"$oid": "66f1a2b3c4d5e6f708192a3c"}]}}{"_id": {"$ne": 7}}Updates
An update is an object of operators. Each takes an object of fields, by name or dotted path.
| Operator | Does | Example |
|---|---|---|
| $set | Sets the field. Objects on the way of a dotted path are made | {"$set": {"status": "won", "address.city": "Mumbai"}} |
| $unset | Removes the field. One that isn’t there is left alone | {"$unset": {"temp_note": ""}} |
| $inc | Adds a number. A field that isn’t there, or is null, counts as 0. A field that holds something else is refused | {"$inc": {"touches": 1, "score": -2.5}} |
| $push | Appends one value to an array. A field that isn’t there becomes an array | {"$push": {"tags": "priority"}} |
| $addToSet | Appends the value unless the array holds it already | {"$addToSet": {"tags": "west"}} |
| $pull | Removes every element equal to the value. It takes a value, not a condition | {"$pull": {"tags": "stale"}} |
{"tool": "update_one", "arguments": {"collection": "leads", "filter": {"_id": {"$oid": "66f1a2b3c4d5e6f708192a3b"}}, "update": { "$set": {"status": "won", "closed_at": {"$date": "2026-02-03T09:00:00Z"}}, "$unset": {"next_step": ""}, "$inc": {"touches": 1}, "$addToSet": {"tags": "customer"}, "$pull": {"tags": "prospect"}}}}Arrays are one value
An array is read and written whole. $push, $addToSet and $pull change it by one value a call. There are no positional paths (items.0.qty, items.$.qty) and no $each: a path that goes through an array is refused (an array is one value here; set the whole array). To change one element, $set the whole array.
{"$set": {"items": [{"sku": "A1", "qty": 3}, {"sku": "B2", "qty": 1}]}}An update that names no operator is refused: to replace fields, $set them. A masked column the update doesn’t name keeps its value: only what the update changed is written. A run that reads a collection’s doc masked can’t update its documents.
Sort, projection and limits
| Rule | |
|---|---|
| Sort | {"field": 1} ascending, {"field": -1} descending. By several fields: an array, in order, [{"status": 1}, {"name": -1}]. An object with several keys is refused, since its keys have no order. Without a sort: by _id. |
| Projection | Top-level fields only, each 1 or 0. {"name": 1, "status": 1} keeps those and _id. {"notes": 0} leaves that out. {"_id": 0} drops _id. Keeping and leaving out in one projection is refused, _id aside. |
limit | 20 unless given. At most GATEWAY_RUN_MAX_ROWS (1,000 by default) documents a call. |
skip | Documents to pass over first, for paging. |
insert | 1,000 documents a call at most. |
update_many, delete_many | 1,000 documents a call at most. A filter that matches more is refused and changes nothing: narrow the filter and call again. |
| A filter is required | update_one, update_many, delete_one and delete_many need filter as an object. {} names every document; delete_many refuses that. |
Extended JSON
Values are relaxed Extended JSON, as doc holds them. Plain strings, numbers, true/false, null, objects and arrays are themselves. Typed values are objects with one $ key:
| Value | Written |
|---|---|
| ObjectId | {"$oid": "66f1a2b3c4d5e6f708192a3b"} |
| Date | {"$date": "2026-01-31T10:00:00Z"}, or milliseconds as above |
| Other typed values | $numberLong, $numberInt, $numberDouble, $numberDecimal, $binary, $timestamp and $uuid are kept as they are, and compared whole by equality. |
Concurrent updates
Two updates of one document at once, in one run, both land. An update is written only if the document is still as the tool read it. If another call changed it meanwhile, the tool reads it again and applies the update to that. After five tries on one document the call answers 409: document ... kept changing under this update; nothing more was written. Try again.
That is inside one run. Two runs never see each other’s changes: each has its own copy. Whether both can merge is decided at the merge, document by document.
What is refused
Anything outside the list above is refused by name (400, code mongo_tool), never guessed. An agent reads the message and takes another way.
| Refused | Instead |
|---|---|
| $elemMatch | Match an array by a value it holds ({"tags": "priority"}), or use SQL on doc |
| $not | $ne, $nin or $nor |
| aggregate | SQL in the run (POST /v1/runs/:id/sql, or the MCP sql tool) |
| upsert: true | Find first, then insert or update |
| Replacing a whole document | $set the fields that change |
| $each, positional paths | One value a call, or $set the whole array |
| Any other operator | The message lists the ones that work |
Errors
| Status | Code | When |
|---|---|---|
| 400 | mongo_tool | An argument a tool doesn’t take: an operator not supported, a missing collection, filter, update or documents, a collection that isn’t attached, a pattern that can’t be read, more than 1,000 documents matched, a run that isn’t beside MongoDB |
| 409 | mongo_tool | A document kept changing under an update, five times |
| 409 | world_lost | The run’s copy was lost with a crashed engine. The run becomes failed. Start a new run |
| 401 | The token isn’t this run’s | |
| 403 | the run’s status, or expired | The run is no longer open (held, merged, rejected, ...), or its time ran out |
| as the engine answers | 42501 | The engine refused it: a row outside the run’s tenant, a write to a collection every tenant shares |
| 429 | Past GATEWAY_RUN_STATEMENTS_PER_MINUTE |
{"error": {"message": "$elemMatch isn't supported in a filter on items ($eq $ne $gt $gte $lt $lte $in $nin $exists $regex)", "code": "mongo_tool"}}What a merge sends to MongoDB
- Only the fields that changed. A document a run updated is sent as those fields, not as the whole document.
- One transaction. Every document of the merge is written together, or none is.
- Each document compared first. A document the run changed is compared with MongoDB as the run read it. If one changed meanwhile, nothing is written and the run is in conflict.
- A record of the merge goes in the engine’s own collections in that database:
chronos_merges, andchronos_merge_rows, which keeps what the merge wrote so it can be undone for 30 days.
GET /v1/runs/:id/changes and the undo preview say a document’s change by field path: “Change the address.city of lead “Acme” from Pune to Mumbai”. Labels name fields by path too:
curl -s -X PUT "$GATEWAY/v1/labels" -H "Authorization: Bearer $KEY" -H 'Content-Type: application/json' \ -d '{"tables": {"leads": {"name": "lead", "title": "name", "columns": {"address.city": "city", "org_id": null}}}}'act_as is Postgres’s only: a run beside MongoDB always writes as the gateway’s role.
SQL on the same data
The run’s SQL endpoint and MCP sql tool work beside MongoDB too, on the same table the tools use: _id, the fields kept as columns, and doc. Use it for what the tools don’t have, such as grouping and joins. Agents write the engine’s SQL (Postgres’s dialect) whatever the database.
curl -s "$GATEWAY/v1/runs/$RUN/sql" -H "Authorization: Bearer $RUN_TOKEN" -H 'Content-Type: application/json' \ -d '{"sql": "select status, count(*) from leads group by status"}'select _id, doc #>> '{address,city}' as cityfrom leadswhere status = 'open'order by _id;A change made by SQL and one made by a tool are the same to the merge: both are rows of the run’s copy.
Following changes
By default the engine takes MongoDB’s latest documents on a timer (GATEWAY_REFRESH_EVERY, 5 minutes). With GATEWAY_FOLLOW=on it also takes changes about a second after they commit, through a change stream on each attached collection. There is nothing to set up in MongoDB and nothing to clean up when you turn it off.
- Needs engine 0.5.1 or later.
- The gateway’s role needs the
changeStreamprivilege on the attached collections. The connection check’srole_sqlgives it. - A role made from older statements needs that added (
db.grantPrivilegesToRole). Until then the engine says what is missing and keeps refreshing on its timer. - With several databases behind one gateway, only the databases that can be followed are: MongoDB and Postgres, not MySQL or MariaDB yet.
Between refreshes an agent may read a document that is out of date. That is safe: the merge compares every document it writes with MongoDB, and the default check_reads = true holds a change if a document it read has changed.