This guide will show you how to build a SQL Agent that can create, modify, and manage databases using GibsonAI MCP Server and LangChain with LangGraph.

What You'll Build

  • A SQL Agent powered by LangChain/LangGraph that can:
    • Create new databases and tables from natural language prompts.
    • Modify existing schemas (add, remove, or update columns and tables).
    • Deploy schema changes to serverless databases (e.g., MySQL).
    • Inspect and query database schemas with conversational commands.
    • Execute SQL queries and get formatted results.

Key Concepts

  • GibsonAI MCP Server: Turns natural language prompts into fully functional database schemas.
  • From Prompt to Database: You can go from describing a database in plain English to having a running schema with deployed APIs in minutes.
  • LangGraph ReAct Agent: Uses reasoning and action cycles to interact with GibsonAI MCP tools effectively.

The GibsonAI MCP integration with LangChain uses the official MCP adapters to seamlessly connect LangChain agents with GibsonAI's database management capabilities.

Prerequisites

Before starting, ensure you have:

  1. A GibsonAI account – Sign up at https://app.gibsonai.com.
  2. Python 3.9+ installed.
  3. OpenAI API key (you can get one from OpenAI).
  1. Install UV Package Manager

    UV is needed to run GibsonAI CLI.

    Run:

    curl -LsSf https://astral.sh/uv/install.sh | sh
  2. Install GibsonAI CLI

    The GibsonAI CLI lets you log in and manage projects:

    uvx --from gibson-cli@latest gibson auth login

    Log in with your GibsonAI account.

  3. Install Python Dependencies

    Install LangChain, LangGraph, MCP adapters, and OpenAI libraries:

    pip install mcp langchain-mcp-adapters langgraph langchain-openai
  4. Set Your OpenAI API Key

    Export your API key:

    export OPENAI_API_KEY="your_openai_api_key"

    (Replace your_openai_api_key with your real key.)

  5. Create a Python File

    Create a new Python file (e.g., agent.py) and copy this code:

    import asyncio
    import os
    from mcp import ClientSession, StdioServerParameters
    from mcp.client.stdio import stdio_client
    from langchain_mcp_adapters.tools import load_mcp_tools
    from langgraph.prebuilt import create_react_agent
    from langchain_openai import ChatOpenAI
    
    class GibsonAIAgent:
        """LangChain + LangGraph agent for GibsonAI database management"""
    
        def __init__(self):
            # Initialize OpenAI model
            self.model = ChatOpenAI(
                model="gpt-4o", 
                temperature=0.1, 
                api_key=os.getenv("OPENAI_API_KEY")
            )
    
            # GibsonAI MCP server parameters
            self.server_params = StdioServerParameters(
                command="uvx", 
                args=["--from", "gibson-cli@latest", "gibson", "mcp", "run"]
            )
    
        async def run_agent(self, message: str) -> None:
            """Run the GibsonAI agent with the given message."""
            try:
                async with stdio_client(self.server_params) as (read, write):
                    async with ClientSession(read, write) as session:
                        # Initialize MCP session
                        await session.initialize()
    
                        # Load all GibsonAI MCP tools
                        tools = await load_mcp_tools(session)
    
                        # Create ReAct agent with tools
                        agent = create_react_agent(
                            self.model,
                            tools,
                            state_modifier="""You are a GibsonAI database assistant. 
                            Help users manage their database projects and schemas.
    
                            Your capabilities include:
                            - Run SQL queries and get results
                            - Creating new GibsonAI projects
                            - Managing database schemas (tables, columns, relationships) 
                            - Deploying schema changes to hosted databases
                            - Querying database schemas and data
                            - Providing insights about database structure and best practices
                            
                            Always be helpful and explain what you're doing step by step.
                            When creating schemas, use appropriate data types and constraints.
                            Consider relationships between tables and suggest indexes where appropriate.
                            Be conversational and provide clear explanations of your actions.""",
                        )
    
                        # Execute the agent
                        result = await agent.ainvoke(
                            {"messages": [{"role": "user", "content": message}]}
                        )
    
                        # Print the response
                        if "messages" in result:
                            for msg in result["messages"]:
                                if hasattr(msg, "content") and msg.content:
                                    print(f"\n🤖 {msg.content}\n")
                                elif hasattr(msg, "tool_calls") and msg.tool_calls:
                                    for tool_call in msg.tool_calls:
                                        print(f"🛠️ Calling tool: {tool_call['name']}")
                                        if tool_call.get("args"):
                                            print(f"   Args: {tool_call['args']}")
    
            except Exception as e:
                print(f"Error running agent: {str(e)}")
    
    async def run_gibsonai_agent(message: str) -> None:
        """Convenience function to run the GibsonAI agent"""
        agent = GibsonAIAgent()
        await agent.run_agent(message)
    
    # Example usage
    if __name__ == "__main__":
        asyncio.run(
            run_gibsonai_agent(
                "Create a database for a blog posts platform with users and posts tables."
            )
        )
  6. Run the Agent

    Run the script:

    python agent.py

    The agent will:

    • Start the local GibsonAI MCP Server.
    • Use LangGraph's ReAct agent to reason about your request.
    • Take your prompt (e.g., "Create a database for a blog with users and posts tables").
    • Automatically create a database schema using GibsonAI tools.
    • Show you step-by-step what actions it's taking.
  7. View Your Database

    Go to your GibsonAI Dashboard:

    https://app.gibsonai.com

    Here, you can:

    • See your database schema.
    • Check generated REST APIs for your data.
    • Monitor database performance and usage.

Example Prompts to Try

You can experiment with these prompts:

  • "Show me the current schema for my project."
  • "Add a 'products' table with name, price, and description fields."
  • "Create a 'users' table with authentication fields."
  • "Deploy my schema changes to production."
  • "Run a query to show all users from the database."
  • "Create a new database for an e-commerce platform."
  • "Add a foreign key relationship between users and posts tables."

Advanced Features

Custom Agent Instructions

You can customize the agent's behavior by modifying the state_modifier parameter:

agent = create_react_agent(
    self.model,
    tools,
    state_modifier="""You are a specialized e-commerce database expert.
    Focus on creating optimized schemas for online stores with proper
    indexing and relationships for high-performance queries.""",
)

Error Handling and Logging

Add robust error handling for production use:

import logging

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

try:
    result = await agent.ainvoke({"messages": [{"role": "user", "content": message}]})
    logger.info("Agent execution completed successfully")
except Exception as e:
    logger.error(f"Agent execution failed: {str(e)}")
    # Handle specific error cases

Multiple Project Management

Create agents that can work with multiple GibsonAI projects:

async def run_multi_project_agent(message: str, project_id: str = None) -> None:
    """Run agent with specific project context"""
    if project_id:
        message = f"Working with project {project_id}: {message}"
    
    agent = GibsonAIAgent()
    await agent.run_agent(message)

Why LangChain + GibsonAI?

  • Tool Integration: LangChain's MCP adapters seamlessly connect to GibsonAI's database tools.
  • Reasoning: LangGraph's ReAct pattern provides intelligent planning and execution.
  • Flexibility: Easy to extend with additional LangChain tools and chains.
  • Observability: Built-in logging and debugging capabilities.
  • Production Ready: Robust error handling and async support.

Key Advantages Over Traditional Approaches

  • No Complex Prompting: Skip writing lengthy system prompts to teach your agent SQL operations. GibsonAI's MCP tools handle database interactions automatically, so your agent knows exactly how to create tables, run queries, and manage schemas without custom instruction engineering.

  • No Custom Tool Development: Forget building your own database connection tools or SQL execution wrappers. GibsonAI provides pre-built MCP tools that work out-of-the-box with any LangChain agent.

  • Unified Database Support: No need to manage separate MCP servers for different databases. GibsonAI handles MySQL today and PostgreSQL support is coming in the next two weeks - all through the same simple interface.

  • Avoid LangChain SQL Toolkit Issues: LangChain's built-in SQL database toolkit has known limitations with complex queries, connection management, and error handling. GibsonAI's MCP tools provide a more reliable alternative with better error messages and query optimization.

  • Sandboxed Database Environment: Your agent can safely run SQL queries in isolated database environments without affecting production data. Each project gets its own secure sandbox, perfect for development and testing.

Next Steps