Skip to content

Commit 2e8ae24

Browse files
feat(tutorial): connect generative apis to sql with mcp
1 parent 5567c70 commit 2e8ae24

File tree

1 file changed

+192
-0
lines changed
  • tutorials/connect-generative-apis-sql

1 file changed

+192
-0
lines changed
Lines changed: 192 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,192 @@
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 human-friendly format
24+
25+
<Macro id="requirements" />
26+
27+
- A Scaleway account logged into the [console](https://console.scaleway.com)
28+
- Python 3.9 or higher
29+
- An API key from Scaleway [Identity and Access Management](/iam/)
30+
- Access to Scaleway [Generative APIs](/generative-apis/quickstart/) and [Serverless SQL](/serverless-sql/quickstart/)
31+
32+
## Introduction
33+
34+
The solution consists of three main components:
35+
36+
1. **Generative APIs**: Provides the AI model that processes natural language queries
37+
2. **Serverless SQL**: Stores and manages the data
38+
3. **Local AI agent**: Coordinates between the AI model and database
39+
40+
<Message type="note">
41+
The agent runs on a local machine in this tutorial but could also be embedded as a remote application.
42+
</Message>
43+
44+
## Configuring Scaleway services
45+
46+
### Set up Generative APIs
47+
48+
1. Go to the Scaleway console and navigate to **Generative APIs**
49+
2. Select a model (Mistral Small is used for this tutorial)
50+
3. Click **View Code* and note down the *base URL* and *model name*
51+
52+
### Configure Serverless SQL
53+
54+
1. Go to **Databases** > **Serverless SQL**
55+
2. Create a new database with default settings
56+
3. Click **Connect application** > **Connect with an existing IAM Secret Key**
57+
4. Switch to the **Connection string** tab and copy the connection string
58+
59+
### Seed the database
60+
61+
Connect to your database and run the following SQL to create a test schema with some data:
62+
63+
```sql
64+
CREATE TABLE Sales (
65+
Product VARCHAR(50),
66+
Buyer VARCHAR(50),
67+
Timestamp TIMESTAMP
68+
);
69+
70+
INSERT INTO Sales (Product, Buyer, Timestamp) VALUES
71+
('Laptop', 'Alice', NOW() - INTERVAL '2 days'),
72+
('Tablet', 'Bob', NOW() - INTERVAL '3 days'),
73+
('Webcam', 'Ivan', NOW() - INTERVAL '30 minutes'),
74+
('Printer', 'Judy', NOW() - INTERVAL '12 hours');
75+
```
76+
77+
## Setting up the development environment
78+
79+
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.
80+
81+
The [postgres-mcp](https://github.com/crystaldba/postgres-mcp) MCP server is used to communicate with Serverless SQL.
82+
83+
1. Install a package manager. `uv` is the recommended package manager by `fast-agent`:
84+
```bash
85+
curl -LsSf https://astral.sh/uv/install.sh | sh
86+
```
87+
88+
2. Create and activate a virtual environment:
89+
```bash
90+
uv venv
91+
```
92+
93+
3. Install required libraries:
94+
```bash
95+
uv pip install fast-agent-mcp postgres-mcp
96+
```
97+
98+
These libraries work together to create a secure and efficient bridge between the AI model and your database.
99+
100+
## Creating the AI Agent
101+
102+
### Configure the agent
103+
104+
Create a file called `fastagent.config.yaml`:
105+
106+
```yaml
107+
default_model: "generic.<Your model name>"
108+
109+
generic:
110+
api_key: "<Your Scaleway API Key>"
111+
base_url: "<Your Generative API Base URL>"
112+
113+
mcp:
114+
servers:
115+
database:
116+
command: "uv"
117+
args: ["run", "postgres-mcp"]
118+
env:
119+
DATABASE_URI: "<Your Serverless SQL Connection String>"
120+
```
121+
122+
### Create the agent script
123+
124+
Create a file called `agent.py` which will contain your agent logic.
125+
126+
1. Import the necessary modules and initialize the agent:
127+
```python
128+
import asyncio
129+
from mcp_agent.core.fastagent import FastAgent
130+
131+
fast = FastAgent("AI Agent")
132+
```
133+
134+
2. Create agents with different responsibilities:
135+
```python
136+
@fast.agent(
137+
"db_schema_reader",
138+
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.""",
139+
servers=["database"],
140+
)
141+
@fast.agent(
142+
"query_writer",
143+
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."""
144+
)
145+
@fast.agent(
146+
"query_executor",
147+
instruction="""Execute the following SQL statement on the database and write the results in JSON format""",
148+
servers=["database"],
149+
)
150+
```
151+
152+
<Message type="note">
153+
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
154+
</Message>
155+
156+
3. Create an orchestrator that coordinates the specialized agents:
157+
```python
158+
@fast.orchestrator(
159+
name="sales_analyst",
160+
agents=["db_schema_reader","query_writer","query_executor"],
161+
plan_type="iterative",
162+
plan_iterations=4,
163+
instruction="You are a sales analyst given an input criteria. Describe the corresponding sales data from the database in one sentence."
164+
)
165+
```
166+
The orchestrator:
167+
- Determines which agents to use and in what order
168+
- Sets an overall goal for the agent system
169+
- Uses an iterative planning approach to refine the results
170+
- Limits the number of iterations to prevent infinite loops
171+
172+
4. Create an entrypoint running the data analysis query **Get sales from last day**:
173+
```python
174+
async def main() -> None:
175+
async with fast.run() as agent:
176+
await agent.sales_analyst("Get sales from last day")
177+
178+
if __name__ == "__main__":
179+
asyncio.run(main())
180+
```
181+
182+
5. Run the script with:
183+
```bash
184+
python agent.py
185+
```
186+
187+
The `fast-agent` framework provides details of all operations and outputs its data analysis:
188+
189+
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.
190+
191+
192+
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

Comments
 (0)