How to Configure Pydantic AI MongoDB Connect

Published
Length
3 min read

Luis Felipe Dias

All posts

To set up a pydantic ai mongodb connect workflow, pass a database client into your agent dependencies. Then bind a restricted database user role to that client before the agent runs. Teams often start by reusing a shared app key during early testing. If that key has broad write rights, a bad prompt can alter or drop production records. How a pydantic ai mongodb connect setup works Pydantic AI uses a dependency injection system to pass tools and clients to an agent. You create a database clien

Your coding agents run with your access.

Claude Code reaches prod with a developer's credentials, and approval prompts get clicked through. hoop.dev checks every query, masks sensitive data, and holds risky changes for a human.

To set up a pydantic ai mongodb connect workflow, pass a database client into your agent dependencies. Then bind a restricted database user role to that client before the agent runs. Teams often start by reusing a shared app key during early testing. If that key has broad write rights, a bad prompt can alter or drop production records.

How a pydantic ai mongodb connect setup works

Pydantic AI uses a dependency injection system to pass tools and clients to an agent. You create a database client outside the agent and pass it into the run context. Your custom tool functions then use that client to run queries on behalf of the model. This keeps network state separate from the prompt logic.

On the database side, MongoDB manages permissions through role-based rules. A role grants the right to run specific actions on a defined resource. Each role applies to the database where you define it. You can scope a role down to a single collection for tighter control. MongoDB Atlas and self-hosted clusters use different built-in role lists, but they share the same base actions.

For most agent tools, you should start with the built-in read role. The read role lets the user read all non-system collections in that database. It allows actions like find, listCollections, listIndexes, dbStats, collStats, and changeStream. It does not allow insert, update, remove, or dropCollection actions. This stops an agent from changing records if a prompt goes wrong.

What native roles solve and where gaps remain

Native database roles decide who can log in and which collections they can touch. If an agent needs to write outputs, teams often switch to the readWrite role. That role includes all read actions plus insert, update, remove, and dropCollection. It also allows createCollection, createIndex, and dropIndex on that database. Giving an agent readWrite access means a flawed tool call could drop an entire collection.

Even a strict read role leaves operational gaps open at the document level. A collection role lets the agent read every field inside the allowed collection. If documents hold emails, phone numbers, card numbers, or national IDs, a find query returns them all. Native roles check permission at login and collection level, not inside each returned document.

MongoDB Authentication & Authorization + AI Agent Security: architecture patterns and best practices

Continue reading? Get the full guide.

Free. No spam. Unsubscribe anytime.

Static database credentials also create key management work for your engineering team. You must store the connection string on every host that runs the agent worker. When someone leaves the team or a key leaks, you must rotate strings across every app. Native roles also do not link a database query back to the human user who triggered the agent.

Best practices for agent tool definitions

Never let the language model write raw database queries on its own. Instead, build narrow tool functions that take typed inputs validated by Pydantic schemas. Each tool should run one pre-written query pattern with strict filter shapes and row limits. This stops the model from running broad scans across millions of documents.

Keep read tools and write tools under separate database users when possible. Use a read-only user for search and lookup tasks across your main collections. If the agent must save state, point that tool at a separate scratch collection. Scope the write role to that single collection so main records stay safe.

Inspect MongoDB wire traffic in flight

Built-in MongoDB roles govern collection access at setup time. They cannot score command risk per call or mask sensitive document values on the fly. By design, hoop.dev is an open-source proxy that sits next to MongoDB as a sidecar for your MongoDB. It reads every command from mongosh, drivers, or agent tools.

First, hoop.dev guardrails block bad deletes, drops, and write pipelines. Next, hoop.dev data masking rewrites sensitive values in returned documents based on your rules and logs each decision. Explore the repo on GitHub.

Frequently asked questions

What MongoDB role should an AI agent use for search tools?

Assign the built-in read role scoped to the specific database or collection needed. It allows find and list actions while blocking insert, update, remove, and dropCollection.

Can MongoDB roles hide specific fields like emails or card numbers?

No, standard MongoDB roles grant access down to the collection level, not the field level. Once an agent can run find on a collection, it receives every field in matching documents unless another system rewrites results.

Why avoid the readWrite role for general AI agent tasks?

The readWrite role includes destructive actions like remove, dropIndex, and dropCollection. If a prompt injection tricks the agent tool, it could delete data instead of just adding a record.

The query runs. The emails stay hidden.