diff --git a/examples/basic-server-java-webflux/.gitignore b/examples/basic-server-java-webflux/.gitignore new file mode 100644 index 00000000..0f803630 --- /dev/null +++ b/examples/basic-server-java-webflux/.gitignore @@ -0,0 +1,7 @@ +target/ +*.iml +.idea/ +.vscode/ +*.class +*.jar +.DS_Store diff --git a/examples/basic-server-java-webflux/.mvn/wrapper/maven-wrapper.properties b/examples/basic-server-java-webflux/.mvn/wrapper/maven-wrapper.properties new file mode 100644 index 00000000..308007b5 --- /dev/null +++ b/examples/basic-server-java-webflux/.mvn/wrapper/maven-wrapper.properties @@ -0,0 +1,2 @@ +distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip +wrapperUrl=https://repo.maven.apache.org/maven2/org/apache/maven/wrapper/maven-wrapper/3.3.2/maven-wrapper-3.3.2.jar diff --git a/examples/basic-server-java-webflux/README.md b/examples/basic-server-java-webflux/README.md new file mode 100644 index 00000000..ae1207e1 --- /dev/null +++ b/examples/basic-server-java-webflux/README.md @@ -0,0 +1,151 @@ +# Example: Basic Server (Java WebFlux) + +A minimal Java MCP server that performs math operations with an interactive calculator UI. Demonstrates the MCP Java SDK with Spring Boot WebFlux and Streamable HTTP transport. + +## MCP Client Configuration + +This server uses HTTP transport only (no stdio). Add to your MCP client configuration: + +```json +{ + "mcpServers": { + "calculator": { + "url": "http://localhost:3001/mcp" + } + } +} +``` + +### Local Development + +To test local modifications, first clone the repository and start the server: + +```bash +git clone https://github.com/modelcontextprotocol/ext-apps.git +cd ext-apps/examples/basic-server-java-webflux +./mvnw spring-boot:run +``` + +Then configure your MCP client to connect to `http://localhost:3001/mcp`. + +## Features + +- Four basic operations: add, subtract, multiply, divide +- Interactive calculator view using ext-apps SDK +- Division by zero error handling +- Structured content metadata for UI integration +- Dark mode support +- Three MCP prompts for guided interactions + +## Prerequisites + +- Java 17+ (`java -version`) +- No global Maven needed (Maven wrapper included) + +## Running + +1. Start the server: + + ```bash + ./mvnw spring-boot:run + # → Calculator listening on http://localhost:3001/mcp + ``` + +2. View using the [`basic-host`](https://github.com/modelcontextprotocol/ext-apps/tree/main/examples/basic-host) example or another MCP Apps-compatible host. + +### Custom Port + +```bash +PORT=3120 ./mvnw spring-boot:run +``` + +### Docker (accessing host server from container) + +``` +http://host.docker.internal:3001/mcp +``` + +## Tool: `calculate` + +Perform a math operation on two numbers. Supports add, subtract, multiply, and divide. + +### Parameters + +| Parameter | Type | Default | Description | +| ----------- | ------ | ---------- | ------------------------------------------------------- | +| `operation` | string | (required) | Math operation: `add`, `subtract`, `multiply`, `divide` | +| `a` | number | (required) | First operand | +| `b` | number | (required) | Second operand | + +### Example Inputs + +**Basic addition:** + +```json +{ "operation": "add", "a": 5, "b": 3 } +``` + +**Decimal multiplication:** + +```json +{ "operation": "multiply", "a": 3.14, "b": 2 } +``` + +**Division by zero (returns error):** + +```json +{ "operation": "divide", "a": 10, "b": 0 } +``` + +## Prompts + +| Prompt | Description | Arguments | +| ----------------- | --------------------------------------------- | ------------ | +| `quick-calc` | Evaluate a math expression step by step | `expression` | +| `compare-numbers` | Compare two numbers using all four operations | `a`, `b` | +| `percentage` | Calculate percentages | `question` | + +## Architecture + +### Server + +Four Spring components wired via `McpConfig`: + +- **`McpConfig`** - Configures `WebFluxStreamableServerTransportProvider`, `RouterFunction`, and `McpSyncServer` with tools, resources, and prompts +- **`CalculatorTools`** - Tool definition with UI metadata and calculation handler +- **`CalculatorResources`** - Serves the interactive HTML view as an MCP resource with CSP metadata +- **`CalculatorPrompts`** - Three guided prompts for common calculation patterns + +### App (`view.html`) + +Vanilla JavaScript UI that: + +- Loads the MCP Apps SDK from CDN (`@modelcontextprotocol/ext-apps`) +- Provides number inputs and operation buttons +- Calls `app.callServerTool()` on button click +- Displays results from `ontoolresult` callback and `structuredContent` metadata +- Adapts to dark mode via `prefers-color-scheme` + +### Key Files + +- [`src/main/java/.../McpConfig.java`](src/main/java/com/example/calculator/McpConfig.java) - Spring configuration with WebFlux transport +- [`src/main/java/.../CalculatorTools.java`](src/main/java/com/example/calculator/CalculatorTools.java) - Tool definition and handler +- [`src/main/java/.../CalculatorResources.java`](src/main/java/com/example/calculator/CalculatorResources.java) - HTML resource with CSP +- [`src/main/java/.../CalculatorPrompts.java`](src/main/java/com/example/calculator/CalculatorPrompts.java) - MCP prompts +- [`src/main/resources/view.html`](src/main/resources/view.html) - Interactive calculator UI + +## Dependencies + +- **Spring Boot 3.5** - WebFlux reactive web framework +- **MCP Java SDK 0.17.2** (`io.modelcontextprotocol.sdk:mcp-spring-webflux`) - Streamable HTTP transport +- **ext-apps SDK** (CDN) - Client-side MCP Apps protocol in `view.html` + +## Notes + +- This example uses HTTP transport only (Streamable HTTP via WebFlux). Stdio transport is not supported. +- The server uses Netty (via WebFlux) instead of Tomcat for non-blocking request handling. +- CSP metadata is declared on content items in `resources/read` to allow loading the ext-apps SDK from `unpkg.com`. + +## License + +MIT diff --git a/examples/basic-server-java-webflux/mvnw b/examples/basic-server-java-webflux/mvnw new file mode 100755 index 00000000..19529ddf --- /dev/null +++ b/examples/basic-server-java-webflux/mvnw @@ -0,0 +1,259 @@ +#!/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.2 +# +# 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:]' +} + +# 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 <"${0%/*}/.mvn/wrapper/maven-wrapper.properties" +[ -n "${distributionUrl-}" ] || die "cannot read distributionUrl property in ${0%/*}/.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${0##*/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 +printf %s\\n "$distributionUrl" >"$TMP_DOWNLOAD_DIR/$distributionUrlNameMain/mvnw.url" +mv -- "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" "$MAVEN_HOME" || [ -d "$MAVEN_HOME" ] || die "fail to move MAVEN_HOME" + +clean || : +exec_maven "$@" diff --git a/examples/basic-server-java-webflux/mvnw.cmd b/examples/basic-server-java-webflux/mvnw.cmd new file mode 100644 index 00000000..249bdf38 --- /dev/null +++ b/examples/basic-server-java-webflux/mvnw.cmd @@ -0,0 +1,149 @@ +<# : 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.2 +@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) { "/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_HOME_PARENT = "$HOME/.m2/wrapper/dists/$distributionUrlNameMain" +if ($env:MAVEN_USER_HOME) { + $MAVEN_HOME_PARENT = "$env:MAVEN_USER_HOME/wrapper/dists/$distributionUrlNameMain" +} +$MAVEN_HOME_NAME = ([System.Security.Cryptography.MD5]::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 +Rename-Item -Path "$TMP_DOWNLOAD_DIR/$distributionUrlNameMain" -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/examples/basic-server-java-webflux/package.json b/examples/basic-server-java-webflux/package.json new file mode 100644 index 00000000..d615ac20 --- /dev/null +++ b/examples/basic-server-java-webflux/package.json @@ -0,0 +1,13 @@ +{ + "name": "@modelcontextprotocol/server-basic-java-webflux", + "version": "1.0.0", + "private": true, + "scripts": { + "start": "./mvnw -q spring-boot:run", + "dev": "./mvnw -q spring-boot:run", + "build": "./mvnw -q package -DskipTests" + }, + "dependencies": { + "@modelcontextprotocol/ext-apps": "^1.0.0" + } +} diff --git a/examples/basic-server-java-webflux/pom.xml b/examples/basic-server-java-webflux/pom.xml new file mode 100644 index 00000000..d16d7334 --- /dev/null +++ b/examples/basic-server-java-webflux/pom.xml @@ -0,0 +1,54 @@ + + + 4.0.0 + + + org.springframework.boot + spring-boot-starter-parent + 3.5.10 + + + + com.example + basic-server-java-webflux + 1.0.0 + Basic Server - Java WebFlux + Simple calculator MCP server demonstrating Java MCP SDK with interactive UI + + + 17 + 0.17.2 + + + + + org.springframework.boot + spring-boot-starter-webflux + + + org.springframework.boot + spring-boot-starter-actuator + + + io.modelcontextprotocol.sdk + mcp-spring-webflux + ${mcp-sdk.version} + + + org.springframework.boot + spring-boot-starter-test + test + + + + + + + org.springframework.boot + spring-boot-maven-plugin + + + + diff --git a/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorApplication.java b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorApplication.java new file mode 100644 index 00000000..5cbe77d5 --- /dev/null +++ b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorApplication.java @@ -0,0 +1,12 @@ +package com.example.calculator; + +import org.springframework.boot.SpringApplication; +import org.springframework.boot.autoconfigure.SpringBootApplication; + +@SpringBootApplication +public class CalculatorApplication { + + public static void main(String[] args) { + SpringApplication.run(CalculatorApplication.class, args); + } +} diff --git a/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorPrompts.java b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorPrompts.java new file mode 100644 index 00000000..83068d7e --- /dev/null +++ b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorPrompts.java @@ -0,0 +1,103 @@ +package com.example.calculator; + +import io.modelcontextprotocol.server.McpServerFeatures; +import io.modelcontextprotocol.spec.McpSchema; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; + +@Component +public class CalculatorPrompts { + + public McpServerFeatures.SyncPromptSpecification[] specifications() { + return new McpServerFeatures.SyncPromptSpecification[] { + quickCalc(), compareNumbers(), percentage() + }; + } + + private McpServerFeatures.SyncPromptSpecification quickCalc() { + return new McpServerFeatures.SyncPromptSpecification( + new McpSchema.Prompt("quick-calc", "Quick Calculation", + "Evaluate a math expression step by step", + List.of(new McpSchema.PromptArgument("expression", "Expression", + "Math expression to evaluate (e.g., '245 * 18')", true)), + null), + (exchange, request) -> { + String expression = arg(request, "expression", "2 + 2"); + return new McpSchema.GetPromptResult( + "Evaluate a math expression step by step", + List.of( + userMessage("Please calculate: " + expression + + "\n\nUse the calculate tool to evaluate this step by step. " + + "If the expression has multiple operations, break it down and show each step."), + assistantMessage("I'll calculate that for you using the calculator. " + + "Let me break it down step by step.") + ), + null); + } + ); + } + + private McpServerFeatures.SyncPromptSpecification compareNumbers() { + return new McpServerFeatures.SyncPromptSpecification( + new McpSchema.Prompt("compare-numbers", "Compare Numbers", + "Compare two numbers using all four operations", + List.of( + new McpSchema.PromptArgument("a", "First number", "First number", true), + new McpSchema.PromptArgument("b", "Second number", "Second number", true) + ), + null), + (exchange, request) -> { + String a = arg(request, "a", "10"); + String b = arg(request, "b", "3"); + return new McpSchema.GetPromptResult( + "Compare two numbers using all four operations", + List.of( + userMessage("Compare the numbers " + a + " and " + b + + " by computing all four basic operations: addition, subtraction, " + + "multiplication, and division. Use the calculate tool for each " + + "operation and present the results in a clear summary."), + assistantMessage("I'll run all four operations on " + a + " and " + b + + " using the calculator.") + ), + null); + } + ); + } + + private McpServerFeatures.SyncPromptSpecification percentage() { + return new McpServerFeatures.SyncPromptSpecification( + new McpSchema.Prompt("percentage", "Calculate Percentage", + "Calculate what percent one number is of another, or find a percentage of a number", + List.of(new McpSchema.PromptArgument("question", "Question", + "Percentage question (e.g., 'What is 15% of 200?')", true)), + null), + (exchange, request) -> { + String question = arg(request, "question", "What is 15% of 200?"); + return new McpSchema.GetPromptResult( + "Calculate a percentage", + List.of( + userMessage(question + + "\n\nUse the calculate tool with multiply and divide operations " + + "to solve this percentage problem. Show your work step by step.") + ), + null); + } + ); + } + + private static String arg(McpSchema.GetPromptRequest request, String name, String defaultValue) { + if (request.arguments() == null) return defaultValue; + Object value = request.arguments().get(name); + return value != null ? value.toString() : defaultValue; + } + + private static McpSchema.PromptMessage userMessage(String text) { + return new McpSchema.PromptMessage(McpSchema.Role.USER, new McpSchema.TextContent(text)); + } + + private static McpSchema.PromptMessage assistantMessage(String text) { + return new McpSchema.PromptMessage(McpSchema.Role.ASSISTANT, new McpSchema.TextContent(text)); + } +} diff --git a/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorResources.java b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorResources.java new file mode 100644 index 00000000..e01b0ea7 --- /dev/null +++ b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorResources.java @@ -0,0 +1,57 @@ +package com.example.calculator; + +import io.modelcontextprotocol.server.McpServerFeatures; +import io.modelcontextprotocol.spec.McpSchema; +import jakarta.annotation.PostConstruct; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Component; + +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.List; +import java.util.Map; + +@Component +public class CalculatorResources { + + private String viewHtml; + + @PostConstruct + public void init() throws IOException { + ClassPathResource resource = new ClassPathResource("view.html"); + viewHtml = resource.getContentAsString(StandardCharsets.UTF_8); + } + + public McpServerFeatures.SyncResourceSpecification specification() { + Map cspMeta = Map.of( + "ui", Map.of("csp", Map.of("resourceDomains", List.of("https://unpkg.com"))) + ); + + McpSchema.Resource resource = new McpSchema.Resource( + CalculatorTools.VIEW_URI, "view", "Calculator UI", "Calculator interactive UI", + "text/html;profile=mcp-app", null, null, cspMeta + ); + + return new McpServerFeatures.SyncResourceSpecification( + resource, + (exchange, request) -> read() + ); + } + + public McpSchema.ReadResourceResult read() { + // CSP metadata must be on each content item, not the result level. + // See: https://modelcontextprotocol.github.io/ext-apps/docs/patterns#configuring-csp-and-cors + Map cspMeta = Map.of( + "ui", Map.of("csp", Map.of("resourceDomains", List.of("https://unpkg.com"))) + ); + + return new McpSchema.ReadResourceResult( + List.of(new McpSchema.TextResourceContents( + CalculatorTools.VIEW_URI, + "text/html;profile=mcp-app", + viewHtml, + cspMeta + )) + ); + } +} diff --git a/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorTools.java b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorTools.java new file mode 100644 index 00000000..f8aee41e --- /dev/null +++ b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/CalculatorTools.java @@ -0,0 +1,120 @@ +package com.example.calculator; + +import io.modelcontextprotocol.server.McpServerFeatures; +import io.modelcontextprotocol.server.McpSyncServerExchange; +import io.modelcontextprotocol.spec.McpSchema; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; + +@Component +public class CalculatorTools { + + static final String VIEW_URI = "ui://calculator/view.html"; + + public McpServerFeatures.SyncToolSpecification specification() { + return McpServerFeatures.SyncToolSpecification.builder() + .tool(toolDefinition()) + .callHandler(this::handle) + .build(); + } + + private McpSchema.Tool toolDefinition() { + Map uiMeta = Map.of( + "ui", Map.of( + "resourceUri", VIEW_URI, + "visibility", List.of("model", "app") + ), + "ui/resourceUri", VIEW_URI + ); + + McpSchema.JsonSchema inputSchema = new McpSchema.JsonSchema( + "object", + Map.of( + "operation", Map.of( + "type", "string", + "description", "Math operation: add, subtract, multiply, or divide", + "enum", List.of("add", "subtract", "multiply", "divide") + ), + "a", Map.of( + "type", "number", + "description", "First operand" + ), + "b", Map.of( + "type", "number", + "description", "Second operand" + ) + ), + List.of("operation", "a", "b"), + false, null, null + ); + + return new McpSchema.Tool( + "calculate", + "Calculate", + "Perform a math operation on two numbers. Supports add, subtract, multiply, and divide.", + inputSchema, + null, null, uiMeta + ); + } + + McpSchema.CallToolResult handle(McpSyncServerExchange exchange, McpSchema.CallToolRequest request) { + return calculate(request.arguments()); + } + + public McpSchema.CallToolResult calculate(Map arguments) { + String operation = (String) arguments.get("operation"); + double a = ((Number) arguments.get("a")).doubleValue(); + double b = ((Number) arguments.get("b")).doubleValue(); + + double result; + String symbol; + switch (operation) { + case "add" -> { result = a + b; symbol = "+"; } + case "subtract" -> { result = a - b; symbol = "-"; } + case "multiply" -> { result = a * b; symbol = "*"; } + case "divide" -> { + if (b == 0) { + return McpSchema.CallToolResult.builder() + .content(List.of(new McpSchema.TextContent("Error: Division by zero"))) + .isError(true) + .build(); + } + result = a / b; + symbol = "/"; + } + default -> { + return McpSchema.CallToolResult.builder() + .content(List.of(new McpSchema.TextContent("Unknown operation: " + operation))) + .isError(true) + .build(); + } + } + + String formatted = result == Math.floor(result) && !Double.isInfinite(result) + ? String.valueOf((long) result) + : String.valueOf(result); + + String text = String.format("%s %s %s = %s", formatNumber(a), symbol, formatNumber(b), formatted); + + Map structured = Map.of( + "operation", operation, + "a", a, + "b", b, + "result", result, + "expression", text + ); + + return McpSchema.CallToolResult.builder() + .content(List.of(new McpSchema.TextContent(text))) + .meta(Map.of("structuredContent", structured)) + .build(); + } + + private String formatNumber(double n) { + return n == Math.floor(n) && !Double.isInfinite(n) + ? String.valueOf((long) n) + : String.valueOf(n); + } +} diff --git a/examples/basic-server-java-webflux/src/main/java/com/example/calculator/McpConfig.java b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/McpConfig.java new file mode 100644 index 00000000..2a4e9495 --- /dev/null +++ b/examples/basic-server-java-webflux/src/main/java/com/example/calculator/McpConfig.java @@ -0,0 +1,47 @@ +package com.example.calculator; + +import io.modelcontextprotocol.json.jackson.JacksonMcpJsonMapper; +import io.modelcontextprotocol.server.McpServer; +import io.modelcontextprotocol.server.McpSyncServer; +import io.modelcontextprotocol.server.transport.WebFluxStreamableServerTransportProvider; +import io.modelcontextprotocol.spec.McpSchema; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.reactive.function.server.RouterFunction; + +@Configuration +public class McpConfig { + + @Bean + WebFluxStreamableServerTransportProvider mcpTransportProvider(ObjectMapper mapper) { + return WebFluxStreamableServerTransportProvider.builder() + .jsonMapper(new JacksonMcpJsonMapper(mapper)) + .messageEndpoint("/mcp") + .build(); + } + + @Bean + RouterFunction mcpRouterFunction(WebFluxStreamableServerTransportProvider transportProvider) { + return transportProvider.getRouterFunction(); + } + + @Bean + McpSyncServer mcpServer(WebFluxStreamableServerTransportProvider transportProvider, + CalculatorTools tools, + CalculatorResources resources, + CalculatorPrompts prompts) { + return McpServer.sync(transportProvider) + .serverInfo("Calculator", "1.0.0") + .capabilities(McpSchema.ServerCapabilities.builder() + .tools(true) + .resources(false, true) + .prompts(true) + .logging() + .build()) + .tools(tools.specification()) + .resources(resources.specification()) + .prompts(prompts.specifications()) + .build(); + } +} diff --git a/examples/basic-server-java-webflux/src/main/resources/application.yml b/examples/basic-server-java-webflux/src/main/resources/application.yml new file mode 100644 index 00000000..8d6b5cd2 --- /dev/null +++ b/examples/basic-server-java-webflux/src/main/resources/application.yml @@ -0,0 +1,17 @@ +server: + port: ${PORT:3001} + shutdown: graceful + +spring: + lifecycle: + timeout-per-shutdown-phase: 30s + +logging: + level: + com.example.calculator: DEBUG + +management: + endpoints: + web: + exposure: + include: health diff --git a/examples/basic-server-java-webflux/src/main/resources/view.html b/examples/basic-server-java-webflux/src/main/resources/view.html new file mode 100644 index 00000000..bca45a7f --- /dev/null +++ b/examples/basic-server-java-webflux/src/main/resources/view.html @@ -0,0 +1,159 @@ + + + + + + + +
+
+
0
+
+
+ + +
+
+ + + + +
+
Java MCP Server + ext-apps SDK
+ + + + diff --git a/examples/basic-server-java-webflux/src/test/java/com/example/calculator/CalculatorResourcesTest.java b/examples/basic-server-java-webflux/src/test/java/com/example/calculator/CalculatorResourcesTest.java new file mode 100644 index 00000000..11cf3c02 --- /dev/null +++ b/examples/basic-server-java-webflux/src/test/java/com/example/calculator/CalculatorResourcesTest.java @@ -0,0 +1,54 @@ +package com.example.calculator; + +import io.modelcontextprotocol.spec.McpSchema; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class CalculatorResourcesTest { + + private CalculatorResources resources; + + @BeforeEach + void setUp() throws IOException { + resources = new CalculatorResources(); + resources.init(); + } + + @Test + void readReturnsHtmlContent() { + McpSchema.ReadResourceResult result = resources.read(); + + assertNotNull(result.contents()); + assertEquals(1, result.contents().size()); + + McpSchema.TextResourceContents contents = (McpSchema.TextResourceContents) result.contents().get(0); + assertEquals(CalculatorTools.VIEW_URI, contents.uri()); + assertEquals("text/html;profile=mcp-app", contents.mimeType()); + assertTrue(contents.text().contains(""), "Should contain HTML content"); + + // CSP metadata must be on content items, not result level + assertNotNull(contents.meta(), "Content item should have _meta with CSP"); + @SuppressWarnings("unchecked") + Map ui = (Map) contents.meta().get("ui"); + assertNotNull(ui, "Content _meta should have ui key"); + @SuppressWarnings("unchecked") + Map csp = (Map) ui.get("csp"); + assertNotNull(csp, "Content _meta.ui should have csp key"); + assertNotNull(csp.get("resourceDomains"), "CSP should have resourceDomains"); + } + + @Test + void specificationReturnsValidResourceSpec() { + var spec = resources.specification(); + + assertNotNull(spec); + assertEquals(CalculatorTools.VIEW_URI, spec.resource().uri()); + assertEquals("Calculator interactive UI", spec.resource().description()); + assertEquals("text/html;profile=mcp-app", spec.resource().mimeType()); + } +} diff --git a/examples/basic-server-java-webflux/src/test/java/com/example/calculator/CalculatorToolsTest.java b/examples/basic-server-java-webflux/src/test/java/com/example/calculator/CalculatorToolsTest.java new file mode 100644 index 00000000..6c13fb02 --- /dev/null +++ b/examples/basic-server-java-webflux/src/test/java/com/example/calculator/CalculatorToolsTest.java @@ -0,0 +1,216 @@ +package com.example.calculator; + +import io.modelcontextprotocol.spec.McpSchema; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.*; + +class CalculatorToolsTest { + + private CalculatorTools tools; + + @BeforeEach + void setUp() { + tools = new CalculatorTools(); + } + + // --- Addition tests --- + + @Test + void addTwoPositiveIntegers() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "add", "a", 5, "b", 3)); + + assertFalse(isError(result)); + assertEquals("5 + 3 = 8", getText(result)); + assertEquals(8.0, getStructuredResult(result)); + } + + @Test + void addDecimalNumbers() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "add", "a", 1.5, "b", 2.3)); + + assertFalse(isError(result)); + assertEquals("1.5 + 2.3 = 3.8", getText(result)); + assertEquals(3.8, getStructuredResult(result)); + } + + @Test + void addNegativeNumbers() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "add", "a", -5, "b", -3)); + + assertFalse(isError(result)); + assertEquals("-5 + -3 = -8", getText(result)); + assertEquals(-8.0, getStructuredResult(result)); + } + + // --- Subtraction tests --- + + @Test + void subtractTwoNumbers() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "subtract", "a", 10, "b", 4)); + + assertFalse(isError(result)); + assertEquals("10 - 4 = 6", getText(result)); + assertEquals(6.0, getStructuredResult(result)); + } + + @Test + void subtractResultingInNegative() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "subtract", "a", 3, "b", 7)); + + assertFalse(isError(result)); + assertEquals("3 - 7 = -4", getText(result)); + assertEquals(-4.0, getStructuredResult(result)); + } + + // --- Multiplication tests --- + + @Test + void multiplyTwoNumbers() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "multiply", "a", 6, "b", 7)); + + assertFalse(isError(result)); + assertEquals("6 * 7 = 42", getText(result)); + assertEquals(42.0, getStructuredResult(result)); + } + + @Test + void multiplyByZero() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "multiply", "a", 99, "b", 0)); + + assertFalse(isError(result)); + assertEquals("99 * 0 = 0", getText(result)); + assertEquals(0.0, getStructuredResult(result)); + } + + // --- Division tests --- + + @Test + void divideTwoNumbers() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "divide", "a", 10, "b", 4)); + + assertFalse(isError(result)); + assertEquals("10 / 4 = 2.5", getText(result)); + assertEquals(2.5, getStructuredResult(result)); + } + + @Test + void divideEvenly() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "divide", "a", 12, "b", 3)); + + assertFalse(isError(result)); + assertEquals("12 / 3 = 4", getText(result)); + assertEquals(4.0, getStructuredResult(result)); + } + + @Test + void divideByZeroReturnsError() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "divide", "a", 10, "b", 0)); + + assertTrue(isError(result)); + assertEquals("Error: Division by zero", getText(result)); + assertNull(result.meta(), "Division by zero should not have structuredContent"); + } + + // --- Unknown operation test --- + + @Test + void unknownOperationReturnsError() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "modulo", "a", 10, "b", 3)); + + assertTrue(isError(result)); + assertEquals("Unknown operation: modulo", getText(result)); + assertNull(result.meta(), "Unknown operation should not have structuredContent"); + } + + // --- Number formatting tests --- + + @Test + void wholeNumbersDisplayWithoutDecimals() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "add", "a", 2.0, "b", 3.0)); + + assertEquals("2 + 3 = 5", getText(result)); + } + + @Test + void decimalNumbersKeepPrecision() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "add", "a", 1.1, "b", 2.2)); + + String text = getText(result); + assertTrue(text.startsWith("1.1 + 2.2 = "), "Expression should show decimal operands: " + text); + // 1.1 + 2.2 = 3.3000000000000003 (floating point) + assertTrue(text.contains("3.3"), "Result should contain 3.3: " + text); + } + + @Test + void mixedWholeAndDecimalFormatting() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "multiply", "a", 2.5, "b", 4)); + + assertEquals("2.5 * 4 = 10", getText(result)); + } + + // --- structuredContent metadata tests --- + + @Test + void successfulCallIncludesStructuredContent() { + McpSchema.CallToolResult result = tools.calculate( + Map.of("operation", "add", "a", 1, "b", 2)); + + assertNotNull(result.meta()); + @SuppressWarnings("unchecked") + Map structured = (Map) result.meta().get("structuredContent"); + assertNotNull(structured); + assertEquals("add", structured.get("operation")); + assertEquals(1.0, structured.get("a")); + assertEquals(2.0, structured.get("b")); + assertEquals(3.0, structured.get("result")); + assertEquals("1 + 2 = 3", structured.get("expression")); + } + + // --- Tool specification tests --- + + @Test + void specificationReturnsValidToolSpec() { + var spec = tools.specification(); + + assertNotNull(spec); + assertEquals("calculate", spec.tool().name()); + assertEquals("Calculate", spec.tool().title()); + assertNotNull(spec.tool().description()); + assertNotNull(spec.tool().inputSchema()); + assertNotNull(spec.tool().meta()); + } + + // --- Helper methods --- + + private String getText(McpSchema.CallToolResult result) { + return ((McpSchema.TextContent) result.content().get(0)).text(); + } + + private boolean isError(McpSchema.CallToolResult result) { + return result.isError() != null && result.isError(); + } + + private double getStructuredResult(McpSchema.CallToolResult result) { + @SuppressWarnings("unchecked") + Map structured = (Map) result.meta().get("structuredContent"); + return (double) structured.get("result"); + } +}