diff --git a/.github/FUNDING.yml b/.github/FUNDING.yml new file mode 100644 index 0000000..a2edaa0 --- /dev/null +++ b/.github/FUNDING.yml @@ -0,0 +1,3 @@ +# These are supported funding model platforms + +github: xemantic diff --git a/.github/scripts/update-readme-version.sh b/.github/scripts/update-readme-version.sh new file mode 100755 index 0000000..9f6518a --- /dev/null +++ b/.github/scripts/update-readme-version.sh @@ -0,0 +1,74 @@ +#!/bin/bash + +# +# Copyright 2025 Kazimierz Pogoda / Xemantic +# +# 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. +# + +# Ensure VERSION environment variable is set +if [ -z "$VERSION" ]; then + echo "Error: VERSION environment variable is not set" + exit 1 +fi + +# Check if settings.gradle.kts exists +if [ ! -f "settings.gradle.kts" ]; then + echo "Error: settings.gradle.kts not found" + exit 1 +fi + +# Extract groupId and name from settings.gradle.kts +GROUP_ID=$(grep "val groupId = " settings.gradle.kts | sed -n 's/.*groupId = "\(.*\)".*/\1/p') +ARTIFACT_ID=$(grep "val name = " settings.gradle.kts | sed -n 's/.*name = "\(.*\)".*/\1/p') + +if [ -z "$GROUP_ID" ] || [ -z "$ARTIFACT_ID" ]; then + echo "Error: Could not extract groupId or name from settings.gradle.kts" + exit 1 +fi + +# Check if README.md exists +if [ ! -f "README.md" ]; then + echo "Error: README.md not found" + exit 1 +fi + +# Escape special characters in the group ID for sed +ESCAPED_GROUP_ID=$(echo "$GROUP_ID" | sed 's/\./\\./g') + +# Create the pattern to match +PATTERN="\"$ESCAPED_GROUP_ID:$ARTIFACT_ID:[0-9]+(\.[0-9]+){0,2}\"" + +# Create the replacement string +REPLACEMENT="\"$GROUP_ID:$ARTIFACT_ID:$VERSION\"" + +# Check if the pattern exists in the file +if ! grep -Eq "$GROUP_ID:$ARTIFACT_ID:[0-9]+(\.[0-9]+){0,2}" README.md; then + echo "Error: Dependency pattern not found in README.md" + exit 1 +fi + +# Perform the replacement and save to a temporary file +sed -E "s|$PATTERN|$REPLACEMENT|g" README.md > README.md.tmp + +# Check if sed made any changes +if cmp -s README.md README.md.tmp; then + echo "No version updates were needed" + rm README.md.tmp + exit 0 +fi + +# Move the temporary file back to the original +mv README.md.tmp README.md + +echo "Successfully updated version to $VERSION in README.md" diff --git a/.github/workflows/build-branch.yml b/.github/workflows/build-branch.yml new file mode 100644 index 0000000..bd6d430 --- /dev/null +++ b/.github/workflows/build-branch.yml @@ -0,0 +1,27 @@ +name: Build branch +on: + push: + branches-ignore: + - main + pull_request: + branches-ignore: + - main + +jobs: + build_branch: + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v4.2.2 + + - name: Setup Java + uses: actions/setup-java@v4.6.0 + with: + distribution: 'temurin' + java-version: 23 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4.2.2 + + - name: Build + run: ./gradlew build diff --git a/.github/workflows/build-main.yml b/.github/workflows/build-main.yml new file mode 100644 index 0000000..c9d6605 --- /dev/null +++ b/.github/workflows/build-main.yml @@ -0,0 +1,26 @@ +name: Build main +on: + push: + branches: + - main +jobs: + build_main: + runs-on: ubuntu-latest + steps: + - name: Checkout sources + uses: actions/checkout@v4.2.2 + + - name: Setup Java + uses: actions/setup-java@v4.6.0 + with: + distribution: 'temurin' + java-version: 23 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4.2.2 + + - name: Build + run: ./gradlew build sourcesJar dokkaGeneratePublicationHtml publish + env: + ORG_GRADLE_PROJECT_githubActor: ${{ secrets.GITHUBACTOR }} + ORG_GRADLE_PROJECT_githubToken: ${{ secrets.GITHUBTOKEN }} diff --git a/.github/workflows/build-release.yml b/.github/workflows/build-release.yml new file mode 100644 index 0000000..c7389ab --- /dev/null +++ b/.github/workflows/build-release.yml @@ -0,0 +1,58 @@ +name: Build release +on: + release: + types: [ published ] +jobs: + build_release: + runs-on: ubuntu-latest + permissions: + # Give the default GITHUB_TOKEN write permission to commit and push the + # added or changed files to the repository. + contents: write + steps: + - name: Write release version + run: | + VERSION=${GITHUB_REF_NAME#v} + echo Version: $VERSION + echo "VERSION=$VERSION" >> $GITHUB_ENV + + - name: Checkout sources + uses: actions/checkout@v4.2.2 + with: + ref: ${{ github.head_ref }} + fetch-depth: 0 + + - name: Setup Java + uses: actions/setup-java@v4.6.0 + with: + distribution: 'temurin' + java-version: 23 + + - name: Setup Gradle + uses: gradle/actions/setup-gradle@v4.2.2 + + - name: Build + env: + ORG_GRADLE_PROJECT_githubActor: ${{ secrets.GITHUBACTOR }} + ORG_GRADLE_PROJECT_githubToken: ${{ secrets.GITHUBTOKEN }} + ORG_GRADLE_PROJECT_signingKey: ${{ secrets.SIGNING_KEY }} + ORG_GRADLE_PROJECT_signingPassword: ${{ secrets.SIGNING_PASSWORD }} + ORG_GRADLE_PROJECT_sonatypeUser: ${{ secrets.SONATYPE_USER }} + ORG_GRADLE_PROJECT_sonatypePassword: ${{ secrets.SONATYPE_PASSWORD }} + ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }} + run: ./gradlew -Pversion=$VERSION build sourcesJar dokkaGeneratePublicationHtml publishToSonatype closeAndReleaseSonatypeStagingRepository + + - name: Checkout main branch + uses: actions/checkout@v4.2.2 + with: + ref: main + fetch-depth: 0 + + - name: Update README + run: sh .github/scripts/update-readme-version.sh + + - name: Create Pull Request + uses: stefanzweifel/git-auto-commit-action@v5.0.1 + with: + commit_message: Dependency version in README.md updated to ${{ env.VERSION }} + file_pattern: 'README.md' diff --git a/.github/workflows/updater.yml b/.github/workflows/updater.yml new file mode 100644 index 0000000..a1e6a9f --- /dev/null +++ b/.github/workflows/updater.yml @@ -0,0 +1,24 @@ +name: GitHub Actions Version Updater + +# Controls when the action will run. +on: + schedule: + # Automatically run on every Sunday + - cron: '0 0 * * 0' + +jobs: + build: + runs-on: ubuntu-latest + + steps: + - name: Git checkout + uses: actions/checkout@v4.2.2 + with: + # [Required] Access token with `workflow` scope. + token: ${{ secrets.WORKFLOW_SECRET }} + + - name: Run GitHub Actions Version Updater + uses: saadmk11/github-actions-version-updater@v0.8.1 + with: + # [Required] Access token with `workflow` scope. + token: ${{ secrets.WORKFLOW_SECRET }} diff --git a/.gitignore b/.gitignore index a5b1113..2e6fa73 100644 --- a/.gitignore +++ b/.gitignore @@ -1,21 +1,45 @@ .gradle -**/build/ -!src/**/build/ +build/ +!gradle/wrapper/gradle-wrapper.jar +!**/src/main/**/build/ +!**/src/test/**/build/ -# Ignore Gradle GUI config -gradle-app.setting +### IntelliJ IDEA ### +/.idea/ +!/.idea/copyright/ +*.iws +*.iml +*.ipr +out/ +!**/src/main/**/out/ +!**/src/test/**/out/ -# Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) -!gradle-wrapper.jar +### Kotlin ### +.kotlin -# Avoid ignore Gradle wrappper properties -!gradle-wrapper.properties +### Eclipse ### +.apt_generated +.classpath +.factorypath +.project +.settings +.springBeans +.sts4-cache +bin/ +!**/src/main/**/bin/ +!**/src/test/**/bin/ -# Cache of project -.gradletasknamecache +### NetBeans ### +/nbproject/private/ +/nbbuild/ +/dist/ +/nbdist/ +/.nb-gradle/ -# Eclipse Gradle plugin generated files -# Eclipse Core -.project -# JDT-specific (Eclipse Java Development Tools) -.classpath +### VS Code ### +.vscode/ + +### Mac OS ### +.DS_Store + +/*.hprof diff --git a/README.md b/README.md index d6287fc..9414b6e 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,63 @@ # xemantic-ai-tool-schema-mdc -An adapter from xemantic-ai-tool-schema to Model Context Protocol kotlin-sdk +Adapting [xemantic-ai-tool-schema](https://github.com/xemantic/xemantic-ai-tool-schema) to Model Context Protocol kotlin-sdk Tool input. + +[Maven Central Version](https://central.sonatype.com/namespace/com.xemantic.ai) +[GitHub Release Date](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/releases) +[license](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/blob/main/LICENSE) + +[GitHub Actions Workflow Status](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/actions/workflows/build-main.yml) +[GitHub branch check runs](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/actions/workflows/build-main.yml) +[GitHub commits since latest release](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/commits/main/) +[GitHub last commit](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/commits/main/) + +[GitHub contributors](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/graphs/contributors) +[GitHub commit activity](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/commits/main/) +[GitHub code size in bytes]() +[GitHub Created At](https://github.com/xemantic/xemantic-ai-tool-schema-mdc/commit/39c1fa4c138d4c671868c973e2ad37b262ae03c2) +[kotlin version](https://kotlinlang.org/docs/releases.html) + +[discord server](https://discord.gg/vQktqqN2Vn) +[discord users online](https://discord.gg/vQktqqN2Vn) +[X (formerly Twitter) Follow](https://x.com/KazikPogoda) + +## Why? + +The [kotlin-sdk](https://github.com/modelcontextprotocol/kotlin-sdk) variant of the [Model Context Protocol](https://modelcontextprotocol.io/) is expressing [JSON Schema](https://json-schema.org/) as `Tool.Input` class, which offers limited flexibility comparing +to [JsonSchema](https://github.com/xemantic/xemantic-ai-tool-schema/blob/main/src/commonMain/kotlin/JsonSchema.kt) delivered by the [xemantic-ai-tool-schema](https://github.com/xemantic/xemantic-ai-tool-schema) project. +In particular `definitions` of types cannot be expressed. +I hope `kotlin-sdk` will embrace something more versatile soon. Meanwhile, this adapter library can be used for automatic MDC-compatible JSON Schema generation out of serializable Kotlin classes. + +## Usage + +### Setting up Gradle + +In your `build.gradle.kts`: + +```kotlin +dependencies { + implementation("com.xemantic.ai:xemantic-ai-tool-schema-mdc:0.1") +} +``` + +### + +Getting `Tool.Input` instance: + +```kotlin +@Serializable +data class Foo( + val bar: String +) + +// ... + +val inputSchema: Tool.Input = mdcToolInput() +``` + +## Development + +Clone this project, and then run: + +```shell +./gradlew build +``` diff --git a/build.gradle.kts b/build.gradle.kts new file mode 100644 index 0000000..f37a107 --- /dev/null +++ b/build.gradle.kts @@ -0,0 +1,280 @@ +@file:OptIn(ExperimentalWasmDsl::class, ExperimentalKotlinGradlePluginApi::class) + +import org.jetbrains.kotlin.gradle.ExperimentalKotlinGradlePluginApi +import org.jetbrains.kotlin.gradle.ExperimentalWasmDsl +import org.jetbrains.kotlin.gradle.dsl.JvmTarget +import org.jetbrains.kotlin.gradle.dsl.KotlinVersion + +plugins { + alias(libs.plugins.kotlin.multiplatform) + alias(libs.plugins.kotlin.plugin.serialization) + alias(libs.plugins.kotlin.plugin.power.assert) + alias(libs.plugins.kotlinx.binary.compatibility.validator) + alias(libs.plugins.dokka) + alias(libs.plugins.versions) + `maven-publish` + signing + alias(libs.plugins.publish) +} + +val githubAccount = "xemantic" + +val javaTarget = libs.versions.javaTarget.get() +val kotlinTarget = KotlinVersion.fromVersion(libs.versions.kotlinTarget.get()) + +val isReleaseBuild = !project.version.toString().endsWith("-SNAPSHOT") +val githubActor: String? by project +val githubToken: String? by project +val signingKey: String? by project +val signingPassword: String? by project +val sonatypeUser: String? by project +val sonatypePassword: String? by project + +println( +""" ++-------------------------------------------- +| Project: ${project.name} +| Version: ${project.version} +| Release build: $isReleaseBuild ++-------------------------------------------- +""" +) + +repositories { + mavenCentral() +} + +kotlin { + + explicitApi() + + compilerOptions { + apiVersion = kotlinTarget + languageVersion = kotlinTarget + freeCompilerArgs.add("-Xmulti-dollar-interpolation") + extraWarnings.set(true) + progressiveMode = true + } + + jvm { + // set up according to https://jakewharton.com/gradle-toolchains-are-rarely-a-good-idea/ + compilerOptions { + apiVersion = kotlinTarget + languageVersion = kotlinTarget + jvmTarget = JvmTarget.fromTarget(javaTarget) + freeCompilerArgs.add("-Xjdk-release=$javaTarget") + progressiveMode = true + } + } + +// js { +// browser() +// nodejs() +// binaries.library() +// } +// +// wasmJs { +// browser() +// nodejs() +// //d8() +// binaries.library() +// } +// +// wasmWasi { +// nodejs() +// binaries.library() +// } +// +// // native, see https://kotlinlang.org/docs/native-target-support.html +// // tier 1 +// macosX64() +// macosArm64() +// iosSimulatorArm64() +// iosX64() +// iosArm64() +// +// // tier 2 +// linuxX64() +// linuxArm64() +// watchosSimulatorArm64() +// watchosX64() +// watchosArm32() +// watchosArm64() +// tvosSimulatorArm64() +// tvosX64() +// tvosArm64() +// +// // tier 3 +// androidNativeArm32() +// androidNativeArm64() +// androidNativeX86() +// androidNativeX64() +// mingwX64() +// watchosDeviceArm64() +// +// @OptIn(ExperimentalSwiftExportDsl::class) +// swiftExport {} + + sourceSets { + + commonMain { + dependencies { + api(libs.mdc.kotlin.sdk) + api(libs.xemantic.ai.tool.schema) + } + } + + commonTest { + dependencies { + implementation(libs.kotlin.test) + implementation(libs.xemantic.kotlin.test) + } + } + + } + +} + +//// skip tests which require XCode components to be installed +//tasks.named("tvosSimulatorArm64Test") { enabled = false } +//tasks.named("watchosSimulatorArm64Test") { enabled = false } +//// skip tests for which system environment variable retrival is not implemented at the moment +//tasks.named("wasmWasiNodeTest") { enabled = false } +//// skip tests which for some reason stale +//tasks.named("wasmJsBrowserTest") { enabled = false } +// +//tasks.withType { +// testLogging { +// events( +// TestLogEvent.SKIPPED, +// TestLogEvent.FAILED +// ) +// showStackTraces = true +// exceptionFormat = TestExceptionFormat.FULL +// } +//} + +powerAssert { + functions = listOf( + "com.xemantic.kotlin.test.assert", + "com.xemantic.kotlin.test.have" + ) +} + +// https://kotlinlang.org/docs/dokka-migration.html#adjust-configuration-options +dokka { + pluginsConfiguration.html { + footerMessage.set("(c) 2025 Xemantic") + } +} + +val javadocJar by tasks.registering(Jar::class) { + archiveClassifier.set("javadoc") + from(tasks.dokkaGeneratePublicationHtml) +} + +publishing { + repositories { + if (!isReleaseBuild) { + maven { + name = "GitHubPackages" + setUrl("https://maven.pkg.github.com/$githubAccount/${rootProject.name}") + credentials { + username = githubActor + password = githubToken + } + } + } + } + publications { + withType { + artifact(javadocJar) + pom { + name = "xemantic-ai-tool-schema-mdc" + description = "Adapting xemantic-ai-tool-schema to Model Context Protocol kotlin-sdk Tool input" + url = "https://github.com/$githubAccount/${rootProject.name}" + inceptionYear = "2025" + organization { + name = "Xemantic" + url = "https://xemantic.com" + } + licenses { + license { + name = "The Apache Software License, Version 2.0" + url = "http://www.apache.org/licenses/LICENSE-2.0.txt" + distribution = "repo" + } + } + scm { + url = "https://github.com/$githubAccount/${rootProject.name}" + connection = "scm:git:git:github.com/$githubAccount/${rootProject.name}.git" + developerConnection = "scm:git:https://github.com/$githubAccount/${rootProject.name}.git" + } + ciManagement { + system = "GitHub" + url = "https://github.com/$githubAccount/${rootProject.name}/actions" + } + issueManagement { + system = "GitHub" + url = "https://github.com/$githubAccount/${rootProject.name}/issues" + } + developers { + developer { + id = "morisil" + name = "Kazik Pogoda" + email = "morisil@xemantic.com" + } + } + } + } + } +} + +if (isReleaseBuild) { + + // workaround for KMP/gradle signing issue + // https://github.com/gradle/gradle/issues/26091 + tasks { + withType { + dependsOn(withType()) + } + } + + // Resolves issues with .asc task output of the sign task of native targets. + // See: https://github.com/gradle/gradle/issues/26132 + // And: https://youtrack.jetbrains.com/issue/KT-46466 + tasks.withType().configureEach { + val pubName = name.removePrefix("sign").removeSuffix("Publication") + + // These tasks only exist for native targets, hence findByName() to avoid trying to find them for other targets + + // Task ':linkDebugTest' uses this output of task ':signPublication' without declaring an explicit or implicit dependency + tasks.findByName("linkDebugTest$pubName")?.let { + mustRunAfter(it) + } + // Task ':compileTestKotlin' uses this output of task ':signPublication' without declaring an explicit or implicit dependency + tasks.findByName("compileTestKotlin$pubName")?.let { + mustRunAfter(it) + } + } + + signing { + useInMemoryPgpKeys( + signingKey, + signingPassword + ) + sign(publishing.publications) + } + + nexusPublishing { + repositories { + sonatype { //only for users registered in Sonatype after 24 Feb 2021 + nexusUrl.set(uri("https://s01.oss.sonatype.org/service/local/")) + snapshotRepositoryUrl.set(uri("https://s01.oss.sonatype.org/content/repositories/snapshots/")) + username.set(sonatypeUser) + password.set(sonatypePassword) + } + } + } + +} diff --git a/gradle.properties b/gradle.properties new file mode 100644 index 0000000..859f4fa --- /dev/null +++ b/gradle.properties @@ -0,0 +1,9 @@ +kotlin.code.style=official +kotlin.js.generate.executable.default=false +kotlin.apple.xcodeCompatibility.nowarn=true +kotlin.experimental.swift-export.enabled=true +kotlin.native.enableKlibsCrossCompilation=true +kotlin.incremental.wasm=true +org.jetbrains.dokka.experimental.gradle.pluginMode=V2Enabled +org.jetbrains.dokka.experimental.gradle.pluginMode.noWarn=true +version=0.1-SNAPSHOT diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml new file mode 100644 index 0000000..87688df --- /dev/null +++ b/gradle/libs.versions.toml @@ -0,0 +1,30 @@ +[versions] +kotlinTarget = "2.1" +javaTarget = "17" + +kotlin = "2.1.0" +modelContextProtocol = "0.3.0" +xemanticAiToolSchema = "0.1.4" +xemanticKotlinTest = "1.1" + +versionsPlugin = "0.51.0" +dokkaPlugin = "2.0.0" +publishPlugin = "2.0.0" + +binaryCompatibilityValidatorPlugin = "0.17.0" + +[libraries] +kotlin-test = { module = "org.jetbrains.kotlin:kotlin-test", version.ref = "kotlin" } +mdc-kotlin-sdk = { module = "io.modelcontextprotocol:kotlin-sdk", version.ref = "modelContextProtocol" } +xemantic-ai-tool-schema = { module = "com.xemantic.ai:xemantic-ai-tool-schema", version.ref = "xemanticAiToolSchema" } + +xemantic-kotlin-test = { module="com.xemantic.kotlin:xemantic-kotlin-test", version.ref="xemanticKotlinTest" } + +[plugins] +kotlin-multiplatform = { id = "org.jetbrains.kotlin.multiplatform", version.ref = "kotlin" } +kotlin-plugin-serialization = { id = "org.jetbrains.kotlin.plugin.serialization", version.ref = "kotlin" } +kotlin-plugin-power-assert = { id = "org.jetbrains.kotlin.plugin.power-assert", version.ref = "kotlin" } +dokka = { id = "org.jetbrains.dokka", version.ref = "dokkaPlugin" } +versions = { id = "com.github.ben-manes.versions", version.ref = "versionsPlugin" } +publish = { id = "io.github.gradle-nexus.publish-plugin", version.ref = "publishPlugin" } +kotlinx-binary-compatibility-validator = { id = "org.jetbrains.kotlinx.binary-compatibility-validator", version.ref = "binaryCompatibilityValidatorPlugin" } diff --git a/gradle/wrapper/gradle-wrapper.jar b/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 0000000..a4b76b9 Binary files /dev/null and b/gradle/wrapper/gradle-wrapper.jar differ diff --git a/gradle/wrapper/gradle-wrapper.properties b/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 0000000..cea7a79 --- /dev/null +++ b/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.12-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..21cee6a --- /dev/null +++ b/gradlew @@ -0,0 +1,250 @@ +#!/bin/sh + +# +# Copyright 2024 Kazimierz Pogoda / Xemantic +# +# 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. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s +' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +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 + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9d21a21 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/settings.gradle.kts b/settings.gradle.kts new file mode 100644 index 0000000..eaab50c --- /dev/null +++ b/settings.gradle.kts @@ -0,0 +1,7 @@ +val groupId = "com.xemantic.ai" +val name = "xemantic-ai-tool-schema-mdc" + +rootProject.name = name +gradle.beforeProject { + group = groupId +} diff --git a/src/commonMain/kotlin/ObjectSchemaToMdcToolInput.kt b/src/commonMain/kotlin/ObjectSchemaToMdcToolInput.kt new file mode 100644 index 0000000..74ee4cd --- /dev/null +++ b/src/commonMain/kotlin/ObjectSchemaToMdcToolInput.kt @@ -0,0 +1,39 @@ +/* + * Copyright 2025 Kazimierz Pogoda / Xemantic + * + * 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 com.xemantic.ai.tool.schema.mdc + +import com.xemantic.ai.tool.schema.ObjectSchema +import com.xemantic.ai.tool.schema.generator.jsonSchemaOf +import io.modelcontextprotocol.kotlin.sdk.Tool.Input +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.encodeToJsonElement +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive + +public fun ObjectSchema.toMdcToolInput(): Input = + Json.encodeToJsonElement(this).jsonObject.run { + Input( + properties = get("properties")!!.jsonObject, + required = get("required")?.jsonArray?.map { + it.jsonPrimitive.content + } + ) + } + +public inline fun Any.mdcToolInput(): Input = + (jsonSchemaOf() as ObjectSchema).toMdcToolInput() diff --git a/src/commonTest/kotlin/ObjectSchemaToMdcToolInputTest.kt b/src/commonTest/kotlin/ObjectSchemaToMdcToolInputTest.kt new file mode 100644 index 0000000..5350130 --- /dev/null +++ b/src/commonTest/kotlin/ObjectSchemaToMdcToolInputTest.kt @@ -0,0 +1,54 @@ +/* + * Copyright 2025 Kazimierz Pogoda / Xemantic + * + * 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 com.xemantic.ai.tool.schema.mdc + +import com.xemantic.kotlin.test.be +import com.xemantic.kotlin.test.have +import com.xemantic.kotlin.test.should +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlin.test.Test + +class ObjectSchemaToMdcToolInputTest { + + @Serializable + private data class Foo( + val bar: String + ) + + @Test + fun `Should convert class to MDC Tool Input`() { + val input = mdcToolInput() + println(input) + input should { + properties should { + have(size == 1) + this["bar"] should { + be() + have(size == 1) + this["type"] should { + be() + have(content == "string") + } + } + } + have(required == listOf("bar")) + } + } + +}