Commit e80c2ba8 by jimchenqj

feat: 初始化项目结构和基础功能

添加项目基础结构包括.gitignore、.gitattributes配置
实现MCP客户端和服务端基础框架
添加LLM工具接口和模型请求/响应类
配置MySQL数据库连接和工具类
实现天气服务和通用服务功能
添加测试类和示例客户端代码
配置Spring Boot应用属性和依赖
0 parents
Showing 65 changed files with 3097 additions and 0 deletions
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.codeverse.userSettings.MarscodeWorkspaceAppSettingsState">
<option name="ckgOperationStatus" value="SUCCESS" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<component name="ProjectCodeStyleConfiguration">
<code_scheme name="Project" version="173">
<ScalaCodeStyleSettings>
<option name="MULTILINE_STRING_CLOSING_QUOTES_ON_NEW_LINE" value="true" />
</ScalaCodeStyleSettings>
</code_scheme>
</component>
\ No newline at end of file \ No newline at end of file
<component name="ProjectCodeStyleConfiguration">
<state>
<option name="PREFERRED_PROJECT_CODE_STYLE" value="Default" />
</state>
</component>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CompilerConfiguration">
<annotationProcessing>
<profile default="true" name="Default" enabled="true" />
<profile name="Maven default annotation processors profile" enabled="true">
<sourceOutputDir name="target/generated-sources/annotations" />
<sourceTestOutputDir name="target/generated-test-sources/test-annotations" />
<outputRelativeToContentRoot value="true" />
<module name="glsk-mcp-server" />
<module name="glsk-mcp-client" />
</profile>
</annotationProcessing>
</component>
<component name="JavacSettings">
<option name="ADDITIONAL_OPTIONS_OVERRIDE">
<module name="glsk-mcp-client" options="-parameters" />
<module name="glsk-mcp-server" options="-parameters" />
</option>
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/glsk-mcp-client/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/glsk-mcp-client/src/main/resources" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/glsk-mcp-server/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/glsk-mcp-server/src/main/resources" charset="UTF-8" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="RemoteRepositoriesConfiguration">
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Central Repository" />
<option name="url" value="https://repo.maven.apache.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="central" />
<option name="name" value="Maven Central repository" />
<option name="url" value="https://repo1.maven.org/maven2" />
</remote-repository>
<remote-repository>
<option name="id" value="jboss.community" />
<option name="name" value="JBoss Community repository" />
<option name="url" value="https://repository.jboss.org/nexus/content/repositories/public/" />
</remote-repository>
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/glsk-mcp-client/pom.xml" />
<option value="$PROJECT_DIR$/glsk-mcp-server/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="azul-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/glsk-mcp.iml" filepath="$PROJECT_DIR$/.idea/glsk-mcp.iml" />
</modules>
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Palette2">
<group name="Swing">
<item class="com.intellij.uiDesigner.HSpacer" tooltip-text="Horizontal Spacer" icon="/com/intellij/uiDesigner/icons/hspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="1" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="com.intellij.uiDesigner.VSpacer" tooltip-text="Vertical Spacer" icon="/com/intellij/uiDesigner/icons/vspacer.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="1" anchor="0" fill="2" />
</item>
<item class="javax.swing.JPanel" icon="/com/intellij/uiDesigner/icons/panel.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3" />
</item>
<item class="javax.swing.JScrollPane" icon="/com/intellij/uiDesigner/icons/scrollPane.svg" removable="false" auto-create-binding="false" can-attach-label="true">
<default-constraints vsize-policy="7" hsize-policy="7" anchor="0" fill="3" />
</item>
<item class="javax.swing.JButton" icon="/com/intellij/uiDesigner/icons/button.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="0" fill="1" />
<initial-values>
<property name="text" value="Button" />
</initial-values>
</item>
<item class="javax.swing.JRadioButton" icon="/com/intellij/uiDesigner/icons/radioButton.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="RadioButton" />
</initial-values>
</item>
<item class="javax.swing.JCheckBox" icon="/com/intellij/uiDesigner/icons/checkBox.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="3" anchor="8" fill="0" />
<initial-values>
<property name="text" value="CheckBox" />
</initial-values>
</item>
<item class="javax.swing.JLabel" icon="/com/intellij/uiDesigner/icons/label.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="8" fill="0" />
<initial-values>
<property name="text" value="Label" />
</initial-values>
</item>
<item class="javax.swing.JTextField" icon="/com/intellij/uiDesigner/icons/textField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JPasswordField" icon="/com/intellij/uiDesigner/icons/passwordField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JFormattedTextField" icon="/com/intellij/uiDesigner/icons/formattedTextField.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1">
<preferred-size width="150" height="-1" />
</default-constraints>
</item>
<item class="javax.swing.JTextArea" icon="/com/intellij/uiDesigner/icons/textArea.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTextPane" icon="/com/intellij/uiDesigner/icons/textPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JEditorPane" icon="/com/intellij/uiDesigner/icons/editorPane.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JComboBox" icon="/com/intellij/uiDesigner/icons/comboBox.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="2" anchor="8" fill="1" />
</item>
<item class="javax.swing.JTable" icon="/com/intellij/uiDesigner/icons/table.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JList" icon="/com/intellij/uiDesigner/icons/list.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="2" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTree" icon="/com/intellij/uiDesigner/icons/tree.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3">
<preferred-size width="150" height="50" />
</default-constraints>
</item>
<item class="javax.swing.JTabbedPane" icon="/com/intellij/uiDesigner/icons/tabbedPane.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSplitPane" icon="/com/intellij/uiDesigner/icons/splitPane.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="3" hsize-policy="3" anchor="0" fill="3">
<preferred-size width="200" height="200" />
</default-constraints>
</item>
<item class="javax.swing.JSpinner" icon="/com/intellij/uiDesigner/icons/spinner.svg" removable="false" auto-create-binding="true" can-attach-label="true">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSlider" icon="/com/intellij/uiDesigner/icons/slider.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="8" fill="1" />
</item>
<item class="javax.swing.JSeparator" icon="/com/intellij/uiDesigner/icons/separator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="6" anchor="0" fill="3" />
</item>
<item class="javax.swing.JProgressBar" icon="/com/intellij/uiDesigner/icons/progressbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1" />
</item>
<item class="javax.swing.JToolBar" icon="/com/intellij/uiDesigner/icons/toolbar.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="6" anchor="0" fill="1">
<preferred-size width="-1" height="20" />
</default-constraints>
</item>
<item class="javax.swing.JToolBar$Separator" icon="/com/intellij/uiDesigner/icons/toolbarSeparator.svg" removable="false" auto-create-binding="false" can-attach-label="false">
<default-constraints vsize-policy="0" hsize-policy="0" anchor="0" fill="1" />
</item>
<item class="javax.swing.JScrollBar" icon="/com/intellij/uiDesigner/icons/scrollbar.svg" removable="false" auto-create-binding="true" can-attach-label="false">
<default-constraints vsize-policy="6" hsize-policy="0" anchor="0" fill="2" />
</item>
</group>
</component>
</project>
\ No newline at end of file \ No newline at end of file
/mvnw text eol=lf
*.cmd text eol=crlf
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
# 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.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
<# : 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-<version>,maven-mvnd-<version>-<platform>}/<hash>
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"
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.glsk</groupId>
<artifactId>glsk-mcp-client</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>glsk-mcp-client</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-client-webflux-spring-boot-starter</artifactId>
<version>1.0.0-M6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
package com.glsk;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.transport.HttpClientSseClientTransport;
import io.modelcontextprotocol.spec.McpSchema;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.DefaultChatClientBuilder;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.ai.chat.model.ChatResponse;
import org.springframework.ai.chat.prompt.Prompt;
import java.util.Map;
public class App {
public static void main(String[] args) {
var transport = new HttpClientSseClientTransport("http://192.168.1.173:8090");
var client = McpClient.sync(transport).build();
client.initialize();
client.ping();
// List and demonstrate tools
McpSchema.ListToolsResult toolsList = client.listTools();
System.out.println("Available Tools = " + toolsList);
McpSchema.CallToolResult weatherForcastResult = client.callTool(new McpSchema.CallToolRequest("getWeatherForecastByLocation",
Map.of("latitude", "47.6062", "longitude", "-122.3321")));
System.out.println("Weather Forcast: " + weatherForcastResult);
McpSchema.CallToolResult alertResult = client.callTool(new McpSchema.CallToolRequest("getAirQuality", Map.of("latitude", "47.6062", "longitude", "-122.3321")));
System.out.println("Alert Response = " + alertResult);
client.closeGracefully();
}
}
package com.glsk;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class McpClientApplication {
public static void main(String[] args) {
SpringApplication.run(McpClientApplication.class, args);
}
// 直接硬编码中文问题,避免配置文件编码问题
// private String userInput = "北京的天气如何?";
// @Bean
// public CommandLineRunner predefinedQuestions(ChatClient.Builder chatClientBuilder, ToolCallbackProvider tools,
// ConfigurableApplicationContext context) {
// return args -> {
//
// var chatClient = chatClientBuilder
// .defaultTools(tools)
// .build();
//
// System.out.println("\n>>> QUESTION: " + userInput);
// System.out.println("\n>>> ASSISTANT: " + chatClient.prompt(userInput).call().content());
//
// context.close();
// };
// }
}
package com.glsk.controller;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api")
class MyWebFluxController {
// 处理 GET 请求
@GetMapping(value = "/get", produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<Map<String, String>> handleGetRequest() {
Map<String, String> response = new HashMap<>();
response.put("message", "This is a GET request response from WebFlux");
return Mono.just(response);
}
// 处理 POST 请求
@PostMapping(value = "/post", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public Mono<Map<String, String>> handlePostRequest(@RequestBody Mono<Map<String, String>> requestBodyMono) {
return requestBodyMono.flatMap(requestBody -> {
Map<String, String> response = new HashMap<>();
response.put("message", "This is a POST request response from WebFlux");
response.put("input", requestBody.toString());
return Mono.just(response);
});
}
}
server.port=8020
spring.application.name=glsk-mcp-client
spring.main.web-application-type=reactive
#spring.ai.mcp.client.enabled=true
#spring.ai.mcp.client.name=glsk-mcp-client
#spring.ai.mcp.client.version=1.0.0
#spring.ai.mcp.client.request-timeout=30s
#spring.ai.mcp.client.type=ASYNC
#spring.ai.mcp.client.sse.connections.server1.url=http://localhost:8090
#
#
#spring.ai.dashscope.api-key=sk-48654db737cc4fdb91aad1f2af7562b8
#spring.ai.dashscope.chat.options.model=qwen-plus
\ No newline at end of file \ No newline at end of file
spring:
application:
name: mcp
main:
web-application-type: none
ai:
dashscope:
api-key: sk-48654db737cc4fdb91aad1f2af7562b8
mcp:
client:
stdio:
servers-configuration: classpath:/mcp-servers-config.json
# 直接配置
# connections:
# server1:
# command: java
# args:
# - -jar
# - /Users/xiadong/mcp-stdio-server-exmaple-0.0.1-SNAPSHOT.jar # 放一个绝对路径,修改为server jar包所在位置
mandatory-file-encoding: UTF-8
# 调试日志
logging:
level:
io:
modelcontextprotocol:
client: DEBUG
spec: DEBUG
server:
servlet:
encoding:
charset: UTF-8
enabled: true
force: true
{
"mcpServers": {
"weather": {
"command": "java",
"args": [
"-Dspring.ai.mcp.server.stdio=true",
"-Dspring.main.web-application-type=none",
"-Dlogging.pattern.console=",
"-jar",
"E:\\Agi_Project\\spring-ai-alibaba-examples-main\\spring-ai-alibaba-mcp-example\\starter-example\\server\\starter-stdio-server\\target\\mcp-stdio-server-exmaple-0.0.1-SNAPSHOT.jar"
],
"env": {}
}
}
}
\ No newline at end of file \ No newline at end of file
package com.glsk;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GlskMcpApplicationTests {
@Test
void contextLoads() {
}
}
/mvnw text eol=lf
*.cmd text eol=crlf
HELP.md
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### STS ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### IntelliJ IDEA ###
.idea
*.iws
*.iml
*.ipr
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
# 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.
wrapperVersion=3.3.2
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.9/apache-maven-3.9.9-bin.zip
<# : 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-<version>,maven-mvnd-<version>-<platform>}/<hash>
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"
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>3.4.4</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.glsk</groupId>
<artifactId>glsk-mcp-server</artifactId>
<version>0.0.1</version>
<name>glsk-mcp-server</name>
<description>Demo project for Spring Boot</description>
<url/>
<licenses>
<license/>
</licenses>
<developers>
<developer/>
</developers>
<scm>
<connection/>
<developerConnection/>
<tag/>
<url/>
</scm>
<properties>
<java.version>17</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-server-spring-boot-starter</artifactId>
<version>1.0.0-M6</version>
</dependency>
<dependency>
<groupId>org.springframework.ai</groupId>
<artifactId>spring-ai-mcp-server-webflux-spring-boot-starter</artifactId>
<version>1.0.0-M6</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>5.2.4</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>5.2.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.17</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>2.14.8</version>
<exclusions>
<!-- <exclusion>-->
<!-- <groupId>com.github.victools</groupId>-->
<!-- <artifactId>jsonschema-generator</artifactId>-->
<!-- </exclusion>-->
</exclusions>
</dependency>
<!-- &lt;!&ndash; Jackson Core &ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>com.fasterxml.jackson.core</groupId>-->
<!-- <artifactId>jackson-core</artifactId>-->
<!-- <version>2.15.2</version> &lt;!&ndash; 确保使用最新或适合你的版本 &ndash;&gt;-->
<!-- </dependency>-->
<!-- &lt;!&ndash; Jackson Databind &ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>com.fasterxml.jackson.core</groupId>-->
<!-- <artifactId>jackson-databind</artifactId>-->
<!-- <version>2.15.2</version> &lt;!&ndash; 确保与jackson-core版本匹配 &ndash;&gt;-->
<!-- </dependency>-->
<!-- &lt;!&ndash; Jackson Annotations &ndash;&gt;-->
<!-- <dependency>-->
<!-- <groupId>com.fasterxml.jackson.core</groupId>-->
<!-- <artifactId>jackson-annotations</artifactId>-->
<!-- <version>2.15.2</version> &lt;!&ndash; 确保与其它两个模块版本匹配 &ndash;&gt;-->
<!-- </dependency>-->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4.15</version>
</dependency>
<!-- Jackson (用于JSON序列化) -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.0</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>2.0.20</version>
</dependency>
<dependency>
<groupId>com.volcengine</groupId>
<artifactId>volcengine-java-sdk-ark-runtime</artifactId>
<version>LATEST</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dashscope-sdk-java</artifactId>
<version>2.14.8</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.30</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<executions>
<execution>
<goals>
<goal>repackage</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
package com.glsk;
import com.glsk.service.*;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.tool.method.MethodToolCallbackProvider;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@SpringBootApplication
public class McpServerApplication {
public static void main(String[] args) {
SpringApplication.run(McpServerApplication.class, args);
}
// @Bean
// public ToolCallbackProvider weatherTools(WeatherService weatherService) {
// return MethodToolCallbackProvider.builder().toolObjects(weatherService).build();
// }
//
// @Bean
// public ToolCallbackProvider openMeteoTools(OpenMeteoService openMeteoService) {
// return MethodToolCallbackProvider.builder().toolObjects(openMeteoService).build();
// }
@Bean
public ToolCallbackProvider businessAnalysisTools(BusinessAnalysisService businessAnalysisService) {
return MethodToolCallbackProvider.builder().toolObjects(businessAnalysisService).build();
}
@Bean
public ToolCallbackProvider merchantAnalysisTools(MerchantAnalysisService merchantAnalysisService) {
return MethodToolCallbackProvider.builder().toolObjects(merchantAnalysisService).build();
}
@Bean
public ToolCallbackProvider staffAnalysisTools(StaffAnalysisService staffAnalysisService) {
return MethodToolCallbackProvider.builder().toolObjects(staffAnalysisService).build();
}
@Bean
public ToolCallbackProvider commonTools(CommonService commonService) {
return MethodToolCallbackProvider.builder().toolObjects(commonService).build();
}
// @Bean
// public ToolCallbackProvider staffReportTools(TeamSupervisorWeeklyReportService reportService) {
// return MethodToolCallbackProvider.builder().toolObjects(reportService).build();
// }
}
/*
* Copyright 2024 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glsk.client;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.ListToolsResult;
import java.util.Map;
/**
* 使用stdio传输,MCP服务器由客户端自动启动
* 但你需要先构建服务器jar:
*
* <pre>
* ./mvnw clean install -DskipTests
* </pre>
*/
public class ClientStdio {
public static void main(String[] args) {
var stdioParams = ServerParameters.builder("java")
.args("-Dspring.ai.mcp.server.stdio=true",
"-Dspring.main.web-application-type=none",
"-Dlogging.pattern.console=",
"-jar",
"glsk-mcp-server/target/glsk-mcp-server-0.0.1.jar")
.build();
var transport = new StdioClientTransport(stdioParams);
var client = McpClient.sync(transport).build();
client.initialize();
// 列出并展示可用的工具
ListToolsResult toolsList = client.listTools();
System.out.println("可用工具 = " + toolsList);
// // 获取北京的天气预报
// CallToolResult realTimeWeatherResult = client.callTool(new CallToolRequest("getRealTimeWeather",
// Map.of("cityId", "101010100")));
// System.out.println("北京天气预报: " + realTimeWeatherResult);
// 获取北京的天气预报
CallToolResult weatherForecastResult = client.callTool(new CallToolRequest("getWeatherForecastByLocation",
Map.of("latitude", "39.9042", "longitude", "116.4074")));
System.out.println("北京天气预报: " + weatherForecastResult);
// 获取北京的空气质量信息(模拟数据)
CallToolResult airQualityResult = client.callTool(new CallToolRequest("getAirQuality",
Map.of("latitude", "39.9042", "longitude", "116.4074")));
System.out.println("北京空气质量: " + airQualityResult);
client.closeGracefully();
}
}
package com.glsk.client;
import io.modelcontextprotocol.client.transport.ServerParameters;
import io.modelcontextprotocol.client.transport.StdioClientTransport;
import java.io.File;
import java.io.IOException;
public class ClientWebflux {
public static void main(String[] args) throws IOException {
System.out.println(new File(".").getAbsolutePath());
var stdioParams = ServerParameters.builder("java")
.args("-Dspring.ai.mcp.server.stdio=true",
"-Dspring.main.web-application-type=none",
"-Dlogging.pattern.console=",
"-jar",
"E:\\Agi_Project\\glsk-mcp\\glsk-mcp-server\\target\\glsk-mcp-server-0.0.1.jar")
.build();
var transport = new StdioClientTransport(stdioParams);
new SampleClient(transport).run();
}
}
/*
* Copyright 2024 - 2024 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.glsk.client;
import io.modelcontextprotocol.client.McpClient;
import io.modelcontextprotocol.spec.ClientMcpTransport;
import io.modelcontextprotocol.spec.McpSchema.CallToolRequest;
import io.modelcontextprotocol.spec.McpSchema.CallToolResult;
import io.modelcontextprotocol.spec.McpSchema.ListToolsResult;
import java.util.Map;
/**
* @author brianxiadong
*/
public class SampleClient {
private final ClientMcpTransport transport;
public SampleClient(ClientMcpTransport transport) {
this.transport = transport;
}
public void run() {
var client = McpClient.sync(this.transport).build();
client.initialize();
client.ping();
// 列出并展示可用的工具
ListToolsResult toolsList = client.listTools();
System.out.println("可用工具 = " + toolsList);
// 获取北京的天气预报
CallToolResult weatherForecastResult = client.callTool(new CallToolRequest("getWeatherForecastByLocation",
Map.of("latitude", "39.9042", "longitude", "116.4074")));
System.out.println("北京天气预报: " + weatherForecastResult);
// 获取北京的空气质量信息
CallToolResult airQualityResult = client.callTool(new CallToolRequest("getAirQuality",
Map.of("latitude", "39.9042", "longitude", "116.4074")));
System.out.println("北京空气质量: " + airQualityResult);
client.closeGracefully();
}
}
package com.glsk.component;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.Map;
import java.util.Objects;
/**
* HTTP 工具类 - 基于 Spring RestTemplate
* 适配 Spring Boot 3.x
*/
@Slf4j
@Component
public class HttpUtil {
private final RestTemplate restTemplate;
private final ObjectMapper objectMapper;
public HttpUtil() {
this.restTemplate = new RestTemplate();
this.objectMapper = new ObjectMapper();
}
/**
* GET 请求
*/
public String doGet(String url, Map<String, Object> params) {
return doGet(url, params, null);
}
/**
* GET 请求
*/
public String doGet(String url, Map<String, Object> params, Map<String, String> headers) {
try {
HttpEntity<String> requestEntity = new HttpEntity<>(buildHeaders(headers));
ResponseEntity<String> response = restTemplate.exchange(
buildUrlWithParams(url, params),
HttpMethod.GET,
requestEntity,
String.class
);
return handleResponse(response);
} catch (Exception e) {
log.error("GET请求失败: {}, 参数: {}", url, params, e);
throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
}
}
/**
* POST 请求 - JSON 格式
*/
public String doPostJson(String url, Object params) {
return doPostJson(url, params, null);
}
/**
* POST 请求 - JSON 格式
*/
public String doPostJson(String url, Object params, Map<String, String> headers) {
try {
HttpHeaders httpHeaders = buildHeaders(headers);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
String requestBody = params != null ? objectMapper.writeValueAsString(params) : "";
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, httpHeaders);
log.debug("POST JSON请求: {}, 参数: {}", url, requestBody);
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
String.class
);
return handleResponse(response);
} catch (Exception e) {
log.error("POST JSON请求失败: {}, 参数: {}", url, params, e);
throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
}
}
/**
* POST 请求 - 表单格式
*/
public String doPostForm(String url, Map<String, Object> params) {
return doPostForm(url, params, null);
}
/**
* POST 请求 - 表单格式
*/
public String doPostForm(String url, Map<String, Object> params, Map<String, String> headers) {
try {
HttpHeaders httpHeaders = buildHeaders(headers);
httpHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
MultiValueMap<String, String> formData = new LinkedMultiValueMap<>();
if (params != null) {
params.forEach((key, value) -> {
if (value != null) {
formData.add(key, value.toString());
}
});
}
HttpEntity<MultiValueMap<String, String>> requestEntity = new HttpEntity<>(formData, httpHeaders);
log.debug("POST表单请求: {}, 参数: {}", url, formData);
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.POST,
requestEntity,
String.class
);
return handleResponse(response);
} catch (Exception e) {
log.error("POST表单请求失败: {}, 参数: {}", url, params, e);
throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
}
}
/**
* PUT 请求 - JSON 格式
*/
public String doPutJson(String url, Object params) {
return doPutJson(url, params, null);
}
/**
* PUT 请求 - JSON 格式
*/
public String doPutJson(String url, Object params, Map<String, String> headers) {
try {
HttpHeaders httpHeaders = buildHeaders(headers);
httpHeaders.setContentType(MediaType.APPLICATION_JSON);
String requestBody = params != null ? objectMapper.writeValueAsString(params) : "";
HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, httpHeaders);
log.debug("PUT请求: {}, 参数: {}", url, requestBody);
ResponseEntity<String> response = restTemplate.exchange(
url,
HttpMethod.PUT,
requestEntity,
String.class
);
return handleResponse(response);
} catch (Exception e) {
log.error("PUT请求失败: {}, 参数: {}", url, params, e);
throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
}
}
/**
* DELETE 请求
*/
public String doDelete(String url, Map<String, Object> params) {
return doDelete(url, params, null);
}
/**
* DELETE 请求
*/
public String doDelete(String url, Map<String, Object> params, Map<String, String> headers) {
try {
HttpEntity<String> requestEntity = new HttpEntity<>(buildHeaders(headers));
ResponseEntity<String> response = restTemplate.exchange(
buildUrlWithParams(url, params),
HttpMethod.DELETE,
requestEntity,
String.class
);
return handleResponse(response);
} catch (Exception e) {
log.error("DELETE请求失败: {}, 参数: {}", url, params, e);
throw new RuntimeException("HTTP请求失败: " + e.getMessage(), e);
}
}
/**
* 构建带参数的 URL
*/
private String buildUrlWithParams(String url, Map<String, Object> params) {
if (params == null || params.isEmpty()) {
return url;
}
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url);
params.forEach((key, value) -> {
if (value != null) {
builder.queryParam(key, value.toString());
}
});
return builder.build().toUriString();
}
/**
* 构建请求头
*/
private HttpHeaders buildHeaders(Map<String, String> headers) {
HttpHeaders httpHeaders = new HttpHeaders();
if (headers != null) {
headers.forEach(httpHeaders::set);
}
return httpHeaders;
}
/**
* 处理响应 - 适配 Spring Boot 3.x
*/
private String handleResponse(ResponseEntity<String> response) {
// Spring Boot 3.x 中,response.getStatusCode() 返回 HttpStatusCode 接口
// 不再是 HttpStatus 枚举,但我们可以通过 value() 方法获取状态码数值
int statusCode = response.getStatusCode().value();
String responseBody = response.getBody();
log.debug("HTTP响应状态码: {}, 响应体: {}", statusCode, responseBody);
// 检查是否为 2xx 状态码
if (statusCode >= 200 && statusCode < 300) {
return Objects.toString(responseBody, "");
} else {
throw new RuntimeException("HTTP请求失败,状态码: " + statusCode + ", 响应: " + responseBody);
}
}
/**
* 将响应字符串转换为指定类型
*/
public <T> T parseResponse(String response, Class<T> clazz) {
try {
return objectMapper.readValue(response, clazz);
} catch (Exception e) {
log.error("解析响应失败", e);
throw new RuntimeException("解析响应失败", e);
}
}
/**
* 将响应字符串转换为复杂类型
*/
public <T> T parseResponse(String response, TypeReference<T> typeReference) {
try {
return objectMapper.readValue(response, typeReference);
} catch (Exception e) {
log.error("解析响应失败", e);
throw new RuntimeException("解析响应失败", e);
}
}
}
\ No newline at end of file \ No newline at end of file
package com.glsk.conf;
import java.io.InputStream;
import java.util.Properties;
public class ConfigurationManager {
private static Properties prop = new Properties();
static {
try {
InputStream in = ConfigurationManager.class.getClassLoader().getResourceAsStream("application.properties");
prop.load(in);
} catch (Exception ex) {
ex.printStackTrace();
}
}
public static String getProperty(String key) {
return prop.getProperty(key);
}
public static Integer getInteger(String key) {
return Integer.valueOf(prop.getProperty(key));
}
public static Boolean getBoolean(String key) {
return Boolean.valueOf(prop.getProperty(key));
}
public static Long getLong(String key) {
return Long.valueOf(prop.getProperty(key));
}
public static void main(String[] args) {
System.out.println(ConfigurationManager.getProperty("mysql.url.dj_smartcarlife"));
}
}
package com.glsk.connection;
import com.glsk.conf.ConfigurationManager;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.*;
import java.util.ArrayList;
public class MysqlConn {
private static Connection connection = null;
static {
try {
// Class.forName("com.mysql.jdbc.Driver");
Class.forName("com.mysql.cj.jdbc.Driver");
} catch (Exception ex) {
ex.printStackTrace();
}
}
private MysqlConn() {
}
public static Connection getConnection(String url) {
if (connection == null) {
synchronized (MysqlConn.class) {
if (connection == null) {
try {
connection = DriverManager.getConnection(url);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
try {
if (!connection.isValid(1)) {
close(connection);
connection = DriverManager.getConnection(url);
}
return connection;
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
public static void executeUpdate(Connection connection, String sql) {
PreparedStatement pstmt = null;
try {
connection.setAutoCommit(false);
pstmt = connection.prepareStatement(sql);
pstmt.executeUpdate();
connection.commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static ArrayList<ArrayList<String>> executeQuery(Connection connection, String sql, int columns) {
try {
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<ArrayList<String>> result = new ArrayList<>();
while (rs.next()) {
String temp = "";
ArrayList<String> colList = new ArrayList<>();
for (int i = 1; i <= columns; i++) {
colList.add(rs.getString(i));
}
result.add(colList);
}
rs.close();
ps.close();
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static void executeQuery(Connection connection, String sql, QueryCallback callback) {
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = connection.prepareStatement(sql);
rs = pstmt.executeQuery();
callback.process(rs);
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
// 流式查询
public static void executeFlowQuery(Connection connection, String sql, QueryCallback callback) {
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
pstmt.setFetchSize(Integer.MIN_VALUE);
pstmt.setFetchDirection(ResultSet.FETCH_REVERSE);
rs = pstmt.executeQuery();
callback.process(rs);
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void close(Connection connection) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static interface QueryCallback {
void process(ResultSet rs) throws Exception;
}
public static void main(String[] args) throws UnsupportedEncodingException {
// dbc:mysql://192.168.3.222:3308/scrm_account?user=os_user&password=os#123&autoReconnect=true&autoReconnectForPools=true
System.out.println("URL=" + ConfigurationManager.getProperty("mysql.url.xlyq_agi"));
String password = "v#@JrWCEH9g3";
String encodedPassword = URLEncoder.encode(password, "UTF-8");
String url = "jdbc:mysql://rm-wz9uqix4n8s738dq18o.mysql.rds.aliyuncs.com:3306/xlyq_agi"
+ "?user=bool"
+ "&password=" + encodedPassword
+ "&useSSL=false"
+ "&serverTimezone=Asia/Shanghai"
+ "&allowPublicKeyRetrieval=true"
+ "&autoReconnect=true"
+ "&autoReconnectForPools=true";
Connection conn = MysqlConn.getConnection(url);
// for (int i = 0; i < 100; i++) {
// String sql = "insert into t_user(username,password) values('name"+(100+i) + "','pw"+(100+i) + "')";
// System.out.println(sql);
// MysqlConn.executeUpdate(conn, sql);
// }
final StringBuffer buffer = new StringBuffer();
MysqlConn.executeQuery(conn, "select theme,content_unit,post_content from xlyq_agi.fund_post\n" +
"where post_date = '2025-11-15' limit 10", new QueryCallback() {
@Override
public void process(ResultSet rs) throws Exception {
while (rs.next()) {
// System.out.println(rs.getString(1));
buffer.append(rs.getString(1));
}
}
});
System.out.println(buffer.toString());
MysqlConn.close(conn);
}
}
package com.glsk.connection;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Mysql连接,可以跨机器使用数据库连接
*/
public class MysqlMutiConn {
private static HashMap<String, Connection> mutiConnection = new HashMap<>();
public static void addConnection(String name, String url) {
try {
Connection connection = DriverManager.getConnection(url);
mutiConnection.put(name, connection);
} catch (SQLException e) {
e.printStackTrace();
}
}
public static Connection getConnection(String name) {
return mutiConnection.get(name);
}
public static void close(Connection connection) {
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void executeUpdate(Connection connection, String sql) {
PreparedStatement pstmt = null;
try {
connection.setAutoCommit(false);
pstmt = connection.prepareStatement(sql);
pstmt.executeUpdate();
connection.commit();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void executeQuery(Connection connection, String sql, QueryCallback callback) {
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = connection.prepareStatement(sql);
rs = pstmt.executeQuery();
callback.process(rs);
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static ArrayList<ArrayList<String>> executeQuery(Connection connection, String sql, int columns) {
try {
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
ArrayList<ArrayList<String>> result = new ArrayList<>();
while (rs.next()) {
String temp = "";
ArrayList<String> colList = new ArrayList<>();
for (int i = 1; i <= columns; i++) {
colList.add(rs.getString(i));
}
result.add(colList);
}
rs.close();
ps.close();
return result;
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
// 流式查询
public static void executeFlowQuery(Connection connection, String sql, QueryCallback callback) {
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
pstmt = connection.prepareStatement(sql, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
pstmt.setFetchSize(Integer.MIN_VALUE);
pstmt.setFetchDirection(ResultSet.FETCH_REVERSE);
rs = pstmt.executeQuery();
callback.process(rs);
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
public static interface QueryCallback {
void process(ResultSet rs) throws Exception;
}
public static void main(String[] args) {
}
}
package com.glsk.controller;
import com.glsk.conf.ConfigurationManager;
import com.glsk.connection.MysqlConn;
import com.glsk.llm.impl.LLMToolFactory;
import com.glsk.llm.impl.LLMTools;
import com.glsk.llm.model.LLMRequest;
import com.glsk.llm.model.LLMResponse;
import com.glsk.util.DocxToMarkdownConverter;
import com.glsk.util.JsonToExcelConverter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.sql.Connection;
import java.util.*;
import java.util.stream.Collectors;
@Slf4j
@RestController
@RequestMapping("/api")
public class CommonController {
@PostMapping("/ai/common/doc_to_markdown")
public Map docToMarkdown(@RequestParam("fileName") String fileName) {
Map<String, Object> result = new HashMap<>();
Map<String, Object> text = DocxToMarkdownConverter.textToExcel(fileName);
result.put("text", text);
result.put("code", 200);
result.put("success", true);
return result;
}
@PostMapping("/ai/common/text_to_excel")
public Map textToExcel(@RequestParam("fileName") String fileName,
@RequestParam("author") String author,
@RequestBody String text) {
log.info("开始根据文本生成示例,text: {},fileName:{},author:{}", text,fileName,author);
Map<String, Object> result = new HashMap<>();
try {
JsonToExcelConverter.convertJsonToExcel(text, fileName, author);
result.put("code", 200);
result.put("success", true);
} catch (Exception ex) {
result.put("code", 800);
result.put("success", false);
result.put("error", ex.getMessage());
ex.printStackTrace();
}
log.info("完成测试用例的生成,fileName:{}",fileName);
return result;
}
@PostMapping("/ai/common/post_merge_summary")
public Map queryData(@RequestParam("post_date") String postDate,
@RequestParam("themes") String themes) throws UnsupportedEncodingException {
log.info("开始根据日期和主题查询数据,postDate:{},themes:{}", postDate,themes);
String password = "v#@JrWCEH9g3";
String encodedPassword = URLEncoder.encode(password, "UTF-8");
String url = "jdbc:mysql://rm-wz9uqix4n8s738dq18o.mysql.rds.aliyuncs.com:3306/xlyq_agi"
+ "?user=bool"
+ "&password=" + encodedPassword
+ "&useSSL=false"
+ "&serverTimezone=Asia/Shanghai"
+ "&allowPublicKeyRetrieval=true"
+ "&autoReconnect=true"
+ "&autoReconnectForPools=true";
Connection connection = MysqlConn.getConnection(url);
String[] themeSplit = themes.trim().replaceAll(",", ",").split(",");
String whereTheme = Arrays.stream(themeSplit).map(s -> "'" + s + "'").collect(Collectors.joining(", "));
Map<String, Object> result = new HashMap<>();
try {
StringBuffer sqlBuff = new StringBuffer();
StringBuffer idBuff = new StringBuffer();
for (int index = 0; index < themeSplit.length; index++) {
if (index > 0) sqlBuff.append("UNION ALL \n");
sqlBuff.append("select id,theme,content_unit,post_content from ");
sqlBuff.append("(").append(String.format("select id,theme,content_unit,post_content from xlyq_agi.fund_post\n" +
"where post_date = '%s' and theme = '%s' limit 10 ) as t%d\n", postDate, themeSplit[index], index));
}
System.out.println(sqlBuff.toString());
StringBuffer sb = new StringBuffer();
ArrayList<ArrayList<String>> arrayLists = MysqlConn.executeQuery(connection, sqlBuff.toString(), 4);
for (ArrayList<String> item : arrayLists) {
sb.append("主题:").append(item.get(1)).append("\n");
sb.append("内容单元:").append(item.get(2)).append("\n");
sb.append("帖子:").append(item.get(3)).append("\n");
sb.append("-----------------------------------------");
idBuff.append(item.get(0)).append(",");
}
String sql = "select system_prompt,user_prompt from llm_prompt where type_id = 1 and status = 1";
ArrayList<ArrayList<String>> executeQuery = MysqlConn.executeQuery(connection, sql, 2);
String systemPrompt = executeQuery.get(0).get(0);
String userPrompt = executeQuery.get(0).get(1);
LLMRequest req = new LLMRequest();
req.setModeName("qwen-plus");
req.setSystem(systemPrompt);
req.setUser(userPrompt);
req.setContent(sb.toString());
LLMTools llmTool = LLMToolFactory.createLLMTool(2);
LLMResponse response = llmTool.invoke(req);
String insertSql = String.format("insert into xlyq_agi.post_merge_summary(post_date,select_themes,data_source_ids,post_merge_content,content_length,status,input_token_count,output_token_count,token_count,error_message) " +
"values('%s','%s','%s','%s',%d,%d,%d,%d,%d,'%s')", postDate, themes, idBuff.toString(), response.getMessage(), response.getMessage().length(), 1,
response.getPromptTokens(),response.getCompletionTokens(), response.getTotalTokens(), response.getError());
System.out.println(insertSql);
MysqlConn.executeUpdate(connection, insertSql);
result.put("text",response.getMessage());
result.put("code", 200);
result.put("success", true);
} catch (Exception ex) {
result.put("code", 800);
result.put("success", false);
result.put("error", ex.getMessage());
ex.printStackTrace();
} finally {
MysqlConn.close(connection);
}
log.info("完成数据查询,postDate:{},themes:{}",postDate,themes);
return result;
}
public static void main(String[] args) {
String themes = "市场涨跌,基金净值,安利卖点";
String postDate = "2025-11-15";
String[] themeSplit = themes.trim().replaceAll(",", ",").split(",");
StringBuffer sqlBuff = new StringBuffer();
for (int index = 0; index < themeSplit.length; index++) {
if (index > 0) sqlBuff.append("UNION ALL \n");
sqlBuff.append("select id,theme,content_unit,post_content from ");
sqlBuff.append("(").append(String.format("select id,theme,content_unit,post_content from xlyq_agi.fund_post\n" +
"where post_date = '%s' and theme = '%s' limit 10 ) as t%d\n", postDate, themeSplit[index], index));
}
System.out.println(sqlBuff.toString());
LLMRequest req = new LLMRequest();
req.setModeName("qwen-plus");
req.setSystem("你是谁");
req.setUser("你是一个专家");
req.setContent("写一首诗");
LLMTools llmTool = LLMToolFactory.createLLMTool(2);
LLMResponse response = llmTool.invoke(req);
StringBuffer idBuff = new StringBuffer();
idBuff.append("1,2,3");
String insertSql = String.format("insert into xlyq_agi.post_merge_summary(post_date,select_themes,data_source_ids,post_merge_content,content_length,status,input_token_count,output_token_count,token_count,error_message) " +
"values('%s','%s','%s','%s',%d,%d,%d,%d,%d,'%s')", postDate, themes, idBuff.toString(), response.getMessage(), response.getMessage().length(), 1,
response.getPromptTokens(),response.getCompletionTokens(), response.getTotalTokens(), response.getError());
System.out.println(insertSql);
}
}
//package com.glsk.llm.impl;
//
//
//import cn.hutool.json.JSONUtil;
//import com.alibaba.fastjson.JSONObject;
//import com.glsk.llm.model.LLMRequest;
//import com.glsk.llm.model.LLMResponse;
//import lombok.extern.slf4j.Slf4j;
//import okhttp3.*;
//
//import java.io.IOException;
//import java.util.concurrent.TimeUnit;
//
///**
// * 自定义组装模型接口
// */
//
//
//@Slf4j
//public class CustomModelTool implements LLMTools {
// private OkHttpClient client;
// private String url;
// private String apiKey;
//
// @Override
// public CustomModelTool init(String key) {
// this.client = new OkHttpClient
// .Builder()
// .readTimeout(600, TimeUnit.SECONDS)
// .build();
//
// this.apiKey = key;
//// this.url = "https://aiassistant.glsx.com.cn/v1/workflows/run";
// this.url = "https://aiassistant.test.glsx.com.cn/v1/workflows/run"; // 测试
//
// return this;
// }
//
// @Override
// public String lauchLLM(LLMRequest req) {
// return "";
// }
//
// @Override
// public String lauchImageLLM(LLMRequest req) {
// return "";
// }
//
// @Override
// public LLMResponse invoke(LLMRequest req) {
//
//// LLMResponse response = new com.glsk.llm.model.LLMResponse();
//
// LLMResponse llmResponse = new LLMResponse();
// JSONObject inputs = new JSONObject();
// inputs.put("recText", req.getContent());
//
// JSONObject requestBody = new JSONObject();
// requestBody.put("inputs", inputs);
// requestBody.put("response_mode", "blocking");
// requestBody.put("user", "20并发测试-压测");
//
//// log.info("调用自定义模型参数:businessType={},callModelTime={}",req.getBusinessType(), Instant.now());
//
// RequestBody body = RequestBody.create(
// MediaType.parse("application/json"),
// requestBody.toString()
// );
//
// Request request = new Request.Builder()
// .url(url)
// .addHeader("Authorization", "Bearer " + apiKey)
// .addHeader("Content-Type", "application/json")
// .post(body)
// .build();
//
// // Execute request
// try (Response response = client.newCall(request).execute()) {
// if (response.isSuccessful() && response.body() != null) {
// String responseBody = response.body().string();
// JSONObject jsonResponse = JSONObject.parseObject(responseBody);
// String workflowRunId = jsonResponse.getString("workflow_run_id");
// JSONObject jsonData = jsonResponse.getJSONObject("data");
// Integer totalTokens = jsonData.getInteger("total_tokens");
// JSONObject result = jsonData.getJSONObject("outputs").getJSONObject("result");
// llmResponse.setRequestId(workflowRunId);
// llmResponse.setTotalTokens(totalTokens);
// llmResponse.setMessage(JSONObject.toJSONString(result));
// llmResponse.setSuccess(true);
// llmResponse.setTaskFinished(true);
// llmResponse.setCode(200);
// log.info("rsp:{}", JSONUtil.toJsonStr(llmResponse));
// } else {
// llmResponse.setError("请求失败");
// llmResponse.setSuccess(false);
// llmResponse.setTaskFinished(true);
// llmResponse.setCode(response.code());
// log.info("rsp:{}", JSONUtil.toJsonStr(llmResponse));
// }
// } catch (IOException e) {
// e.printStackTrace();
// llmResponse.setError(e.getMessage());
// llmResponse.setSuccess(false);
// llmResponse.setTaskFinished(true);
// llmResponse.setCode(400);
// log.info("rsp:{}", JSONUtil.toJsonStr(llmResponse));
// }
// return llmResponse;
// }
//}
package com.glsk.llm.impl;
public class LLMToolFactory {
/**
*
* @param modeType 模型类别 1-智普 2-千问 3-豆包 4-百度
* @return
*/
public static LLMTools createLLMTool(Integer modeType) {
LLMTools llmTool = null;
String key = "";
if (modeType == 1) {
key = "91ec43d091d925ffaad067da44c7a800.g6VVjrdXb1KeXBw2";
// llmTool = new ChatglmTool().init(key);
} else if (modeType == 2) {
// key = "sk-0721c51e73fc4a44a0deda96bb8cfe18"; // 自己的
key = "sk-48654db737cc4fdb91aad1f2af7562b8"; // 测试用
llmTool = new QwenTool().init(key);
} else if (modeType == 3){
key = "AKLTYTdjZTBmYmUyNWY0NDgyNWJlMTdmNWNlMjMxYjYxYTU.TWpRNU9XTmhPVGszTldFME5EVmtNamxrWXpCall6SXlZVFV5WXpoaU9UTQ==";
// llmTool = new DoubaoTool().init(key);
} else if (modeType == 4){
} else if (modeType == 99) {
key = "app-UjfMn0UWo66VfE8exb0TiWHH";
// llmTool = new CustomModelTool().init(key);
}
return llmTool;
}
}
package com.glsk.llm.impl;
import com.glsk.llm.model.LLMRequest;
import com.glsk.llm.model.LLMResponse;
public interface LLMTools {
public LLMTools init(String apikey);
public String lauchLLM(LLMRequest req);
public String lauchImageLLM(LLMRequest req);
public LLMResponse invoke(LLMRequest req);
}
package com.glsk.llm.impl;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.GenerationUsage;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.ResultCallback;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.glsk.llm.model.LLMRequest;
import com.glsk.llm.model.LLMResponse;
import java.util.*;
import java.util.concurrent.Semaphore;
public class QwenTool implements LLMTools {
private Generation gen;
@Override
public LLMTools init(String apikey) {
Constants.apiKey = apikey;
Generation gen = new Generation();
this.gen = gen;
return this;
}
@Override
public String lauchLLM(LLMRequest req) {
Constants.apiKey = "sk-48654db737cc4fdb91aad1f2af7562b8";
final List<Message> messages = new ArrayList<>();
final Message systemMessage = Message.builder().role(Role.SYSTEM.getValue()).content(req.getSystem()).build();
final Message userMessage = Message.builder().role(Role.USER.getValue()).content(String.format("<content>\n%s\n</content>\n%s\n", req.getContent(), req.getUser())).build();
// final Message systemMessage = Message.builder().role(Role.SYSTEM.getValue()).content(req.getUser()).build();
// final Message userMessage = Message.builder().role(Role.USER.getValue()).content(req.getContent()).build();
messages.add(systemMessage);
messages.add(userMessage);
GenerationParam param =
GenerationParam.builder().model(req.getModeName())
.messages(messages)
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.maxTokens(req.getMaxTokens())
.temperature(0.01F)
.incrementalOutput(true)
.build();
Semaphore semaphore = new Semaphore(0);
final String[] requestId = {""};
final GenerationUsage[] usage = {null};
StringBuilder fullContent = new StringBuilder();
try {
gen.streamCall(param, new ResultCallback<GenerationResult>() {
@Override
public void onEvent(GenerationResult message) {
requestId[0] = message.getRequestId();
usage[0] = message.getUsage();
fullContent.append(message.getOutput().getChoices().get(0).getMessage().getContent());
}
@Override
public void onError(Exception ex) {
System.out.println(ex.getMessage());
semaphore.release();
}
@Override
public void onComplete() {
// System.out.println("onComplete");
semaphore.release();
}
});
semaphore.acquire();
} catch (Exception ex) {
}
// System.out.println("Full content: \n" + fullContent);
// QwenParam param =
// QwenParam.builder()
//// .model("qwen2-72b-instruct")
// .model(req.getModeName())
// .messages(messages)
// .resultFormat(QwenParam.ResultFormat.MESSAGE)
// .maxTokens(4096)
// .temperature(0.01F)
// .build();
//
// GenerationResult result = null;
// try {
// result = gen.call(param);
// } catch (NoApiKeyException e) {
// throw new RuntimeException(e);
// } catch (InputRequiredException e) {
// throw new RuntimeException(e);
// }
// String retContent = result.getOutput().getChoices().get(0).getMessage().getContent();
// System.out.println("原始返回:\n" + retContent);
// System.out.println(String.format("requestId=%s", requestId[0]));
return fullContent.toString();
}
@Override
public String lauchImageLLM(LLMRequest req) {
// Constants.apiKey = "sk-48654db737cc4fdb91aad1f2af7562b8";
MultiModalConversation conv = new MultiModalConversation();
MultiModalMessage systemMessage = MultiModalMessage.builder()
.role(Role.SYSTEM.getValue())
.content(Arrays.asList(Collections.singletonMap("text", req.getSystem()))).build();
MultiModalMessage userMessage = MultiModalMessage.builder()
.role(Role.USER.getValue())
.content(Arrays.asList(
Collections.singletonMap("image", req.getContent()),
Collections.singletonMap("text", req.getUser()))).build();
MultiModalConversationParam param = MultiModalConversationParam.builder()
// .apiKey("sk-48654db737cc4fdb91aad1f2af7562b8")
.model("qwen-vl-max")
.messages(Arrays.asList(systemMessage, userMessage))
.build();
MultiModalConversationResult result = null;
try {
result = conv.call(param);
} catch (NoApiKeyException e) {
throw new RuntimeException(e);
} catch (UploadFileException e) {
throw new RuntimeException(e);
}
String textContent = String.valueOf(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
System.out.println(textContent);
return textContent;
}
public LLMResponse invoke(LLMRequest req) {
Constants.apiKey = "sk-48654db737cc4fdb91aad1f2af7562b8";
LLMResponse response = new LLMResponse();
List<Message> messages = new ArrayList<>();
Message systemMessage = Message.builder().role(Role.SYSTEM.getValue()).content(req.getSystem()).build();
Message userMessage = Message.builder().role(Role.USER.getValue()).content(String.format("<content>\n%s\n</content>\n%s\n", req.getContent(), req.getUser())).build();
messages.add(systemMessage);
messages.add(userMessage);
GenerationParam param =
GenerationParam.builder()
.model(req.getModeName())
.messages(messages)
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.maxTokens(req.getMaxTokens())
.temperature(0.01F)
.incrementalOutput(true)
.build();
Semaphore semaphore = new Semaphore(0);
StringBuilder fullContent = new StringBuilder();
String[] requestId = {""};
GenerationUsage[] usage = {null};
final long[] delayTime = {0};
final Date[] nowTime = {new Date()};
try {
gen.streamCall(param, new ResultCallback<GenerationResult>() {
@Override
public void onEvent(GenerationResult message) {
requestId[0] = message.getRequestId();
usage[0] = message.getUsage();
if (message.getOutput() != null && !message.getOutput().getChoices().isEmpty())
fullContent.append(message.getOutput().getChoices().get(0).getMessage().getContent());
long now = System.currentTimeMillis();
if (now <= delayTime[0] || delayTime[0]==0) {
delayTime[0] = now;
nowTime[0] = new Date();
}
}
@Override
public void onError(Exception ex) {
ex.printStackTrace();
semaphore.release();
}
@Override
public void onComplete() {
semaphore.release();
}
});
semaphore.acquire();
response.setRequestId(requestId[0]);
if (usage[0] != null) {
response.setPromptTokens(usage[0].getInputTokens());
response.setCompletionTokens(usage[0].getOutputTokens());
response.setTotalTokens(usage[0].getTotalTokens());
}
response.setMessage(fullContent.toString());
response.setSuccess(true);
response.setTaskFinished(true);
response.setCode(200);
response.setFirstLetterTime(delayTime[0]);
response.setFirstLetterTimeDate(nowTime[0]);
} catch (NullPointerException nullEx) {
nullEx.printStackTrace();
response.setError("异步函数内部异常,请检查key是否有问题!");
response.setMessage("异步函数内部异常,请检查key是否有问题!");
response.setSuccess(false);
response.setTaskFinished(false);
response.setCode(0);
} catch (Exception ex) {
ex.printStackTrace();
String message = ex.getMessage();
JSONObject object = JSON.parseObject(message);
response.setRequestId(object.getString("requestId"));
response.setError(object.getString("error"));
response.setMessage(object.getString("message"));
response.setSuccess(false);
response.setTaskFinished(false);
response.setCode(object.getInteger("statusCode"));
System.out.println(response.getError());
}
return response;
}
public static void main(String[] args) {
LLMTools llmTool = LLMToolFactory.createLLMTool(2).init("sk-48654db737cc4fdb91aad1f2af7562b8");
LLMRequest req = new LLMRequest();
req.setSystem("你是谁");
req.setUser("你是诗人");
req.setContent("写一首诗");
req.setModeName("/data/QwQ-32B");
// req.setModeName("/data/Qwen3-30B-A3B");
// req.setModeName("qwen-plus");
LLMResponse response = llmTool.invoke(req);
System.out.println(response.getMessage());
}
}
\ No newline at end of file \ No newline at end of file
package com.glsk.llm.model;
import com.alibaba.dashscope.common.Message;
import java.util.List;
public class LLMImageRequest {
private Integer maxTokens = 4096;
private String modelName;
private List<Message> messages;
public List<Message> getMessages() {
return messages;
}
public void setMessages(List<Message> messages) {
this.messages = messages;
}
public String getModelName() {
return modelName;
}
public void setModelName(String modelName) {
this.modelName = modelName;
}
public Integer getMaxTokens() {
return maxTokens;
}
public void setMaxTokens(Integer maxTokens) {
this.maxTokens = maxTokens;
}
}
package com.glsk.llm.model;
public class LLMRequest {
private String modeName = "GLM-4";
private String system;
private String user;
private String content;
private Integer maxTokens = 4096;
public String getModeName() {
return modeName;
}
public void setModeName(String modeName) {
this.modeName = modeName;
}
public String getSystem() {
return system;
}
public void setSystem(String system) {
this.system = system;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Integer getMaxTokens() {
return maxTokens;
}
public void setMaxTokens(Integer maxTokens) {
this.maxTokens = maxTokens;
}
}
package com.glsk.llm.model;
import java.util.Date;
public class LLMResponse {
/**
* 请求id
*/
private String requestId;
/**
* 异步查询id
*/
private String taskId;
/**
* 异步请求是否完成
*/
private boolean taskFinished;
/**
* 提示词tokens数
*/
private int promptTokens;
/**
* 输出tokens数
*/
private int completionTokens;
/**
* 总tokens数
*/
private int totalTokens;
/**
* 响应时间
*/
private Date created = new Date();
/**
* 响应内容
*/
private String message;
/**
* 是否成功
*/
private boolean success;
/**
* 失败错误描述
*/
private String error;
private int code;
/**
* 第一个字产生的时间
*/
private long firstLetterTime;
/**
* 首字当前时间精确到秒
*/
private Date firstLetterTimeDate;
/**
* 大模型原始响应内容
*/
private String llmMessage;
public String getRequestId() {
return requestId;
}
public void setRequestId(String requestId) {
this.requestId = requestId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public boolean isTaskFinished() {
return taskFinished;
}
public void setTaskFinished(boolean taskFinished) {
this.taskFinished = taskFinished;
}
public int getPromptTokens() {
return promptTokens;
}
public void setPromptTokens(int promptTokens) {
this.promptTokens = promptTokens;
}
public int getCompletionTokens() {
return completionTokens;
}
public void setCompletionTokens(int completionTokens) {
this.completionTokens = completionTokens;
}
public int getTotalTokens() {
return totalTokens;
}
public void setTotalTokens(int totalTokens) {
this.totalTokens = totalTokens;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public boolean isSuccess() {
return success;
}
public void setSuccess(boolean success) {
this.success = success;
}
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getLlmMessage() {
return llmMessage;
}
public void setLlmMessage(String llmMessage) {
this.llmMessage = llmMessage;
}
public long getFirstLetterTime() {
return firstLetterTime;
}
public void setFirstLetterTime(long firstLetterTime) {
this.firstLetterTime = firstLetterTime;
}
public Date getFirstLetterTimeDate() {
return firstLetterTimeDate;
}
public void setFirstLetterTimeDate(Date firstLetterTimeDate) {
this.firstLetterTimeDate = firstLetterTimeDate;
}
}
package com.glsk.service;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonProperty;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestClientException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;
/**
* 通用服务
*/
@Service
@Slf4j
public class CommonService {
@Tool(description = "像人类一样先思考再行动。")
public String thinkAndPlan(
@Parameter(description = "你对用户核心需求的理解") String userIntent,
@Parameter(description = "当前状态分析,包括已有信息和缺失信息") String currentSituation,
@Parameter(description = "详细的执行步骤列表,每步都要具体可执行") List<String> plan,
@Parameter(description = "基于规划确定的下一个具体行动") String nextAction
) {
try {
// 构建思考结果的字符串表示
StringBuilder result = new StringBuilder();
result.append("🤔 思考与规划结果:\n\n");
result.append("📋 用户意图理解: ").append(userIntent).append("\n\n");
result.append("🔍 当前状况分析: ").append(currentSituation).append("\n\n");
result.append("📝 执行计划:\n");
for (int i = 0; i < plan.size(); i++) {
result.append(" ").append(i + 1).append(". ").append(plan.get(i)).append("\n");
}
result.append("\n➡️ 下一步行动: ").append(nextAction);
log.info("思考规划完成: userIntent={}, steps={}", userIntent, plan.size());
return result.toString();
} catch (Exception e) {
log.error("思考规划工具执行失败", e);
throw new RuntimeException("思考规划失败: " + e.getMessage(), e);
}
}
@Tool(description = "检查函数参数。")
public String checkFunctionParameters (
@Parameter(description = "工具名称") String toolName,
@Parameter(description = "工具参数描述") String parametersDetails
) {
try {
// 构建思考结果的字符串表示
StringBuilder result = new StringBuilder();
result.append("🤔 检查函数参数:\n\n");
result.append("📋 工具名称: ").append(toolName).append("\n\n");
result.append("🔍 工具参数描述: ").append(parametersDetails).append("\n\n");
log.info("检查函数参数完成: toolName={}, parametersDetails={}");
return result.toString();
} catch (Exception e) {
log.error("检查函数参数工具执行失败", e);
throw new RuntimeException("检查函数参数失败: " + e.getMessage(), e);
}
}
public static void main(String[] args) {
CommonService client = new CommonService();
}
}
package com.glsk.service;
import com.fasterxml.jackson.databind.util.JSONPObject;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import org.springframework.web.client.RestTemplate;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.GZIPInputStream;
import java.util.zip.InflaterInputStream;
@Service
public class WeatherService {
private final String baseUrl = "https://nj59faynve.re.qweatherapi.com";
private final String apiKey = "fbe83962adc34e80885c9cac5a885d35";
@Tool(description = "通过城市Id实时获取天气")
public String getRealTimeWeather(String cityId) {
StringBuilder response = new StringBuilder();
try {
String urlString = String.format("%s/v7/weather/now?location=%s&key=%s", baseUrl, cityId, apiKey);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 设置请求属性,模拟浏览器
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
// 获取响应流并根据 Content-Encoding 判断是否需要解压缩
String encoding = connection.getContentEncoding();
BufferedReader reader;
if ("gzip".equalsIgnoreCase(encoding)) {
// 如果是 gzip 压缩,使用 GZIPInputStream 解压缩
reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream())));
} else if ("deflate".equalsIgnoreCase(encoding)) {
// 如果是 deflate 压缩,使用 InflaterInputStream 解压缩
reader = new BufferedReader(new InputStreamReader(new InflaterInputStream(connection.getInputStream())));
} else {
// 没有压缩,直接读取
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
} else {
System.out.println("GET request failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
@Tool(description = "根据城市Id获取未来三天的天气预报")
public String getForecastWeather(String cityId) {
StringBuilder response = new StringBuilder();
try {
String urlString = String.format("%s/v7/weather/3d?location=%s&key=%s", baseUrl, cityId, apiKey);
URL url = new URL(urlString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
// 设置请求属性,模拟浏览器
connection.setRequestProperty("User-Agent", "Mozilla/5.0");
connection.setRequestProperty("Accept-Encoding", "gzip,deflate");
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
// 获取响应流并根据 Content-Encoding 判断是否需要解压缩
String encoding = connection.getContentEncoding();
BufferedReader reader;
if ("gzip".equalsIgnoreCase(encoding)) {
// 如果是 gzip 压缩,使用 GZIPInputStream 解压缩
reader = new BufferedReader(new InputStreamReader(new GZIPInputStream(connection.getInputStream())));
} else if ("deflate".equalsIgnoreCase(encoding)) {
// 如果是 deflate 压缩,使用 InflaterInputStream 解压缩
reader = new BufferedReader(new InputStreamReader(new InflaterInputStream(connection.getInputStream())));
} else {
// 没有压缩,直接读取
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
}
String inputLine;
while ((inputLine = reader.readLine()) != null) {
response.append(inputLine);
}
reader.close();
System.out.println("Response Body: " + response.toString());
} else {
System.out.println("GET request failed.");
}
} catch (Exception e) {
e.printStackTrace();
}
return response.toString();
}
public static void main(String[] args) {
WeatherService weatherService = new WeatherService();
String realTimeWeather = weatherService.getRealTimeWeather("101010100");
System.out.println(realTimeWeather);
}
}
package com.glsk.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
public class TestUtil {
public static void main(String[] args) throws Exception {
// 1. 准备主题数组(与之前生成的数组一致)
String[] topicCombinations = {
"安利卖点,操作倾向",
"市场涨跌,网感词语",
"基金净值,市场涨跌,操作倾向",
"安利卖点,网感词语,基金净值",
"操作倾向,市场涨跌,安利卖点,网感词语",
"基金净值,安利卖点,操作倾向,市场涨跌",
"网感词语,基金净值,市场涨跌,操作倾向,安利卖点",
"市场涨跌,操作倾向,网感词语,基金净值",
"安利卖点,基金净值",
"操作倾向,网感词语",
"基金净值,操作倾向,安利卖点",
"网感词语,市场涨跌,基金净值",
"安利卖点,市场涨跌,操作倾向,网感词语",
"基金净值,网感词语,操作倾向,市场涨跌",
"市场涨跌,基金净值,安利卖点,操作倾向,网感词语",
"操作倾向,安利卖点",
"网感词语,安利卖点,市场涨跌",
"基金净值,市场涨跌",
"操作倾向,基金净值,网感词语,安利卖点",
"安利卖点,操作倾向,基金净值,市场涨跌,网感词语"
};
String postDate = "2025-11-19";
// 2. 创建HttpClient
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
// 3. 构建请求
String baseUrl = "http://localhost:8090/api/ai/common/post_merge_summary";
for (String theme : topicCombinations) {
String url = baseUrl + "?post_date=" + URLEncoder.encode(postDate, StandardCharsets.UTF_8.name())
+ "&themes=" + theme;
// 6. 创建POST请求(参数在URL中)
HttpPost request = new HttpPost(url);
request.setHeader("Content-Type", "application/json; charset=UTF-8");
// 7. 执行请求
try (CloseableHttpResponse response = httpClient.execute(request)) {
// 8. 处理响应
int statusCode = response.getStatusLine().getStatusCode();
String responseBody = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
System.out.println("Status: " + statusCode);
System.out.println("Response: " + responseBody);
}
}
} catch (Exception ex) {
ex.printStackTrace();
}
httpClient.close();
}
}
#spring.application.name=glsk-mcp-server
#spring.main.bannerMode=off
#spring.main.web-application-type=none
#spring.main.banner-mode=off
#logging.pattern.console=
#spring.ai.mcp.server.name=my-weather-server
#spring.ai.mcp.server.version=0.0.1
#logging.level.root=DEBUG
server.port=8090
spring.application.name=glsk-mcp-server
ai.mcp.server.name=glsk-mcp-server
ai.mcp.server.version=1.0.0
# MySQL??
#mysql.url.dj_smartcarlife=jdbc:mysql://192.168.5.23:3306/dj_smartcarlife?user=user_wangxl&password=BbuJbiPM&autoReconnect=true&autoReconnectForPools=true
mysql.url.dj_smartcarlife=jdbc:mysql://192.168.1.39:3306/dj_smartcarlife?user=wechat_user&password=b4WRTkl&autoReconnect=true&autoReconnectForPools=true
#
#mysql.url.xlyq_agi=jdbc:mysql://rm-wz9uqix4n8s738dq18o.mysql.rds.aliyuncs.com:3306/xlyq_agi?user=bool&password=v#@JrWCEH9g3&autoReconnect=true&autoReconnectForPools=true
mysql.url.xlyq_agi=jdbc:mysql://rm-wz9uqix4n8s738dq18o.mysql.rds.aliyuncs.com:3306/xlyq_agi?user=bool&password=v%23%40JrWCEH9g3&useSSL=false&serverTimezone=Asia/Shanghai&allowPublicKeyRetrieval=true&autoReconnect=true&autoReconnectForPools=true&characterEncoding=utf8mb
package com.glsk;
import com.glsk.service.MerchantAnalysisService;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class GlskMcpApplicationTests {
@Test
void contextLoads() {
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!