How to Use Spring AI MCP with Chat2DB for Natural Language Database Queries
This tutorial explains how to integrate Spring AI's Model Context Protocol (MCP) with Chat2DB to enable secure, natural‑language queries against a PostgreSQL database, covering configuration, core Java code, execution flow, and sample SQL queries.
Introduction
In the previous article we introduced the basics of Spring AI MCP (Model Context Protocol) and demonstrated file operations. This article dives deeper, showing how to use MCP for natural‑language interaction with databases.
What is Chat2DB?
Chat2DB is an innovative database interaction tool that lets users query and manipulate databases using natural language. By leveraging large language models (LLMs), it translates everyday questions into appropriate SQL statements.
MCP (Model Context Protocol) Overview
MCP is a protocol designed to give LLMs read‑only access to databases. Its main features include:
Read‑only database access interface
Allows LLMs to inspect database schema
Supports execution of read‑only queries
Ensures data security
In a PostgreSQL scenario, the MCP server acts as a bridge between the database and the LLM, enabling safe understanding and querying of the database structure.
Spring AI Integration
Dependency Configuration
<code><dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-openai-spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.experimental</groupId>
<artifactId>spring-ai-mcp</artifactId>
<version>0.4.1</version>
</dependency></code>Model Configuration
<code>spring.ai.openai.chat.options.model=deepseek-chat
spring.ai.openai.base-url=https://api.deepseek.com
spring.ai.openai.api-key=sk-XXX</code>Core Implementation
The following Java code implements the MCP client and chat functionality:
<code>@Bean
public CommandLineRunner predefinedQuestions(ChatClient.Builder chatClientBuilder,
List<McpFunctionCallback> functionCallbacks, ConfigurableApplicationContext context) {
return args -> {
var chatClient = chatClientBuilder
.defaultFunctions(functionCallbacks.toArray(new McpFunctionCallback[0]))
.build();
String question1 = "你能链接我的postgres数据库,然后告诉我这个数据库有多少张表吗?";
System.out.println("ASSISTANT: " + chatClient.prompt(question1).call().content());
String question2 = "你能链接我的postgres数据库,然后告诉我这个商品表里面哪个车最贵吗?";
System.out.println("ASSISTANT: " + chatClient.prompt(question2).call().content());
context.close();
};
}
@Bean
public List<McpFunctionCallback> functionCallbacks(McpSyncClient mcpClient) {
return mcpClient.listTools(null)
.tools()
.stream()
.map(tool -> new McpFunctionCallback(mcpClient, tool))
.toList();
}
@Bean(destroyMethod = "close")
public McpSyncClient mcpClient() {
var stdioParams = ServerParameters.builder("npx")
.args("-y", "@modelcontextprotocol/server-postgres",
"postgresql://postgres:lengleng@localhost:5432")
.build();
var mcpClient = McpClient.using(new StdioClientTransport(stdioParams))
.requestTimeout(Duration.ofSeconds(10)).sync();
var init = mcpClient.initialize();
System.out.println("MCP Initialized: " + init);
return mcpClient;
}</code>Database Schema Example
Execution Flow Diagram
Detailed Execution Steps
Initialization Phase
Spring application starts
MCP client initialized with protocol version 2024-11-05
Server info: example-servers/postgres v0.1.0
Tool Registration Phase
Register query tool for read‑only SQL queries
Set query timeout to 10 seconds
Database Interaction Phase
Perform connection check
Retrieve database table structure
Execute user query and return results
Response Handling Phase
Convert query results to structured JSON
LLM processes result and generates natural‑language answer
Return formatted response to user
Sample Queries
<code>-- Query table count
SELECT COUNT(*) as count FROM information_schema.tables WHERE table_schema = 'public';
-- Query table schema
SELECT column_name, data_type FROM information_schema.columns WHERE table_name = 'products';
-- Query product data
SELECT id, name, price FROM products ORDER BY price DESC;</code>Conclusion
Chat2DB combined with Spring AI MCP provides a revolutionary solution for database interaction. By using natural‑language processing and a secure protocol design, it offers ease of use while guaranteeing data safety, making it ideal for scenarios that require frequent queries with a low technical barrier.
Java Architecture Diary
Committed to sharing original, high‑quality technical articles; no fluff or promotional content.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.