diff --git a/helpers/exclusion_list.txt b/helpers/exclusion_list.txt index b683b763991..27bc5504e30 100644 --- a/helpers/exclusion_list.txt +++ b/helpers/exclusion_list.txt @@ -91,3 +91,4 @@ ./examples/mcptoolbox-bq-claude-slack-agent ./tools/mosaic-rag-ai ./examples/creative-studio +./tools/oas-mcp-tools-weaver diff --git a/tools/oas-mcp-tools-weaver/README.md b/tools/oas-mcp-tools-weaver/README.md new file mode 100644 index 00000000000..cd4e0a0eb32 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/README.md @@ -0,0 +1,92 @@ +
+ OAS MCP Tools Weaver Logo +
+ +

+ OAS MCP Tools Weaver πŸ•ΈοΈ +

+ +

+ Java + OpenAPI + MCP + License +

+ +

+ Welcome to OAS MCP Tools Weaver, a powerful Spring Boot application that serves as a dynamic tool provider for AI models. It parses an OpenAPI 3.0 specification at startup and exposes each API operation as a "tool" that can be invoked by a Large Language Model (LLM). This bridges the gap between your existing RESTful APIs and modern LLMs, enabling them to interact with your services through the standardized Model-Context-Protocol (MCP). +

+ +--- + +## πŸ›οΈ Architecture & Workflow +LLMs can be augmented with "tools" that allow them to interact with external systems. The Model-Context-Protocol (MCP) provides a standard for defining these tools. The **OAS MCP Tools Weaver** is a Spring Boot server that dynamically exposes your OpenAPI-defined APIs as MCP-compliant tools for LLMs. +This server dynamically exposes your OpenAPI-defined APIs as tools for LLMs. + +The workflow is simple: + +1. **Configuration**: You place your OpenAPI 3.0 specification file (`spec.json` or `spec.yaml`) inside the application's resources and configure a `ToolCallbackProvider` bean for it. +2. **Startup**: On startup, the Spring Boot application parses the OpenAPI specification, extracting API endpoints, parameters, and request/response schemas. +3. **Tool Exposure**: The server dynamically creates and exposes an MCP-compliant "tool" for each API operation. It intelligently handles complex schemas (e.g., `oneOf`, `allOf`) to make them understandable to LLMs. +4. **Interaction**: An LLM can now discover and invoke these tools. The server translates the LLM's tool call into a live HTTP request to your backend API, including authentication, and returns the result. + +
+ Workflow Diagram +
+ +## ✨ Key Features + +* βœ… **Dynamic Tool Serving**: No need to manually generate static tool files. Tools are created at runtime directly from your OAS. +* βœ… **OpenAPI 3.0 Support**: Works with the industry-standard API specification format. +* βœ… **Intelligent Schema Handling**: Simplifies complex JSON schemas (`oneOf`, `allOf`) from the OAS, making them easier for LLMs to consume. +* βœ… **Enterprise Ready**: Built with Java and Spring Boot, a robust and widely-adopted stack for enterprise-grade applications. +* βœ… **MCP Compliant**: Adheres to the Model-Context-Protocol for standardized tool interaction with LLMs. + +## πŸš€ Getting Started + +Follow these steps to install and run the tool. + +### Prerequisites + +* Java 17 or higher +* Apache Maven +* An OpenAPI 3.0 specification file for your API. + +### Installation + +1. **Clone the repository:** + ```bash + git clone https://github.com/your-repo/oas-mcp-tools-weaver.git + cd oas-mcp-tools-weaver/mcpserver + ``` + +2. **Place your OpenAPI Specification:** + Copy your OpenAPI specification file (e.g., `my-api.yaml`) into the `src/main/resources/openapi/` directory. + +3. **Configure the Tool Provider:** + You must create a `ToolCallbackProvider` bean for your OpenAPI specification. Open the relevant Spring configuration file and add a bean definition similar to the following: + + ```bash + @Bean + ToolCallbackProvider myApiTools(OASSchemaHandler schemaProcessor, RestTemplate restTemplate) { + return new DynamicOpenApiToolCallbackProvider("/openapi/my-api.yaml", schemaProcessor, restTemplate, apiUrlEnv); + } + ``` + +### Usage + +The server is run as a standard Spring Boot application using Maven. + +1. **Set Environment Variables:** + Before running, ensure you have set the required environment variables. + ```bash + export API_ENV_URL="https://your.api.backend.com" + ``` + +2. **Run the Application:** + Navigate to the `mcpserver` directory and execute the following Maven command: + ```bash + mvn spring-boot:run + ``` + + The server will start (by default on port `8081`) and will be ready to serve tools to your LLM. \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/architecture.png b/tools/oas-mcp-tools-weaver/architecture.png new file mode 100644 index 00000000000..6a6bc344cff Binary files /dev/null and b/tools/oas-mcp-tools-weaver/architecture.png differ diff --git a/tools/oas-mcp-tools-weaver/mcpserver/Dockerfile b/tools/oas-mcp-tools-weaver/mcpserver/Dockerfile new file mode 100644 index 00000000000..99e35aecbcf --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/Dockerfile @@ -0,0 +1,45 @@ +# Copyright 2025 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. +# Use a multi-stage build to keep the final image size small + +# Stage 1: Build the application +FROM maven:3.8.6-eclipse-temurin-17 AS builder + +# Set the working directory inside the container +WORKDIR /app + +# Copy the pom.xml and install dependencies +COPY pom.xml . +RUN mvn dependency:go-offline + +# Copy the source code +COPY src ./src + +# Package the application +RUN mvn package -DskipTests + +# Stage 2: Create the final image +FROM eclipse-temurin:17-jdk-jammy + +# Set the working directory inside the container +WORKDIR /app + +# Copy the jar file from the builder stage +COPY --from=builder /app/target/*.jar app.jar + +# Expose port 8080 +EXPOSE 8081 + +# Run the application +ENTRYPOINT ["java", "-jar", "app.jar"] \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/README.md b/tools/oas-mcp-tools-weaver/mcpserver/README.md new file mode 100644 index 00000000000..5aa726c9860 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/README.md @@ -0,0 +1,41 @@ +# MCP Server + +## Introduction + +This MCP Server is a Spring Boot application that serves as a dynamic tool provider for AI models, enabling them to interact with backend APIs. It works by parsing an OpenAPI specification at startup and creating a corresponding "tool" for each API operation defined. + +These tools can then be invoked by a Large Language Model (LLM) to perform actions, effectively allowing the LLM to use the API to fulfill tasks. The server handles the translation from the LLM's tool call into a live HTTP request to the target API, including authentication. A key feature is its ability to process and simplify complex JSON schemas (e.g., `oneOf`, `allOf`) from the OpenAPI specification, making them easier for the LLM to understand and use correctly. + +## Architecture Diagram + +![architecture_diagram.png](architecture_diagram.png?raw=true "MCP Server Architecture Diagram") + +## How to Run + +1. **Prerequisites**: + * Java 17 or later + * Apache Maven + +2. **Configuration**: + + * Before starting the application, keep your OpenAPI Specs under [src/main/resources/openapi/](src/main/resources/openapi/) directory. + * Ensure you're creating a ToolCallbackProvider Bean for your OAS. For example: + + ```java + @Bean + ToolCallbackProvider flightSearch(OASSchemaHandler schemaProcessor, RestTemplate restTemplate) { + return new DynamicOpenApiToolCallbackProvider("/openapi/your-oas-spec.yaml", schemaProcessor, restTemplate, apiUrlEnv); + } + ``` + + * Make sure you have set the below environment variable: + + * `API_ENV_URL`: Your API Environment URL value. + +3. **Run the application**: + + Navigate to the project's root directory and execute the following Maven command: + ```bash + mvn spring-boot:run + ``` + The server will start on the port `8081`. \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/architecture_diagram.png b/tools/oas-mcp-tools-weaver/mcpserver/architecture_diagram.png new file mode 100644 index 00000000000..5f80c403d9d Binary files /dev/null and b/tools/oas-mcp-tools-weaver/mcpserver/architecture_diagram.png differ diff --git a/tools/oas-mcp-tools-weaver/mcpserver/mvnw b/tools/oas-mcp-tools-weaver/mcpserver/mvnw new file mode 100644 index 00000000000..e9cf8d3307b --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/mvnw @@ -0,0 +1,295 @@ +#!/bin/sh +# ---------------------------------------------------------------------------- +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you 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. +# ---------------------------------------------------------------------------- + +# ---------------------------------------------------------------------------- +# Apache Maven Wrapper startup batch script, version 3.3.3 +# +# Optional ENV vars +# ----------------- +# JAVA_HOME - location of a JDK home dir, required when download maven via java source +# MVNW_REPOURL - repo url base for downloading maven distribution +# MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +# MVNW_VERBOSE - true: enable verbose log; debug: trace the mvnw script; others: silence the output +# ---------------------------------------------------------------------------- + +set -euf +[ "${MVNW_VERBOSE-}" != debug ] || set -x + +# OS specific support. +native_path() { printf %s\\n "$1"; } +case "$(uname)" in +CYGWIN* | MINGW*) + [ -z "${JAVA_HOME-}" ] || JAVA_HOME="$(cygpath --unix "$JAVA_HOME")" + native_path() { cygpath --path --windows "$1"; } + ;; +esac + +# set JAVACMD and JAVACCMD +set_java_home() { + # For Cygwin and MinGW, ensure paths are in Unix format before anything is touched + if [ -n "${JAVA_HOME-}" ]; then + if [ -x "$JAVA_HOME/jre/sh/java" ]; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACCMD="$JAVA_HOME/jre/sh/javac" + else + JAVACMD="$JAVA_HOME/bin/java" + JAVACCMD="$JAVA_HOME/bin/javac" + + if [ ! -x "$JAVACMD" ] || [ ! -x "$JAVACCMD" ]; then + echo "The JAVA_HOME environment variable is not defined correctly, so mvnw cannot run." >&2 + echo "JAVA_HOME is set to \"$JAVA_HOME\", but \"\$JAVA_HOME/bin/java\" or \"\$JAVA_HOME/bin/javac\" does not exist." >&2 + return 1 + fi + fi + else + JAVACMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v java + )" || : + JAVACCMD="$( + 'set' +e + 'unset' -f command 2>/dev/null + 'command' -v javac + )" || : + + if [ ! -x "${JAVACMD-}" ] || [ ! -x "${JAVACCMD-}" ]; then + echo "The java/javac command does not exist in PATH nor is JAVA_HOME set, so mvnw cannot run." >&2 + return 1 + fi + fi +} + +# hash string like Java String::hashCode +hash_string() { + str="${1:-}" h=0 + while [ -n "$str" ]; do + char="${str%"${str#?}"}" + h=$(((h * 31 + $(LC_CTYPE=C printf %d "'$char")) % 4294967296)) + str="${str#?}" + done + printf %x\\n $h +} + +verbose() { :; } +[ "${MVNW_VERBOSE-}" != true ] || verbose() { printf %s\\n "${1-}"; } + +die() { + printf %s\\n "$1" >&2 + exit 1 +} + +trim() { + # MWRAPPER-139: + # Trims trailing and leading whitespace, carriage returns, tabs, and linefeeds. + # Needed for removing poorly interpreted newline sequences when running in more + # exotic environments such as mingw bash on Windows. + printf "%s" "${1}" | tr -d '[:space:]' +} + +scriptDir="$(dirname "$0")" +scriptName="$(basename "$0")" + +# parse distributionUrl and optional distributionSha256Sum, requires .mvn/wrapper/maven-wrapper.properties +while IFS="=" read -r key value; do + case "${key-}" in + distributionUrl) distributionUrl=$(trim "${value-}") ;; + distributionSha256Sum) distributionSha256Sum=$(trim "${value-}") ;; + esac +done <"$scriptDir/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" + +case "${distributionUrl##*/}" in +maven-mvnd-*bin.*) + MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ + case "${PROCESSOR_ARCHITECTURE-}${PROCESSOR_ARCHITEW6432-}:$(uname -a)" in + *AMD64:CYGWIN* | *AMD64:MINGW*) distributionPlatform=windows-amd64 ;; + :Darwin*x86_64) distributionPlatform=darwin-amd64 ;; + :Darwin*arm64) distributionPlatform=darwin-aarch64 ;; + :Linux*x86_64*) distributionPlatform=linux-amd64 ;; + *) + echo "Cannot detect native platform for mvnd on $(uname)-$(uname -m), use pure java version" >&2 + distributionPlatform=linux-amd64 + ;; + esac + distributionUrl="${distributionUrl%-bin.*}-$distributionPlatform.zip" + ;; +maven-mvnd-*) MVN_CMD=mvnd.sh _MVNW_REPO_PATTERN=/maven/mvnd/ ;; +*) MVN_CMD="mvn${scriptName#mvnw}" _MVNW_REPO_PATTERN=/org/apache/maven/ ;; +esac + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +[ -z "${MVNW_REPOURL-}" ] || distributionUrl="$MVNW_REPOURL$_MVNW_REPO_PATTERN${distributionUrl#*"$_MVNW_REPO_PATTERN"}" +distributionUrlName="${distributionUrl##*/}" +distributionUrlNameMain="${distributionUrlName%.*}" +distributionUrlNameMain="${distributionUrlNameMain%-bin}" +MAVEN_USER_HOME="${MAVEN_USER_HOME:-${HOME}/.m2}" +MAVEN_HOME="${MAVEN_USER_HOME}/wrapper/dists/${distributionUrlNameMain-}/$(hash_string "$distributionUrl")" + +exec_maven() { + unset MVNW_VERBOSE MVNW_USERNAME MVNW_PASSWORD MVNW_REPOURL || : + exec "$MAVEN_HOME/bin/$MVN_CMD" "$@" || die "cannot exec $MAVEN_HOME/bin/$MVN_CMD" +} + +if [ -d "$MAVEN_HOME" ]; then + verbose "found existing MAVEN_HOME at $MAVEN_HOME" + exec_maven "$@" +fi + +case "${distributionUrl-}" in +*?-bin.zip | *?maven-mvnd-?*-?*.zip) ;; +*) die "distributionUrl is not valid, must match *-bin.zip or maven-mvnd-*.zip, but found '${distributionUrl-}'" ;; +esac + +# prepare tmp dir +if TMP_DOWNLOAD_DIR="$(mktemp -d)" && [ -d "$TMP_DOWNLOAD_DIR" ]; then + clean() { rm -rf -- "$TMP_DOWNLOAD_DIR"; } + trap clean HUP INT TERM EXIT +else + die "cannot create temp dir" +fi + +mkdir -p -- "${MAVEN_HOME%/*}" + +# Download and Install Apache Maven +verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +verbose "Downloading from: $distributionUrl" +verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +# select .zip or .tar.gz +if ! command -v unzip >/dev/null; then + distributionUrl="${distributionUrl%.zip}.tar.gz" + distributionUrlName="${distributionUrl##*/}" +fi + +# verbose opt +__MVNW_QUIET_WGET=--quiet __MVNW_QUIET_CURL=--silent __MVNW_QUIET_UNZIP=-q __MVNW_QUIET_TAR='' +[ "${MVNW_VERBOSE-}" != true ] || __MVNW_QUIET_WGET='' __MVNW_QUIET_CURL='' __MVNW_QUIET_UNZIP='' __MVNW_QUIET_TAR=v + +# normalize http auth +case "${MVNW_PASSWORD:+has-password}" in +'') MVNW_USERNAME='' MVNW_PASSWORD='' ;; +has-password) [ -n "${MVNW_USERNAME-}" ] || MVNW_USERNAME='' MVNW_PASSWORD='' ;; +esac + +if [ -z "${MVNW_USERNAME-}" ] && command -v wget >/dev/null; then + verbose "Found wget ... using wget" + wget ${__MVNW_QUIET_WGET:+"$__MVNW_QUIET_WGET"} "$distributionUrl" -O "$TMP_DOWNLOAD_DIR/$distributionUrlName" || die "wget: Failed to fetch $distributionUrl" +elif [ -z "${MVNW_USERNAME-}" ] && command -v curl >/dev/null; then + verbose "Found curl ... using curl" + curl ${__MVNW_QUIET_CURL:+"$__MVNW_QUIET_CURL"} -f -L -o "$TMP_DOWNLOAD_DIR/$distributionUrlName" "$distributionUrl" || die "curl: Failed to fetch $distributionUrl" +elif set_java_home; then + verbose "Falling back to use Java to download" + javaSource="$TMP_DOWNLOAD_DIR/Downloader.java" + targetZip="$TMP_DOWNLOAD_DIR/$distributionUrlName" + cat >"$javaSource" <<-END + public class Downloader extends java.net.Authenticator + { + protected java.net.PasswordAuthentication getPasswordAuthentication() + { + return new java.net.PasswordAuthentication( System.getenv( "MVNW_USERNAME" ), System.getenv( "MVNW_PASSWORD" ).toCharArray() ); + } + public static void main( String[] args ) throws Exception + { + setDefault( new Downloader() ); + java.nio.file.Files.copy( java.net.URI.create( args[0] ).toURL().openStream(), java.nio.file.Paths.get( args[1] ).toAbsolutePath().normalize() ); + } + } + END + # For Cygwin/MinGW, switch paths to Windows format before running javac and java + verbose " - Compiling Downloader.java ..." + "$(native_path "$JAVACCMD")" "$(native_path "$javaSource")" || die "Failed to compile Downloader.java" + verbose " - Running Downloader.java ..." + "$(native_path "$JAVACMD")" -cp "$(native_path "$TMP_DOWNLOAD_DIR")" Downloader "$distributionUrl" "$(native_path "$targetZip")" +fi + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +if [ -n "${distributionSha256Sum-}" ]; then + distributionSha256Result=false + if [ "$MVN_CMD" = mvnd.sh ]; then + echo "Checksum validation is not supported for maven-mvnd." >&2 + echo "Please disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + elif command -v sha256sum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | sha256sum -c - >/dev/null 2>&1; then + distributionSha256Result=true + fi + elif command -v shasum >/dev/null; then + if echo "$distributionSha256Sum $TMP_DOWNLOAD_DIR/$distributionUrlName" | shasum -a 256 -c >/dev/null 2>&1; then + distributionSha256Result=true + fi + else + echo "Checksum validation was requested but neither 'sha256sum' or 'shasum' are available." >&2 + echo "Please install either command, or disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." >&2 + exit 1 + fi + if [ $distributionSha256Result = false ]; then + echo "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised." >&2 + echo "If you updated your Maven version, you need to update the specified distributionSha256Sum property." >&2 + exit 1 + fi +fi + +# unzip and move +if command -v unzip >/dev/null; then + unzip ${__MVNW_QUIET_UNZIP:+"$__MVNW_QUIET_UNZIP"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -d "$TMP_DOWNLOAD_DIR" || die "failed to unzip" +else + tar xzf${__MVNW_QUIET_TAR:+"$__MVNW_QUIET_TAR"} "$TMP_DOWNLOAD_DIR/$distributionUrlName" -C "$TMP_DOWNLOAD_DIR" || die "failed to untar" +fi + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +actualDistributionDir="" + +# First try the expected directory name (for regular distributions) +if [ -d "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" ]; then + if [ -f "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/bin/$MVN_CMD" ]; then + actualDistributionDir="$distributionUrlNameMain" + fi +fi + +# If not found, search for any directory with the Maven executable (for snapshots) +if [ -z "$actualDistributionDir" ]; then + # enable globbing to iterate over items + set +f + for dir in "$TMP_DOWNLOAD_DIR"/*; do + if [ -d "$dir" ]; then + if [ -f "$dir/bin/$MVN_CMD" ]; then + actualDistributionDir="$(basename "$dir")" + break + fi + fi + done + set -f +fi + +if [ -z "$actualDistributionDir" ]; then + verbose "Contents of $TMP_DOWNLOAD_DIR:" + verbose "$(ls -la "$TMP_DOWNLOAD_DIR")" + die "Could not find Maven distribution directory in extracted archive" +fi + +verbose "Found extracted Maven distribution directory: $actualDistributionDir" +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$actualDistributionDir/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$actualDistributionDir" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/tools/oas-mcp-tools-weaver/mcpserver/mvnw.cmd b/tools/oas-mcp-tools-weaver/mcpserver/mvnw.cmd new file mode 100755 index 00000000000..b80a7af7726 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/mvnw.cmd @@ -0,0 +1,202 @@ +# Copyright 2025 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. +<# : batch portion +@REM ---------------------------------------------------------------------------- +@REM Licensed to the Apache Software Foundation (ASF) under one +@REM or more contributor license agreements. See the NOTICE file +@REM distributed with this work for additional information +@REM regarding copyright ownership. The ASF licenses this file +@REM to you under the Apache License, Version 2.0 (the +@REM "License"); you may not use this file except in compliance +@REM with the License. You may obtain a copy of the License at +@REM +@REM http://www.apache.org/licenses/LICENSE-2.0 +@REM +@REM Unless required by applicable law or agreed to in writing, +@REM software distributed under the License is distributed on an +@REM "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +@REM KIND, either express or implied. See the License for the +@REM specific language governing permissions and limitations +@REM under the License. +@REM ---------------------------------------------------------------------------- + +@REM ---------------------------------------------------------------------------- +@REM Apache Maven Wrapper startup batch script, version 3.3.3 +@REM +@REM Optional ENV vars +@REM MVNW_REPOURL - repo url base for downloading maven distribution +@REM MVNW_USERNAME/MVNW_PASSWORD - user and password for downloading maven +@REM MVNW_VERBOSE - true: enable verbose log; others: silence the output +@REM ---------------------------------------------------------------------------- + +@IF "%__MVNW_ARG0_NAME__%"=="" (SET __MVNW_ARG0_NAME__=%~nx0) +@SET __MVNW_CMD__= +@SET __MVNW_ERROR__= +@SET __MVNW_PSMODULEP_SAVE=%PSModulePath% +@SET PSModulePath= +@FOR /F "usebackq tokens=1* delims==" %%A IN (`powershell -noprofile "& {$scriptDir='%~dp0'; $script='%__MVNW_ARG0_NAME__%'; icm -ScriptBlock ([Scriptblock]::Create((Get-Content -Raw '%~f0'))) -NoNewScope}"`) DO @( + IF "%%A"=="MVN_CMD" (set __MVNW_CMD__=%%B) ELSE IF "%%B"=="" (echo %%A) ELSE (echo %%A=%%B) +) +@SET PSModulePath=%__MVNW_PSMODULEP_SAVE% +@SET __MVNW_PSMODULEP_SAVE= +@SET __MVNW_ARG0_NAME__= +@SET MVNW_USERNAME= +@SET MVNW_PASSWORD= +@IF NOT "%__MVNW_CMD__%"=="" ("%__MVNW_CMD__%" %*) +@echo Cannot start maven from wrapper >&2 && exit /b 1 +@GOTO :EOF +: end batch / begin powershell #> + +$ErrorActionPreference = "Stop" +if ($env:MVNW_VERBOSE -eq "true") { + $VerbosePreference = "Continue" +} + +# calculate distributionUrl, requires .mvn/wrapper/maven-wrapper.properties +$distributionUrl = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionUrl +if (!$distributionUrl) { + Write-Error "cannot read distributionUrl property in $scriptDir/.mvn/wrapper/maven-wrapper.properties" +} + +switch -wildcard -casesensitive ( $($distributionUrl -replace '^.*/','') ) { + "maven-mvnd-*" { + $USE_MVND = $true + $distributionUrl = $distributionUrl -replace '-bin\.[^.]*$',"-windows-amd64.zip" + $MVN_CMD = "mvnd.cmd" + break + } + default { + $USE_MVND = $false + $MVN_CMD = $script -replace '^mvnw','mvn' + break + } +} + +# apply MVNW_REPOURL and calculate MAVEN_HOME +# maven home pattern: ~/.m2/wrapper/dists/{apache-maven-,maven-mvnd--}/ +if ($env:MVNW_REPOURL) { + $MVNW_REPO_PATTERN = if ($USE_MVND -eq $False) { "/org/apache/maven/" } else { "/maven/mvnd/" } + $distributionUrl = "$env:MVNW_REPOURL$MVNW_REPO_PATTERN$($distributionUrl -replace "^.*$MVNW_REPO_PATTERN",'')" +} +$distributionUrlName = $distributionUrl -replace '^.*/','' +$distributionUrlNameMain = $distributionUrlName -replace '\.[^.]*$','' -replace '-bin$','' + +$MAVEN_M2_PATH = "$HOME/.m2" +if ($env:MAVEN_USER_HOME) { + $MAVEN_M2_PATH = "$env:MAVEN_USER_HOME" +} + +if (-not (Test-Path -Path $MAVEN_M2_PATH)) { + New-Item -Path $MAVEN_M2_PATH -ItemType Directory | Out-Null +} + +$MAVEN_WRAPPER_DISTS = $null +if ((Get-Item $MAVEN_M2_PATH).Target[0] -eq $null) { + $MAVEN_WRAPPER_DISTS = "$MAVEN_M2_PATH/wrapper/dists" +} else { + $MAVEN_WRAPPER_DISTS = (Get-Item $MAVEN_M2_PATH).Target[0] + "/wrapper/dists" +} + +$MAVEN_HOME_PARENT = "$MAVEN_WRAPPER_DISTS/$distributionUrlNameMain" +$MAVEN_HOME_NAME = ([System.Security.Cryptography.SHA256]::Create().ComputeHash([byte[]][char[]]$distributionUrl) | ForEach-Object {$_.ToString("x2")}) -join '' +$MAVEN_HOME = "$MAVEN_HOME_PARENT/$MAVEN_HOME_NAME" + +if (Test-Path -Path "$MAVEN_HOME" -PathType Container) { + Write-Verbose "found existing MAVEN_HOME at $MAVEN_HOME" + Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" + exit $? +} + +if (! $distributionUrlNameMain -or ($distributionUrlName -eq $distributionUrlNameMain)) { + Write-Error "distributionUrl is not valid, must end with *-bin.zip, but found $distributionUrl" +} + +# prepare tmp dir +$TMP_DOWNLOAD_DIR_HOLDER = New-TemporaryFile +$TMP_DOWNLOAD_DIR = New-Item -Itemtype Directory -Path "$TMP_DOWNLOAD_DIR_HOLDER.dir" +$TMP_DOWNLOAD_DIR_HOLDER.Delete() | Out-Null +trap { + if ($TMP_DOWNLOAD_DIR.Exists) { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } + } +} + +New-Item -Itemtype Directory -Path "$MAVEN_HOME_PARENT" -Force | Out-Null + +# Download and Install Apache Maven +Write-Verbose "Couldn't find MAVEN_HOME, downloading and installing it ..." +Write-Verbose "Downloading from: $distributionUrl" +Write-Verbose "Downloading to: $TMP_DOWNLOAD_DIR/$distributionUrlName" + +$webclient = New-Object System.Net.WebClient +if ($env:MVNW_USERNAME -and $env:MVNW_PASSWORD) { + $webclient.Credentials = New-Object System.Net.NetworkCredential($env:MVNW_USERNAME, $env:MVNW_PASSWORD) +} +[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 +$webclient.DownloadFile($distributionUrl, "$TMP_DOWNLOAD_DIR/$distributionUrlName") | Out-Null + +# If specified, validate the SHA-256 sum of the Maven distribution zip file +$distributionSha256Sum = (Get-Content -Raw "$scriptDir/.mvn/wrapper/maven-wrapper.properties" | ConvertFrom-StringData).distributionSha256Sum +if ($distributionSha256Sum) { + if ($USE_MVND) { + Write-Error "Checksum validation is not supported for maven-mvnd. `nPlease disable validation by removing 'distributionSha256Sum' from your maven-wrapper.properties." + } + Import-Module $PSHOME\Modules\Microsoft.PowerShell.Utility -Function Get-FileHash + if ((Get-FileHash "$TMP_DOWNLOAD_DIR/$distributionUrlName" -Algorithm SHA256).Hash.ToLower() -ne $distributionSha256Sum) { + Write-Error "Error: Failed to validate Maven distribution SHA-256, your Maven distribution might be compromised. If you updated your Maven version, you need to update the specified distributionSha256Sum property." + } +} + +# unzip and move +Expand-Archive "$TMP_DOWNLOAD_DIR/$distributionUrlName" -DestinationPath "$TMP_DOWNLOAD_DIR" | Out-Null + +# Find the actual extracted directory name (handles snapshots where filename != directory name) +$actualDistributionDir = "" + +# First try the expected directory name (for regular distributions) +$expectedPath = Join-Path "$TMP_DOWNLOAD_DIR" "$distributionUrlNameMain" +$expectedMvnPath = Join-Path "$expectedPath" "bin/$MVN_CMD" +if ((Test-Path -Path $expectedPath -PathType Container) -and (Test-Path -Path $expectedMvnPath -PathType Leaf)) { + $actualDistributionDir = $distributionUrlNameMain +} + +# If not found, search for any directory with the Maven executable (for snapshots) +if (!$actualDistributionDir) { + Get-ChildItem -Path "$TMP_DOWNLOAD_DIR" -Directory | ForEach-Object { + $testPath = Join-Path $_.FullName "bin/$MVN_CMD" + if (Test-Path -Path $testPath -PathType Leaf) { + $actualDistributionDir = $_.Name + } + } +} + +if (!$actualDistributionDir) { + Write-Error "Could not find Maven distribution directory in extracted archive" +} + +Write-Verbose "Found extracted Maven distribution directory: $actualDistributionDir" +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$actualDistributionDir" -NewName $MAVEN_HOME_NAME | Out-Null +try { + Move-Item -Path "$TMP_DOWNLOAD_DIR/$MAVEN_HOME_NAME" -Destination $MAVEN_HOME_PARENT | Out-Null +} catch { + if (! (Test-Path -Path "$MAVEN_HOME" -PathType Container)) { + Write-Error "fail to move MAVEN_HOME" + } +} finally { + try { Remove-Item $TMP_DOWNLOAD_DIR -Recurse -Force | Out-Null } + catch { Write-Warning "Cannot remove $TMP_DOWNLOAD_DIR" } +} + +Write-Output "MVN_CMD=$MAVEN_HOME/bin/$MVN_CMD" diff --git a/tools/oas-mcp-tools-weaver/mcpserver/pom.xml b/tools/oas-mcp-tools-weaver/mcpserver/pom.xml new file mode 100644 index 00000000000..d67e9ae8d26 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/pom.xml @@ -0,0 +1,110 @@ + + + 4.0.0 + + org.springframework.boot + spring-boot-starter-parent + 3.5.5 + + + poc.google + mcpserver + 0.0.1-SNAPSHOT + mcpserver + Demo project for Spring AI MCP Server + + + + + + + + + + + + + + + 17 + 1.0.0 + + + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + + + + org.springframework.boot + spring-boot-starter-actuator + + + org.springframework.boot + spring-boot-starter + + + org.springframework.ai + spring-ai-starter-mcp-server-webmvc + + + org.projectlombok + lombok + true + + + io.swagger.parser.v3 + swagger-parser + 2.1.30 + + + org.json + json + 20250517 + + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + + + + org.projectlombok + lombok + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + org.projectlombok + lombok + + + + + + + + diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/McpserverApplication.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/McpserverApplication.java new file mode 100644 index 00000000000..86098f2d7d3 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/McpserverApplication.java @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class McpserverApplication { + public static void main(String[] args) { + SpringApplication.run(McpserverApplication.class, args); + + } +} diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/OASSchemaProcessorConfiguration.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/OASSchemaProcessorConfiguration.java new file mode 100644 index 00000000000..4ad2aa6d810 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/OASSchemaProcessorConfiguration.java @@ -0,0 +1,79 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.configuration; + +import java.util.List; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import poc.google.mcpserver.processor.OASSchemaHandler; +import poc.google.mcpserver.processor.keywords.AllOfHandler; +import poc.google.mcpserver.processor.keywords.AnyOfHandler; +import poc.google.mcpserver.processor.keywords.IKeywordHandler; +import poc.google.mcpserver.processor.keywords.OneOfHandler; + +/** + * Configuration class for setting up the OpenAPI Schema processor and its keyword handlers. + * This is used to simplify complex schema structures (like oneOf, allOf) into a format + * that is more easily understood by AI models. + */ +@Configuration +public class OASSchemaProcessorConfiguration { + + /** + * Provides a handler for the {@code oneOf} keyword in an OpenAPI schema. + * + * @return An {@link IKeywordHandler} for the {@code oneOf} keyword. + */ + @Bean + public IKeywordHandler oneOfHandler() { + return new OneOfHandler(); + } + + /** + * Provides a handler for the {@code anyOf} keyword in an OpenAPI schema. + * + * @return An {@link IKeywordHandler} for the {@code anyOf} keyword. + */ + @Bean + public IKeywordHandler anyOfHandler() { + return new AnyOfHandler(); + } + + /** + * Provides a handler for the {@code allOf} keyword in an OpenAPI schema. + * + * @return An {@link IKeywordHandler} for the {@code allOf} keyword. + */ + @Bean + public IKeywordHandler allOfHandler() { + return new AllOfHandler(); + } + + /** + * Creates the main {@link OASSchemaHandler} bean. + * This handler iterates through a list of keyword-specific handlers to process + * and simplify an OpenAPI schema. + * + * @param keywordHandlers A list of all configured {@link IKeywordHandler} beans. + * @return The main {@link OASSchemaHandler} for processing schemas. + */ + @Bean + public OASSchemaHandler schemaProcessor(List keywordHandlers) { + return new OASSchemaHandler(keywordHandlers); + } +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/PromptsConfiguration.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/PromptsConfiguration.java new file mode 100644 index 00000000000..93f80c70a06 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/PromptsConfiguration.java @@ -0,0 +1,38 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.configuration; + +import org.springframework.context.annotation.Configuration; + +/** + * Configuration class for creating MCP (Model Context Protocol) prompt specifications + * dynamically from OpenAPI specification files. + */ +@Configuration +public class PromptsConfiguration { + + /** + * Creates a list of {@link McpServerFeatures.SyncPromptSpecification} beans for the Pet Store API. + * These prompts are generated from the examples in the petStore.yaml OpenAPI specification. + * + * @return A list of synchronous prompt specifications for the pet store. + */ + // @Bean + // public List petStorePrompts() { + // return new DynamicPromptTemplateExamplesGenerator().generatPromptTemplatesFromOAS("/openapi/petStore.yaml"); + // } + +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/RestAPIConfiguration.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/RestAPIConfiguration.java new file mode 100644 index 00000000000..fe77882728e --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/RestAPIConfiguration.java @@ -0,0 +1,45 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.configuration; + +import org.springframework.boot.web.client.RestTemplateBuilder; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.web.client.RestTemplate; + +/** + * Configuration for REST API communication. + * This class sets up the RestTemplate bean used for making outbound HTTP requests. + */ +@Configuration +public class RestAPIConfiguration { + + /** + * Creates and configures a {@link RestTemplate} bean. + * The RestTemplate is configured with default headers to accept and send JSON. + * @param builder The {@link RestTemplateBuilder} to construct the RestTemplate. + * @return A configured {@link RestTemplate} instance. + */ + @Bean + public RestTemplate restTemplate(RestTemplateBuilder builder) { + return builder + .defaultHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON_VALUE) + .defaultHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE) + .build(); + } +} diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/ToolsConfiguration.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/ToolsConfiguration.java new file mode 100644 index 00000000000..8a0d0fbceda --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/configuration/ToolsConfiguration.java @@ -0,0 +1,54 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.configuration; + +import org.springframework.ai.tool.ToolCallbackProvider; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +import poc.google.mcpserver.processor.OASSchemaHandler; +import poc.google.mcpserver.tool.DynamicOpenApiToolCallbackProvider; + +/** + * Configuration class for creating Spring AI {@link ToolCallbackProvider} beans + * from OpenAPI specifications. This allows for dynamic generation of tools + * that can be used by an AI model. + */ +@Configuration +public class ToolsConfiguration { + + /** + * The environment for the API (e.g., 'petstore3.swagger.io'). + */ + @Value("${api.envUrl}") + private String apiUrlEnv; + + /** + * Creates a {@link ToolCallbackProvider} for the Pet Store API. + * The tools are dynamically generated from the {@code /openapi/petStore.yaml} specification. + * + * @param schemaProcessor The processor to handle complex OpenAPI schema constructs. + * @param restTemplate The RestTemplate to use for making API calls. + * @return A {@link ToolCallbackProvider} containing tools for the Pet Store API. + */ + @Bean + ToolCallbackProvider petStoreTools(OASSchemaHandler schemaProcessor, RestTemplate restTemplate) { + return new DynamicOpenApiToolCallbackProvider("/openapi/petStore.yaml", schemaProcessor, restTemplate, apiUrlEnv); + } + +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/OASSchemaHandler.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/OASSchemaHandler.java new file mode 100644 index 00000000000..9f4f0ddbc59 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/OASSchemaHandler.java @@ -0,0 +1,60 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.processor; + +import java.util.List; + +import io.swagger.v3.oas.models.media.Schema; +import poc.google.mcpserver.processor.keywords.IKeywordHandler; + +/** + * A handler that processes an OpenAPI {@link Schema} object by applying a series of + * keyword-specific handlers. It recursively traverses the schema structure (objects and arrays) + * to ensure all parts of the schema are processed. + */ +public class OASSchemaHandler { + + private final List keywordHandlers; + + /** + * Constructs a new SchemaHandler with a list of keyword handlers. + * + * @param keywordHandlers The list of {@link IKeywordHandler} instances to apply to the schemas. + */ + public OASSchemaHandler(List keywordHandlers) { + this.keywordHandlers = keywordHandlers; + } + + /** + * Processes the given schema by applying all configured keyword handlers and then + * recursively processing any nested schemas within its properties or items. + * + * @param schema The {@link Schema} object to process. Can be null. + */ + public void process(Schema schema) { + if (schema == null) { + return; + } + + keywordHandlers.forEach(handler -> handler.process(schema)); + + if ("object".equals(schema.getType()) && schema.getProperties() != null) { + schema.getProperties().values().forEach(this::process); + } else if ("array".equals(schema.getType()) && schema.getItems() != null) { + process(schema.getItems()); + } + } +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/AllOfHandler.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/AllOfHandler.java new file mode 100644 index 00000000000..55afbe2b63c --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/AllOfHandler.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.processor.keywords; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.swagger.v3.oas.models.media.Schema; + +/** + * A handler for the {@code allOf} keyword in an OpenAPI schema. + * This handler merges the properties of all sub-schemas listed in the {@code allOf} + * array into a single superset of properties in the parent schema. This flattens + * the structure, making it simpler for consumers that may not fully support composition keywords. + */ +public class AllOfHandler implements IKeywordHandler { + + /** + * Processes a schema to resolve the {@code allOf} keyword. + * @param schema The schema to process. + */ + @Override + public void process(Schema schema) { + List subSchemaList = schema.getAllOf(); + if(subSchemaList != null && subSchemaList.size() > 0) { + Map supersetProperties = new HashMap<>(); + + subSchemaList.stream() + .filter(subSchema -> subSchema.getProperties() != null) + .map(Schema::getProperties) + .forEach(supersetProperties::putAll); + + schema.setProperties(supersetProperties); + schema.setAllOf(null); + } + } + +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/AnyOfHandler.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/AnyOfHandler.java new file mode 100644 index 00000000000..3bde0f88a42 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/AnyOfHandler.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.processor.keywords; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.swagger.v3.oas.models.media.Schema; + +/** + * A handler for the {@code anyOf} keyword in an OpenAPI schema. + * This handler merges the properties of all sub-schemas listed in the {@code anyOf} + * array into a single superset of properties in the parent schema. This flattens + * the structure, making it simpler for consumers that may not fully support composition keywords. + */ +public class AnyOfHandler implements IKeywordHandler { + + /** + * Processes a schema to resolve the {@code anyOf} keyword. + * @param schema The schema to process. + */ + @Override + public void process(Schema schema) { + List subSchemaList = schema.getAnyOf(); + if(subSchemaList != null && subSchemaList.size() > 0) { + Map supersetProperties = new HashMap<>(); + + subSchemaList.stream() + .filter(subSchema -> subSchema.getProperties() != null) + .map(Schema::getProperties) + .forEach(supersetProperties::putAll); + + schema.setProperties(supersetProperties); + schema.setAnyOf(null); + } + } + +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/IKeywordHandler.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/IKeywordHandler.java new file mode 100644 index 00000000000..6fb8ae8c87e --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/IKeywordHandler.java @@ -0,0 +1,22 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.processor.keywords; + +import io.swagger.v3.oas.models.media.Schema; + +public interface IKeywordHandler { + void process(Schema schema); +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/OneOfHandler.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/OneOfHandler.java new file mode 100644 index 00000000000..98e402a35ca --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/processor/keywords/OneOfHandler.java @@ -0,0 +1,52 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.processor.keywords; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import io.swagger.v3.oas.models.media.Schema; + +/** + * A handler for the {@code oneOf} keyword in an OpenAPI schema. + * This handler merges the properties of all sub-schemas listed in the {@code oneOf} + * array into a single superset of properties in the parent schema. This flattens + * the structure, making it simpler for consumers that may not fully support composition keywords. + */ +public class OneOfHandler implements IKeywordHandler { + + /** + * Processes a schema to resolve the {@code oneOf} keyword. + * @param schema The schema to process. + */ + @Override + public void process(Schema schema) { + List subSchemaList = schema.getOneOf(); + if(subSchemaList != null && subSchemaList.size() > 0) { + Map supersetProperties = new HashMap<>(); + + subSchemaList.stream() + .filter(subSchema -> subSchema.getProperties() != null) + .map(Schema::getProperties) + .forEach(supersetProperties::putAll); + + schema.setProperties(supersetProperties); + schema.setOneOf(null); + } + } + +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/prompt/DynamicPromptTemplateExamplesGenerator.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/prompt/DynamicPromptTemplateExamplesGenerator.java new file mode 100644 index 00000000000..fa871a89bfb --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/prompt/DynamicPromptTemplateExamplesGenerator.java @@ -0,0 +1,163 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.prompt; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; + +import io.modelcontextprotocol.server.McpServerFeatures; +import io.modelcontextprotocol.server.McpServerFeatures.SyncPromptSpecification; +import io.modelcontextprotocol.spec.McpSchema; +import io.modelcontextprotocol.spec.McpSchema.GetPromptResult; +import io.modelcontextprotocol.spec.McpSchema.PromptMessage; +import io.modelcontextprotocol.spec.McpSchema.Role; +import io.modelcontextprotocol.spec.McpSchema.TextContent; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.examples.Example; +import io.swagger.v3.parser.OpenAPIV3Parser; +import io.swagger.v3.parser.core.models.ParseOptions; + +/** + * Dynamically generates MCP (Model Context Protocol) {@link SyncPromptSpecification} instances + * from the examples found in an OpenAPI specification file. + *

+ * This class reads an OpenAPI file, extracts the request body examples for each operation, + * and creates a corresponding prompt specification that can serve these examples to an AI model. + */ +public class DynamicPromptTemplateExamplesGenerator { + + private static final Logger log = LoggerFactory.getLogger(DynamicPromptTemplateExamplesGenerator.class); + + private final ObjectMapper objectMapper = JsonMapper.builder().configure(MapperFeature.REQUIRE_HANDLERS_FOR_JAVA8_TIMES, false).build(); + private final List syncPromptSpecificationList = new ArrayList<>(); + + /** + * Generates a list of {@link McpServerFeatures.SyncPromptSpecification} from a given OpenAPI specification file. + * It parses the spec, iterates through all operations, and constructs a prompt for each operation that has examples. + * + * @param openApiSpecPath The classpath resource path to the OpenAPI specification YAML file. + * @return A list of {@link McpServerFeatures.SyncPromptSpecification} containing the extracted examples. + * @throws RuntimeException if the OpenAPI spec file cannot be found, read, or parsed. + */ + public List generatPromptTemplatesFromOAS(String openApiSpecPath){ + + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + try (InputStream inputStream = this.getClass().getResourceAsStream(openApiSpecPath)) { + if (inputStream == null) { + throw new IllegalArgumentException("OpenAPI spec not found on classpath: " + openApiSpecPath); + } + + String spec = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); + ParseOptions options = new ParseOptions(); + options.setResolve(true); + options.setResolveFully(true); + OpenAPI openAPI = new OpenAPIV3Parser().readContents(spec, null, options).getOpenAPI(); + + if (openAPI == null) { + throw new RuntimeException("Failed to read OpenAPI spec from: " + openApiSpecPath); + } + + openAPI.getPaths().forEach((path, pathItem) -> { + pathItem.readOperationsMap().forEach((httpMethod, operation) -> constructPrompts(operation, openAPI)); + }); + + } catch (Exception e) { + throw new RuntimeException("Failed to load and parse OpenAPI spec", e); + } + + return syncPromptSpecificationList; + } + + /** + * Extracts and serializes the request body examples for a given OpenAPI operation. + * It handles resolving {@code $ref} pointers to examples defined in the components section. + * + * @param operation The OpenAPI {@link Operation} from which to extract examples. + * @param openAPI The fully resolved {@link OpenAPI} model, used for resolving references. + * @return A JSON string representation of the examples, or a fallback message if no examples are found or an error occurs. + */ + private String extractExamplesFromReqBody(Operation operation, OpenAPI openAPI) { + + if (operation.getRequestBody().getContent().get("application/json").getExamples() == null) { + return "Refer tool description and inputSchema to build JSON Request Body"; + } + + Map examplesMap = operation.getRequestBody().getContent().get("application/json").getExamples(); + + try { + // Manually resolve $ref in examples + for (Map.Entry entry : examplesMap.entrySet()) { + Example example = entry.getValue(); + if (example.get$ref() != null) { + String ref = example.get$ref(); + if (ref.startsWith("#/components/examples/")) { + String exampleName = ref.substring("#/components/examples/".length()); + if (openAPI.getComponents() != null && openAPI.getComponents().getExamples() != null) { + Example resolvedExample = openAPI.getComponents().getExamples().get(exampleName); + if (resolvedExample != null) { + entry.setValue(resolvedExample); + } + } + } + } + } + String examples = objectMapper.writeValueAsString(examplesMap); + log.debug("Extracted examples for operation {}: {}", operation.getOperationId(), examples); + return examples; + } catch (JsonProcessingException e) { + log.warn("JsonProcessingException while extracting examples for operation {}", operation.getOperationId(), e); + return "Refer tool description and inputSchema to build JSON Request Body"; + } + } + + /** + * Constructs a {@link McpServerFeatures.SyncPromptSpecification} for a given operation. + * The prompt contains the extracted request body examples. + * + * @param operation The OpenAPI {@link Operation} to construct the prompt for. + * @param openAPI The fully resolved {@link OpenAPI} model. + */ + private void constructPrompts(Operation operation, OpenAPI openAPI) { + + String operationId = operation.getOperationId(); + if (operationId == null || operationId.isBlank()) return; + + String examples = extractExamplesFromReqBody(operation, openAPI); + + var prompt = new McpSchema.Prompt(operation.getOperationId() + "_examples", "Examples of Request Body for " + operation.getOperationId() + " tool", null); + + syncPromptSpecificationList.add(new McpServerFeatures.SyncPromptSpecification(prompt, (exchange, getPromptRequest) -> { + var userMessage = new PromptMessage(Role.USER, new TextContent( + examples + )); + return new GetPromptResult("Tool Request Body Examples", List.of(userMessage)); + })); + } +} diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/tool/DynamicOpenApiToolCallbackProvider.java b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/tool/DynamicOpenApiToolCallbackProvider.java new file mode 100644 index 00000000000..f4358c3e026 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/java/poc/google/mcpserver/tool/DynamicOpenApiToolCallbackProvider.java @@ -0,0 +1,438 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver.tool; + +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.function.BiFunction; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.ai.chat.model.ToolContext; +import org.springframework.ai.tool.ToolCallback; +import org.springframework.ai.tool.ToolCallbackProvider; +import org.springframework.ai.tool.definition.ToolDefinition; +import org.springframework.ai.tool.function.FunctionToolCallback; +import org.springframework.core.ResolvableType; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.ResponseEntity; +import org.springframework.web.client.RestTemplate; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.MapperFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.json.JsonMapper; + +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.examples.Example; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.parser.OpenAPIV3Parser; +import io.swagger.v3.parser.core.models.ParseOptions; +import poc.google.mcpserver.processor.OASSchemaHandler; + +/** + * A {@link ToolCallbackProvider} that dynamically creates {@link ToolCallback} instances + * from an OpenAPI specification file. + *

+ * This class parses an OpenAPI specification, and for each operation defined, it constructs + * a corresponding {@link FunctionToolCallback}. This tool can then be invoked by an AI model. + * The tool's function is to make an HTTP request to the API endpoint described by the operation. + * It handles schema processing, example extraction, and the actual REST call. + */ +public class DynamicOpenApiToolCallbackProvider implements ToolCallbackProvider { + + private static final Logger logger = LoggerFactory.getLogger(DynamicOpenApiToolCallbackProvider.class); + + private final OASSchemaHandler schemaProcessor; + + private final RestTemplate restTemplate; + private final Map> toolMap = new LinkedHashMap<>(); + private final Map opIdToInputSchemaMap = new HashMap<>(); + private final Map opIdToDescriptionMap = new HashMap<>(); + private final Map> opIdToParamMap = new HashMap<>(); + + private final ObjectMapper objectMapper = JsonMapper.builder().configure(MapperFeature.REQUIRE_HANDLERS_FOR_JAVA8_TIMES, false).build(); + + private final String defaultInputSchema = """ + { + "type": "object", + "properties": {} + } + """; + + /** + * Constructs a new DynamicOpenApiToolCallbackProvider. + * It reads and parses the OpenAPI specification from the given path, then constructs + * a tool for each operation found. + * + * @param openApiSpecPath The classpath resource path to the OpenAPI specification file. + * @param schemaProcessor A handler to process and simplify OpenAPI schemas. + * @param restTemplate The {@link RestTemplate} to use for making the API calls. + * @param apiUrlEnv The environment string (e.g., 'api.cert.platform') to substitute in the server URL. + */ + public DynamicOpenApiToolCallbackProvider( + String openApiSpecPath, + OASSchemaHandler schemaProcessor, + RestTemplate restTemplate, + String apiUrlEnv + ) { + + this.schemaProcessor = schemaProcessor; + this.restTemplate = restTemplate; + + // objectMapper.enable(SerializationFeature.INDENT_OUTPUT); + objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + + try (InputStream inputStream = this.getClass().getResourceAsStream(openApiSpecPath)) { + if (inputStream == null) { + throw new IllegalArgumentException("OpenAPI spec not found on classpath: " + openApiSpecPath); + } + + String spec = new String(inputStream.readAllBytes(), StandardCharsets.UTF_8); + + ParseOptions options = new ParseOptions(); + options.setResolve(true); + options.setResolveFully(true); + OpenAPI openAPI = new OpenAPIV3Parser().readContents(spec, null, options).getOpenAPI(); + + if (openAPI == null) { + throw new RuntimeException("Failed to read OpenAPI spec from: " + openApiSpecPath); + } + + + String apiUrl = openAPI.getServers().get(0).getUrl() + .replace("{environment}", apiUrlEnv); + + openAPI.getPaths().forEach( + (path, pathItem) -> { + pathItem.readOperationsMap().forEach( + (httpMethod, operation) -> constructToolMap(apiUrl, path, httpMethod, operation, openAPI)); + } + ); + + } catch (Exception e) { + logger.error("Failed to load and parse OpenAPI spec from: {}", openApiSpecPath, e); + throw new RuntimeException("Failed to load and parse OpenAPI spec", e); + } + } + + /** + * Constructs a single tool (a function) based on an OpenAPI {@link Operation}. + * This method extracts the necessary information like operationId, input schema, and description, + * and creates a function that, when called, executes an HTTP request against the API. + * + * @param apiUrl The base URL of the API server. + * @param path The specific path for the operation (e.g., "/v1/offers/flightShop"). + * @param httpMethod The HTTP method for the operation (e.g., POST). + * @param operation The OpenAPI {@link Operation} object. + * @param openAPI The fully parsed {@link OpenAPI} object for resolving references. + */ + private void constructToolMap(String apiUrl, String path, PathItem.HttpMethod httpMethod, Operation operation, OpenAPI openAPI) { + String operationId = operation.getOperationId(); + if (operationId == null || operationId.isBlank()) return; + + String inputSchema = buildInputSchema(operation); + opIdToInputSchemaMap.put(operationId, inputSchema); + + String opDesc = operation.getDescription(); + String examples = extractExamplesForOp(operation, openAPI); + opDesc = opDesc + "\n" + "Below are some examples on how to structure the request body for the tool based on different use cases:\n" + examples; + opIdToDescriptionMap.put(operationId, opDesc); + + toolMap.put(operationId, (input, context) -> { + try{ + System.out.println("Tool operationId => " + operationId); + + String resolvedPath = path; + String fullUrl = apiUrl + resolvedPath; + + List paramList = opIdToParamMap.get(operationId); + + Map restCallDataMap = constructUrlParamsAndRequestBodyFromInput(operationId, input, fullUrl, paramList); + + String requestBody=""; + try { + requestBody = objectMapper.writeValueAsString(restCallDataMap.get("requestBody")); + } catch (JsonProcessingException e) { + logger.error("Failed to convert to JSON request for operationId: {}", operationId, e); + } + String finalUrl = (String) restCallDataMap.get("finalUrl"); + + logger.debug("Executing tool '{}' with finalUrl: {} and requestBody: {}", operationId, finalUrl, requestBody); + + HttpHeaders headers = new HttpHeaders(); + // headers.setBearerAuth(authToken); + HttpEntity entity = null; + + if(httpMethod.name().equals("GET")) { + entity = new HttpEntity<>(headers); + } else { + entity = new HttpEntity<>(requestBody, headers); + } + + ResponseEntity response = restTemplate.exchange( + finalUrl, + HttpMethod.valueOf(httpMethod.name()), + entity, + String.class + ); + + try { + logger.debug("Response for operationId '{}': {}", operationId, response.getBody()); + return response.getBody(); + } catch (Exception e) { + logger.error("Failed to parse JSON response for operationId: {}", operationId, e); + throw new RuntimeException("Failed to parse JSON response for " + operationId, e); + } + } catch (Exception e) { + logger.error("operationId: {} failed with error: {}", operationId, e); + throw new RuntimeException("Failed to execute tool for op id => " + operationId, e); + } + }); + } + + // private Map constructUrlParamsAndRequestBodyFromInput(String operationId, Object input, String fullUrl, List paramList) { + + // Map inputMap = new HashMap<>(); + + // try { + // inputMap = objectMapper.convertValue(input, new TypeReference>() {}); + // logger.debug("inputMap: {}", inputMap); + // for(Map.Entry entry : inputMap.entrySet()) { + // System.out.println(entry.getKey() + " => " + entry.getKey().getClass()); + // System.out.println(entry.getValue() + " => " + entry.getValue().getClass()); + // } + // logger.debug("Input requestBody for operationId '{}': {}", operationId, inputMap.get("requestBody")); + // } catch (IllegalArgumentException e) { + // logger.error("Error serializing request body for operationId: {}", operationId, e); + // } + + // if(paramList != null) { + // List queryParamStrList = new ArrayList<>(); + // for(Parameter param : paramList) { + // if(inputMap.containsKey(param.getName())) { + // if("path".equals(param.getIn())) { + // fullUrl.replace("{" + param.getName() + "}", inputMap.get(param.getName())); + // } else if ("query".equals(param.getIn())) { + // if(param.getSchema().getType().equals("array")) { + // //TODO: ARRAY IMPLEMENTATION + // // ArrayList test = inputMap.get(param.getName()); + // // if(test instanceof ArrayList){ + + // // } + // System.out.println("query array => " + inputMap.get(param.getName())); + // } else { + // queryParamStrList.add(param.getName() + "=" + inputMap.get(param.getName())); + // // querySb.append(param.getName() + "=" + inputMap.get(param.getName())); + // // fullUrl += ("?" + param.getName() + "=" + inputMap.get(param.getName())); + // } + // } + // } + // if(queryParamStrList.size() > 0) { + // fullUrl += "?" + String.join("&", queryParamStrList); + // } + // } + // inputMap.put("finalUrl", fullUrl); + // } else { + // inputMap.put("finalUrl", fullUrl); + // } + + // return inputMap; + // } + + private Map constructUrlParamsAndRequestBodyFromInput(String operationId, Object input, String fullUrl, List paramList) { + + Map inputMap = (HashMap) input; + + // Map inputMap = new HashMap<>(); + + // try { + // inputMap = objectMapper.convertValue(input, new TypeReference>() {}); + // logger.debug("inputMap: {}", inputMap); + // for(Map.Entry entry : inputMap.entrySet()) { + // System.out.println(entry.getKey() + " => " + entry.getKey().getClass()); + // System.out.println(entry.getValue() + " => " + entry.getValue().getClass()); + // } + // logger.debug("Input requestBody for operationId '{}': {}", operationId, inputMap.get("requestBody")); + // } catch (IllegalArgumentException e) { + // logger.error("Error serializing request body for operationId: {}", operationId, e); + // } + + if(paramList != null) { + List queryParamStrList = new ArrayList<>(); + for(Parameter param : paramList) { + if(inputMap.containsKey(param.getName())) { + if("path".equals(param.getIn())) { + fullUrl = fullUrl.replace("{" + param.getName() + "}", String.valueOf(inputMap.get(param.getName()))); + } else if ("query".equals(param.getIn())) { + if(param.getSchema().getType().equals("array")) { + //TODO: ARRAY IMPLEMENTATION + System.out.println("query array => " + inputMap.get(param.getName())); + if(inputMap.get(param.getName()) instanceof List) { + List tempStrList = (List) inputMap.get(param.getName()); + tempStrList.forEach((element) -> queryParamStrList.add(param.getName() + "=" + element)); + } + } else { + queryParamStrList.add(param.getName() + "=" + inputMap.get(param.getName())); + // querySb.append(param.getName() + "=" + inputMap.get(param.getName())); + // fullUrl += ("?" + param.getName() + "=" + inputMap.get(param.getName())); + } + } + } + if(queryParamStrList.size() > 0) { + fullUrl += "?" + String.join("&", queryParamStrList); + } + } + inputMap.put("finalUrl", fullUrl); + } else { + inputMap.put("finalUrl", fullUrl); + } + + return inputMap; + } + + + /** + * {@inheritDoc} + */ + @Override + public ToolCallback[] getToolCallbacks() { + return toolMap.entrySet().stream() + .map(entry -> { + String operationId = entry.getKey(); + String schema = opIdToInputSchemaMap.getOrDefault(operationId, defaultInputSchema); + String description = opIdToDescriptionMap.getOrDefault(operationId, "Tool generated from OpenAPI spec"); + + logger.debug("Schema for tool '{}': {}", operationId, schema); + + ToolDefinition definition = ToolDefinition.builder() + .name(operationId) + .description(description) + .inputSchema(schema) + .build(); + + return new FunctionToolCallback( + definition, + null, + ResolvableType.forClass(Object.class).getType(), + entry.getValue(), + null + ); + }) + .toArray(ToolCallback[]::new); + } + + /** + * Builds a JSON schema string for the input of a tool from the operation's parameters and request body. + * It uses the {@link OASSchemaHandler} to process and simplify the schema before serialization. + * + * @param operation The OpenAPI {@link Operation}. + * @return A JSON string representing the input schema, or a default empty object schema on failure. + */ + private String buildInputSchema(Operation operation) { + + Schema rootSchema; + rootSchema = new Schema<>(); + rootSchema.setType("object"); + rootSchema.setProperties(new HashMap<>()); + List reqList = new ArrayList<>(); + + if(operation.getParameters() != null) { + operation.getParameters().forEach(parameter -> { + if (parameter.getRequired()) + reqList.add(parameter.getName()); + rootSchema.getProperties().put(parameter.getName(), parameter.getSchema()); + }); + opIdToParamMap.put(operation.getOperationId(), operation.getParameters()); + } + + if(operation.getRequestBody() != null && + operation.getRequestBody().getContent()!= null && + operation.getRequestBody().getContent().get("application/json") != null && + operation.getRequestBody().getContent().get("application/json").getSchema() != null) { + Schema requestBodySchema = operation.getRequestBody().getContent().get("application/json").getSchema(); + schemaProcessor.process(requestBodySchema); + reqList.add("requestBody"); + rootSchema.getProperties().put("requestBody", requestBodySchema); + } + + rootSchema.setRequired(reqList); + + try { + return objectMapper.writeValueAsString(rootSchema); + } catch (JsonProcessingException e) { + logger.error("Error processing schema for operation: {}", operation.getOperationId(), e); + return defaultInputSchema; + } + } + + /** + * Extracts and serializes the request body examples for a given OpenAPI operation. + * This method manually resolves {@code $ref} pointers to examples defined in the components section. + * The serialized examples are appended to the tool's description to provide context to the AI model. + * + * @param operation The OpenAPI {@link Operation} from which to extract examples. + * @param openAPI The fully parsed {@link OpenAPI} model for resolving references. + * @return A JSON string of the examples, or a fallback message if none are found or an error occurs. + */ + private String extractExamplesForOp(Operation operation, OpenAPI openAPI) { + + if (operation.getRequestBody() == null || + operation.getRequestBody().getContent() == null || + operation.getRequestBody().getContent().get("application/json") == null || + operation.getRequestBody().getContent().get("application/json").getExamples() == null) { + return "Refer tool description and inputSchema to build JSON Request Body"; + } + + Map examplesMap = operation.getRequestBody().getContent().get("application/json").getExamples(); + + try { + // Manually resolve $ref in examples + for (Map.Entry entry : examplesMap.entrySet()) { + Example example = entry.getValue(); + if (example.get$ref() != null) { + String ref = example.get$ref(); + if (ref.startsWith("#/components/examples/")) { + String exampleName = ref.substring("#/components/examples/".length()); + if (openAPI.getComponents() != null && openAPI.getComponents().getExamples() != null) { + Example resolvedExample = openAPI.getComponents().getExamples().get(exampleName); + if (resolvedExample != null) { + entry.setValue(resolvedExample); + } + } + } + } + } + String examples = objectMapper.writeValueAsString(examplesMap); + logger.debug("Extracted examples for operation '{}': {}", operation.getOperationId(), examples); + return examples; + } catch (JsonProcessingException e) { + logger.warn("Could not process and extract examples for operation: {}", operation.getOperationId(), e); + return "Refer tool description and inputSchema to build JSON Request Body"; + } + } +} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/resources/application.yaml b/tools/oas-mcp-tools-weaver/mcpserver/src/main/resources/application.yaml new file mode 100644 index 00000000000..7cddea99e7f --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/resources/application.yaml @@ -0,0 +1,21 @@ +server: + port: 8081 +spring: + ai: + mcp: + server: + capabilities.prompt: true + application: + name: mcpserver +logging: + level: + poc.google.mcpserver.tool.DynamicOpenApiToolCallbackProvider: DEBUG + +management: + endpoints: + web: + exposure: + include: "*" + +api: + envUrl: ${API_ENV_URL} \ No newline at end of file diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/main/resources/openapi/petStore.yaml b/tools/oas-mcp-tools-weaver/mcpserver/src/main/resources/openapi/petStore.yaml new file mode 100644 index 00000000000..47ff8d529f9 --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/main/resources/openapi/petStore.yaml @@ -0,0 +1,450 @@ +--- +openapi: 3.0.4 +info: + title: Swagger Petstore - OpenAPI 3.0 + description: |- + This is a sample Pet Store Server based on the OpenAPI 3.0 specification. You can find out more about + Swagger at [https://swagger.io](https://swagger.io). In the third iteration of the pet store, we've switched to the design first approach! + You can now help us improve the API whether it's by making changes to the definition itself or to the code. + That way, with time, we can improve the API in general, and expose some of the new features in OAS3. + + Some useful links: + - [The Pet Store repository](https://github.com/swagger-api/swagger-petstore) + - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml) + termsOfService: https://swagger.io/terms/ + contact: + email: apiteam@swagger.io + license: + name: Apache 2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + version: 1.0.27 +externalDocs: + description: Find out more about Swagger + url: https://swagger.io +servers: +- url: "https://{environment}/api/v3" + variables: + environment: + default: 'petstore3.swagger.io' + enum: + - petstore3.swagger.io +tags: +- name: Pet + description: Everything about your Pets + externalDocs: + description: Find out more + url: https://swagger.io +paths: + "/pet": + put: + tags: + - pet + summary: Update an existing pet. + description: Update an existing pet by Id. + operationId: updatePet + requestBody: + description: Update an existent pet in the store + content: + application/json: + schema: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + "$ref": "#/components/schemas/Pet" + application/x-www-form-urlencoded: + schema: + "$ref": "#/components/schemas/Pet" + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + "$ref": "#/components/schemas/Pet" + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '422': + description: Validation exception + default: + description: Unexpected error + security: + - petstore_auth: + - write:pets + - read:pets + post: + tags: + - pet + summary: Add a new pet to the store. + description: Add a new pet to the store. + operationId: addPet + requestBody: + description: Create a new pet in the store + content: + application/json: + schema: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + "$ref": "#/components/schemas/Pet" + application/x-www-form-urlencoded: + schema: + "$ref": "#/components/schemas/Pet" + required: true + responses: + '200': + description: Successful operation + content: + application/json: + schema: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + "$ref": "#/components/schemas/Pet" + '400': + description: Invalid input + '422': + description: Validation exception + default: + description: Unexpected error + security: + - petstore_auth: + - write:pets + - read:pets + "/pet/findByStatus": + get: + tags: + - pet + summary: Finds Pets by status. + description: Multiple status values can be provided with comma separated strings. + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + explode: true + schema: + type: string + default: available + enum: + - available + - pending + - sold + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + type: array + items: + "$ref": "#/components/schemas/Pet" + '400': + description: Invalid status value + default: + description: Unexpected error + security: + - petstore_auth: + - write:pets + - read:pets + "/pet/findByTags": + get: + tags: + - pet + summary: Finds Pets by tags. + description: Multiple tags can be provided with comma separated strings. Use + tag1, tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + explode: true + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: array + items: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + type: array + items: + "$ref": "#/components/schemas/Pet" + '400': + description: Invalid tag value + default: + description: Unexpected error + security: + - petstore_auth: + - write:pets + - read:pets + "/pet/{petId}": + get: + tags: + - pet + summary: Find pet by ID. + description: Returns a single pet. + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + "$ref": "#/components/schemas/Pet" + '400': + description: Invalid ID supplied + '404': + description: Pet not found + default: + description: Unexpected error + security: + - api_key: [] + - petstore_auth: + - write:pets + - read:pets + post: + tags: + - pet + summary: Updates a pet in the store with form data. + description: Updates a pet resource based on the form data. + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + - name: name + in: query + description: Name of pet that needs to be updated + schema: + type: string + - name: status + in: query + description: Status of pet that needs to be updated + schema: + type: string + responses: + '200': + description: successful operation + content: + application/json: + schema: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + "$ref": "#/components/schemas/Pet" + '400': + description: Invalid input + default: + description: Unexpected error + security: + - petstore_auth: + - write:pets + - read:pets + delete: + tags: + - pet + summary: Deletes a pet. + description: Delete a pet. + operationId: deletePet + parameters: + - name: api_key + in: header + description: '' + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: Pet deleted + '400': + description: Invalid pet value + default: + description: Unexpected error + security: + - petstore_auth: + - write:pets + - read:pets + "/pet/{petId}/uploadImage": + post: + tags: + - pet + summary: Uploads an image. + description: Upload image of the pet. + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + - name: additionalMetadata + in: query + description: Additional Metadata + required: false + schema: + type: string + requestBody: + content: + application/octet-stream: + schema: + type: string + format: binary + responses: + '200': + description: successful operation + content: + application/json: + schema: + "$ref": "#/components/schemas/ApiResponse" + '400': + description: No file uploaded + '404': + description: Pet not found + default: + description: Unexpected error + security: + - petstore_auth: + - write:pets + - read:pets +components: + schemas: + Category: + type: object + properties: + id: + type: integer + format: int64 + example: 1 + name: + type: string + example: Dogs + xml: + name: category + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: tag + Pet: + required: + - id + - name + type: object + properties: + id: + type: integer + format: int64 + example: 10 + name: + type: string + example: doggie + category: + "$ref": "#/components/schemas/Category" + photoUrls: + type: array + xml: + wrapped: true + items: + type: string + xml: + name: photoUrl + tags: + type: array + xml: + wrapped: true + items: + "$ref": "#/components/schemas/Tag" + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: pet + ApiResponse: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + xml: + name: "##default" + requestBodies: + Pet: + description: Pet object that needs to be added to the store + content: + application/json: + schema: + "$ref": "#/components/schemas/Pet" + application/xml: + schema: + "$ref": "#/components/schemas/Pet" + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: https://petstore3.swagger.io/oauth/authorize + scopes: + write:pets: modify pets in your account + read:pets: read your pets + api_key: + type: apiKey + name: api_key + in: header diff --git a/tools/oas-mcp-tools-weaver/mcpserver/src/test/java/poc/google/mcpserver/McpserverApplicationTests.java b/tools/oas-mcp-tools-weaver/mcpserver/src/test/java/poc/google/mcpserver/McpserverApplicationTests.java new file mode 100644 index 00000000000..5ae9837e73e --- /dev/null +++ b/tools/oas-mcp-tools-weaver/mcpserver/src/test/java/poc/google/mcpserver/McpserverApplicationTests.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2025 Google Inc. + * + * 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. + */ +package poc.google.mcpserver; + +import org.junit.jupiter.api.Test; +import org.springframework.boot.test.context.SpringBootTest; + +@SpringBootTest +class McpserverApplicationTests { + + @Test + void contextLoads() { + } + +} diff --git a/tools/oas-mcp-tools-weaver/weaver-logo.png b/tools/oas-mcp-tools-weaver/weaver-logo.png new file mode 100644 index 00000000000..07615214d95 Binary files /dev/null and b/tools/oas-mcp-tools-weaver/weaver-logo.png differ