EnrichMCP can automatically transform existing SQLAlchemy models into an AI-navigable API.
To use this feature:
- Add
EnrichSQLAlchemyMixin to your DeclarativeBase. - Use the
info parameter in mapped_column or relationship to provide descriptions that help the AI understand the schema. - Initialize the
EnrichMCP app using sqlalchemy_lifespan to manage the database connection and lifecycle. - Register your models with the app using
include_sqlalchemy_models(app, Base).
This enables tools like explore_data_model(), automatic filtering (e.g., list_users(status='active')), and relationship navigation (e.g., user.orders).
from enrichmcp import EnrichMCP
from enrichmcp.sqlalchemy import (
include_sqlalchemy_models,
sqlalchemy_lifespan,
EnrichSQLAlchemyMixin,
)
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
class Base(DeclarativeBase, EnrichSQLAlchemyMixin):
pass
class User(Base):
"""User account."""
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True, info={"description": "Unique user ID"})
orders: Mapped[list["Order"]] = relationship(
back_populates="user", info={"description": "All orders for this user"}
)
class Order(Base):
"""Customer order."""
__tablename__ = "orders"
user_id: Mapped[int] = mapped_column(info={"description": "Owner user ID"})
user: Mapped[User] = relationship(back_populates="orders")
app = EnrichMCP(
"E-commerce Data",
"API generated from SQLAlchemy models",
lifespan=sqlalchemy_lifespan(Base, engine, cleanup_db_file=True),
)
include_sqlalchemy_models(app, Base)
if __name__ == "__main__":
app.run()