|
| 1 | + |
| 2 | +--- |
| 3 | +meta: |
| 4 | + title: Connect Generative APIs to Serverless SQL with the Model Context Protocol |
| 5 | + description: Create an intelligent agent that can analyze your Serverless SQL data using natural language queries through Model Context Protocol. |
| 6 | +content: |
| 7 | + h1: Connect Generative APIs to Serverless SQL with the Model Context Protocol |
| 8 | + paragraph: Create an intelligent agent that can analyze your Serverless SQL data using natural language queries through Model Context Protocol. |
| 9 | +tags: AI MCP SQL agent python database |
| 10 | +categories: |
| 11 | + - generative-apis |
| 12 | + - serverless-sql |
| 13 | +dates: |
| 14 | + validation: 2025-05-13 |
| 15 | + posted: 2025-05-13 |
| 16 | +--- |
| 17 | + |
| 18 | +[Model Context Protocol](https://modelcontextprotocol.io/introduction) (MCP) is an open, standardized communication protocol that enables Large Language Models to interact with external tools and services through a defined interface. |
| 19 | + |
| 20 | +This tutorial demonstrates how to build a data analysis agent that connects Scaleway's Generative APIs with Serverless SQL using MCP. You'll learn how to create an AI agent that can: |
| 21 | +- Understand your database schema automatically |
| 22 | +- Convert natural language questions into SQL queries |
| 23 | +- Execute queries and present results in a human-friendly format |
| 24 | + |
| 25 | +<Macro id="requirements" /> |
| 26 | + |
| 27 | +- A Scaleway account logged into the [console](https://console.scaleway.com) |
| 28 | +- [Owner](/iam/concepts/#owner) status or [IAM permissions](/iam/concepts/#permission) allowing actions in the intended Organization |
| 29 | +- Python 3.9 or higher |
| 30 | +- An API key from Scaleway [Identity and Access Management](/iam/) |
| 31 | +- Access to Scaleway [Generative APIs](/generative-apis/quickstart/) and [Serverless SQL](/serverless-sql/quickstart/) |
| 32 | + |
| 33 | +## Introduction |
| 34 | + |
| 35 | +The solution consists of three main components: |
| 36 | + |
| 37 | +1. **Generative APIs**: Provides the AI model that processes natural language queries |
| 38 | +2. **Serverless SQL**: Stores and manages the data |
| 39 | +3. **Local AI agent**: Coordinates between the AI model and database |
| 40 | + |
| 41 | +<Message type="note"> |
| 42 | + The agent runs on a local machine in this tutorial but could also be embedded as a remote application. |
| 43 | +</Message> |
| 44 | + |
| 45 | +## Configuring Scaleway services |
| 46 | + |
| 47 | +### Set up Generative APIs |
| 48 | + |
| 49 | +1. Go to the Scaleway console and navigate to **Generative APIs** |
| 50 | +2. Select a model (Mistral Small is used for this tutorial) |
| 51 | +3. Click **View Code* and note down the *base URL* and *model name* |
| 52 | + |
| 53 | +### Configure Serverless SQL |
| 54 | + |
| 55 | +1. Go to **Databases** > **Serverless SQL** |
| 56 | +2. [Create a new database](/serverless-sql-databases/how-to/create-a-database/) with default settings |
| 57 | +3. Click **Connect application** > **Connect with an existing IAM Secret Key** |
| 58 | +4. Switch to the **Connection string** tab and copy the connection string |
| 59 | + |
| 60 | +### Seed the database |
| 61 | + |
| 62 | +[Connect to your database](/serverless-sql-databases/how-to/connect-to-a-database/) and run the following SQL to create a test schema with some data: |
| 63 | + |
| 64 | +```sql |
| 65 | +CREATE TABLE Sales ( |
| 66 | + Product VARCHAR(50), |
| 67 | + Buyer VARCHAR(50), |
| 68 | + Timestamp TIMESTAMP |
| 69 | +); |
| 70 | + |
| 71 | +INSERT INTO Sales (Product, Buyer, Timestamp) VALUES |
| 72 | + ('Laptop', 'Alice', NOW() - INTERVAL '2 days'), |
| 73 | + ('Tablet', 'Bob', NOW() - INTERVAL '3 days'), |
| 74 | + ('Webcam', 'Ivan', NOW() - INTERVAL '30 minutes'), |
| 75 | + ('Printer', 'Judy', NOW() - INTERVAL '12 hours'); |
| 76 | +``` |
| 77 | + |
| 78 | +## Setting up the development environment |
| 79 | + |
| 80 | +The AI Agent is built in Python using the [fast-agent](https://github.com/evalstate/fast-agent) open-source framework which has native support for the MCP protocol. |
| 81 | + |
| 82 | +The [postgres-mcp](https://github.com/crystaldba/postgres-mcp) MCP server is used to communicate with Serverless SQL. |
| 83 | + |
| 84 | +1. Install a package manager. `uv` is the recommended package manager by `fast-agent`: |
| 85 | + ```bash |
| 86 | + curl -LsSf https://astral.sh/uv/install.sh | sh |
| 87 | + ``` |
| 88 | + |
| 89 | +2. Create and activate a virtual environment: |
| 90 | + ```bash |
| 91 | + uv venv |
| 92 | + ``` |
| 93 | + |
| 94 | +3. Install required libraries: |
| 95 | + ```bash |
| 96 | + uv pip install fast-agent-mcp postgres-mcp |
| 97 | + ``` |
| 98 | + |
| 99 | +These libraries work together to create a secure and efficient bridge between the AI model and your database. |
| 100 | + |
| 101 | +## Creating the AI Agent |
| 102 | + |
| 103 | +### Configure the agent |
| 104 | + |
| 105 | +Create a file called `fastagent.config.yaml`: |
| 106 | + |
| 107 | +```yaml |
| 108 | +default_model: "generic.<Your model name>" |
| 109 | + |
| 110 | +generic: |
| 111 | + api_key: "<Your Scaleway API Key>" |
| 112 | + base_url: "<Your Generative API Base URL>" |
| 113 | + |
| 114 | +mcp: |
| 115 | + servers: |
| 116 | + database: |
| 117 | + command: "uv" |
| 118 | + args: ["run", "postgres-mcp"] |
| 119 | + env: |
| 120 | + DATABASE_URI: "<Your Serverless SQL Connection String>" |
| 121 | +``` |
| 122 | +
|
| 123 | +### Create the agent script |
| 124 | +
|
| 125 | +Create a file called `agent.py` which will contain your agent logic. |
| 126 | + |
| 127 | +1. Import the necessary modules and initialize the agent: |
| 128 | + ```python |
| 129 | + import asyncio |
| 130 | + from mcp_agent.core.fastagent import FastAgent |
| 131 | +
|
| 132 | + fast = FastAgent("AI Agent") |
| 133 | + ``` |
| 134 | + |
| 135 | +2. Create agents with different responsibilities: |
| 136 | + ```python |
| 137 | + @fast.agent( |
| 138 | + "db_schema_reader", |
| 139 | + instruction="""Get the details of the 'sales' table in the 'public' schema of the database, which contains the sales data. Only return the column names and types.""", |
| 140 | + servers=["database"], |
| 141 | + ) |
| 142 | + @fast.agent( |
| 143 | + "query_writer", |
| 144 | + instruction="""Write a SQL query to fetch the sales data from the database (sales table) given the input constraint. Only return the SQL query, no other text.""" |
| 145 | + ) |
| 146 | + @fast.agent( |
| 147 | + "query_executor", |
| 148 | + instruction="""Execute the following SQL statement on the database and write the results in JSON format""", |
| 149 | + servers=["database"], |
| 150 | + ) |
| 151 | + ``` |
| 152 | + |
| 153 | + <Message type="note"> |
| 154 | + Each agent has a specific role. Some agents need direct database access through the MCP server (using the `servers=["database"]` parameter) while others don't |
| 155 | + </Message> |
| 156 | + |
| 157 | +3. Create an orchestrator that coordinates the specialized agents: |
| 158 | + ```python |
| 159 | + @fast.orchestrator( |
| 160 | + name="sales_analyst", |
| 161 | + agents=["db_schema_reader","query_writer","query_executor"], |
| 162 | + plan_type="iterative", |
| 163 | + plan_iterations=4, |
| 164 | + instruction="You are a sales analyst given an input criteria. Describe the corresponding sales data from the database in one sentence." |
| 165 | + ) |
| 166 | + ``` |
| 167 | + The orchestrator: |
| 168 | + - Determines which agents to use and in what order |
| 169 | + - Sets an overall goal for the agent system |
| 170 | + - Uses an iterative planning approach to refine the results |
| 171 | + - Limits the number of iterations to prevent infinite loops |
| 172 | + |
| 173 | +4. Create an entrypoint running the data analysis query **Get sales from last day**: |
| 174 | + ```python |
| 175 | + async def main() -> None: |
| 176 | + async with fast.run() as agent: |
| 177 | + await agent.sales_analyst("Get sales from last day") |
| 178 | +
|
| 179 | + if __name__ == "__main__": |
| 180 | + asyncio.run(main()) |
| 181 | + ``` |
| 182 | + |
| 183 | +5. Run the script with: |
| 184 | + ```bash |
| 185 | + python agent.py |
| 186 | + ``` |
| 187 | + |
| 188 | +The `fast-agent` framework provides details of all operations and outputs its data analysis: |
| 189 | + |
| 190 | + The sales data from the last day includes two transactions: a webcam purchased by Ivan at 14:52 and a printer purchased by Judy at 03:22. |
| 191 | + |
| 192 | + |
| 193 | +This tutorial demonstrated how to create an AI agent that can analyze your SQL database using natural language queries. By combining Scaleway **Generative APIs** with **Serverless SQL** through Model Context Protocol, you can create powerful tools that are accessible to non-technical users. |
0 commit comments