Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
156 changes: 156 additions & 0 deletions demo-applications/spring-boot-postgres/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
# Spring Boot MCP Toolbox PostgreSQL Example 🚀

This sample application demonstrates how to build a modern **Spring Boot 3** microservice integrated with the **MCP Toolbox Java SDK** (`com.google.cloud.mcp:mcp-toolbox-sdk-java`).

The application connects to an official [MCP Toolbox](https://github.com/googleapis/mcp-toolbox) server running in Docker, configured with a custom declarative **`tools.yaml`** that defines domain-specific database tools (`get-all-products`, `get-product-by-id`, `get-products-by-category`, `add-product`, `delete-product-by-id`, `list_tables`, `get-table-schema`) backed by a live **PostgreSQL** instance.

---

## Architecture Overview

```
┌─────────────────────────────────┐
│ Spring Boot 3 Application │
│ (Port 8080) │
│ - ProductController (REST API) │
│ - ProductCatalogService │
│ - McpToolboxClient (Java SDK) │
└────────────────┬────────────────┘
│ HTTP (JSON-RPC 2.0 /mcp)
┌─────────────────────────────────┐
│ MCP Toolbox Server (Docker) │
│ (Port 5005:5000) │
│ --config /tools.yaml │
│ (Custom declarative tools) │
└────────────────┬────────────────┘
│ TCP (5432)
┌─────────────────────────────────┐
│ PostgreSQL 15 (Docker) │
│ (Port 5433:5432, DB: mcpdb) │
│ - Table: products │
└─────────────────────────────────┘
```

---

## Custom Declarative `tools.yaml`

Rather than exposing arbitrary raw SQL execution, the application defines domain-specific tools declaratively in [`tools.yaml`](./tools.yaml):

| Tool Name | Parameters | Description |
| :--- | :--- | :--- |
| `get-all-products` | None | Retrieves all products ordered by ID. |
| `get-product-by-id` | `id` (integer) | Retrieves a single product by its ID. |
| `get-products-by-category` | `category` (string) | Retrieves products filtered by category. |
| `add-product` | `name` (string), `category` (string, optional), `price` (float), `stock` (integer) | Inserts a product using parameterized queries (`$1, $2, $3, $4`) and returns the created record via `RETURNING`. |
| `delete-product-by-id` | `id` (integer) | Deletes a product by ID. |
| `list_tables` | None | Lists public tables from `information_schema.tables`. |
| `get-table-schema` | `table_name` (string) | Introspects column types and nullability for a table. |

### Why Declarative Tools?
1. **Parameterized Security**: Toolbox binds arguments via PostgreSQL prepared statement parameters (`$1`, `$2`), eliminating SQL injection risks.
2. **Schema & Validation**: Input types, required parameters, and descriptions are enforced at the MCP layer before hitting the database.
3. **Domain Abstraction**: LLMs and microservices interact with clean business tools rather than raw SQL commands.

## Maven Dependency

Add the MCP Toolbox Java SDK dependency to your `pom.xml`:

```xml
<dependency>
<groupId>com.google.cloud.mcp</groupId>
<artifactId>mcp-toolbox-sdk-java</artifactId>
<version>1.0.0</version> <!-- {x-version-update:mcp-toolbox-sdk-java:current} -->
</dependency>
```

---

## Prerequisites

- **Java 17+** (JDK 17, 21, or 26)
- **Maven 3.9+**
- **Docker** container engine

---

## Quickstart

### 1. Start the Docker Containers

Run the automated startup script to launch PostgreSQL and MCP Toolbox:

```bash
./scripts/start-containers.sh
```

This script:
1. Spawns a PostgreSQL container (`mcp-postgres`) on port `5433`.
2. Seeds a sample `products` table with initial records.
3. Spawns the MCP Toolbox server (`mcp-toolbox`) linked to PostgreSQL on port `5005`.
4. Waits until the server responds to tool discovery.

### 2. Run the Test Suites

Execute standalone unit tests (offline, hermetic, no Docker containers required):

```bash
mvn clean test -Dnet.bytebuddy.experimental=true
```

Execute end-to-end integration tests (requires Docker containers running from Step 1):

```bash
mvn clean verify -Dnet.bytebuddy.experimental=true
```

### 3. Run the Spring Boot Application

```bash
mvn spring-boot:run
```

The application will start on `http://localhost:8080`.

---

## REST Endpoints

### 1. List Available MCP Tools
```bash
curl -s http://localhost:8080/api/tools | jq .
```

### 2. Get All Products
```bash
curl -s http://localhost:8080/api/products | jq .
```

### 3. Create a New Product
```bash
curl -s -X POST http://localhost:8080/api/products \
-H "Content-Type: application/json" \
-d '{
"name": "Ultra HD Monitor 34-inch",
"category": "Electronics",
"price": 649.99,
"stock": 30
}'
```

### 4. Inspect Table Schema
```bash
curl -s http://localhost:8080/api/schema/products | jq .
```

---

## Teardown

To shut down and remove the test containers:

```bash
./scripts/stop-containers.sh
```
109 changes: 109 additions & 0 deletions demo-applications/spring-boot-postgres/pom.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
<?xml version="1.0" encoding="UTF-8"?>
<!--
Copyright 2026 Google LLC

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

https://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.1.3</version>
<relativePath/>
</parent>

<groupId>com.google.cloud.mcp.example</groupId>
<artifactId>spring-boot-postgres-example</artifactId>
<version>1.0.0</version>
<name>Spring Boot MCP Toolbox PostgreSQL Example</name>
<description>Demonstration of using the Java MCP Toolbox SDK within a Spring Boot 3 application connected to a containerized PostgreSQL instance.</description>

<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<!-- Spring Boot Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<!-- MCP Toolbox Java SDK -->
<dependency>
<groupId>com.google.cloud.mcp</groupId>
<artifactId>mcp-toolbox-sdk-java</artifactId>
<version>1.0.0</version><!-- {x-version-update:mcp-toolbox-sdk-java:current} -->
</dependency>

<!-- Jackson JSON -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
</dependency>

<!-- Spring Boot Test Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Dnet.bytebuddy.experimental=true</argLine>
Comment thread
stenalpjolly marked this conversation as resolved.
<includes>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/*IT.java</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-failsafe-plugin</artifactId>
<configuration>
<argLine>-Dnet.bytebuddy.experimental=true</argLine>
<includes>
<include>**/*IT.java</include>
</includes>
</configuration>
<executions>
<execution>
<goals>
<goal>integration-test</goal>
<goal>verify</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
#!/usr/bin/env bash
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

set -euo pipefail

NETWORK_NAME="${NETWORK_NAME:-mcp-network}"

echo "==> Cleaning up previous test containers and network if running..."
docker rm -f mcp-toolbox mcp-postgres 2>/dev/null || true
docker network rm "${NETWORK_NAME}" 2>/dev/null || true
docker network create "${NETWORK_NAME}"

POSTGRES_USER="${POSTGRES_USER:-mcpuser}"
POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-mcppass}"
POSTGRES_DATABASE="${POSTGRES_DATABASE:-mcpdb}"

echo "==> Starting PostgreSQL container (port 5433:5432)..."
docker run -d --name mcp-postgres --network "${NETWORK_NAME}" --network-alias postgres -p 5433:5432 \
-e POSTGRES_USER="${POSTGRES_USER}" \
-e POSTGRES_PASSWORD="${POSTGRES_PASSWORD}" \
-e POSTGRES_DB="${POSTGRES_DATABASE}" \
postgres:15-alpine

echo "==> Waiting for PostgreSQL to be ready..."
until docker exec mcp-postgres pg_isready -U "${POSTGRES_USER}" -d "${POSTGRES_DATABASE}"; do
sleep 1
done

echo "==> Initializing schema and seed data in PostgreSQL from schema.sql..."
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
docker exec -i mcp-postgres psql -U "${POSTGRES_USER}" -d "${POSTGRES_DATABASE}" < "${SCRIPT_DIR}/../src/main/resources/schema.sql"

echo "==> Starting MCP Toolbox container with custom tools.yaml (port 5005:5000)..."
docker run -d --name mcp-toolbox --network "${NETWORK_NAME}" -p 5005:5000 \
-e POSTGRES_HOST=postgres \
-e POSTGRES_PORT=5432 \
-e POSTGRES_DATABASE="${POSTGRES_DATABASE}" \
-e POSTGRES_USER="${POSTGRES_USER}" \
-e POSTGRES_PASSWORD="${POSTGRES_PASSWORD}" \
-v "${SCRIPT_DIR}/../tools.yaml:/tools.yaml:ro" \
us-central1-docker.pkg.dev/database-toolbox/toolbox/toolbox:latest \
--config /tools.yaml --address 0.0.0.0 --port 5000

echo "==> Waiting for MCP Toolbox to be ready on http://localhost:5005/mcp..."
until curl -s -X POST http://localhost:5005/mcp -H "Content-Type: application/json" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list","params":{}}' | grep -q "get-all-products"; do
sleep 1
done

echo "==> MCP Toolbox Server is healthy and accepting requests on http://localhost:5005/mcp."
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env bash
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

NETWORK_NAME="${NETWORK_NAME:-mcp-network}"
docker rm -f mcp-toolbox mcp-postgres 2>/dev/null || true
docker network rm "${NETWORK_NAME}" 2>/dev/null || true
echo "==> Test containers and network stopped and removed."
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
/*
* Copyright 2026 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package com.google.cloud.mcp.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/** Entry point for the Spring Boot MCP Toolbox PostgreSQL Example Application. */
@SpringBootApplication
public class SpringBootPostgresApplication {

public static void main(String[] args) {
SpringApplication.run(SpringBootPostgresApplication.class, args);
}
}
Loading
Loading