[Developer] #424 add Java MCP client demo tab

This commit is contained in:
devmrko
2026-06-25 15:38:17 +09:00
parent 8bc89ee3dc
commit cfad317d73
6 changed files with 341 additions and 0 deletions

View File

@@ -0,0 +1,12 @@
package com.cloudhandson.vpdbackoffice.domain.mcp;
public record McpClientDemoResult(
String contextPath,
String messageUrl,
String selectedTool,
String initializeResponse,
String toolsListResponse,
String toolsCallResponse,
String status
) {
}

View File

@@ -0,0 +1,144 @@
package com.cloudhandson.vpdbackoffice.service;
import com.cloudhandson.vpdbackoffice.config.BackofficeProperties;
import com.cloudhandson.vpdbackoffice.domain.mcp.McpClientDemoResult;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import java.net.URI;
import java.time.Duration;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
@Service
public class McpClientDemoService {
private final BackofficeProperties properties;
private final ObjectMapper objectMapper;
private final RestTemplate restTemplate;
public McpClientDemoService(
BackofficeProperties properties,
ObjectMapper objectMapper,
RestTemplateBuilder restTemplateBuilder
) {
this.properties = properties;
this.objectMapper = objectMapper;
this.restTemplate = restTemplateBuilder
.setConnectTimeout(Duration.ofSeconds(5))
.setReadTimeout(Duration.ofSeconds(15))
.build();
}
public McpClientDemoResult run(
String serverOrigin,
String contextPath,
String toolName,
String bearerToken,
int limit
) {
String normalizedContextPath = normalizeContextPath(contextPath);
URI messageUri = messageUri(serverOrigin, normalizedContextPath);
JsonNode initializeResponse = post(messageUri, initializeRequest(1));
JsonNode toolsListResponse = post(messageUri, toolsListRequest(2));
JsonNode toolsCallResponse = null;
if (hasText(toolName) && hasText(bearerToken)) {
toolsCallResponse = post(messageUri, toolsCallRequest(3, toolName.trim(), bearerToken.trim(), normalizeLimit(limit)));
}
return new McpClientDemoResult(
normalizedContextPath,
messageUri.toString(),
hasText(toolName) ? toolName.trim() : "",
pretty(initializeResponse),
pretty(toolsListResponse),
toolsCallResponse == null ? "Bearer Token이 없어 tools/call은 실행하지 않았습니다." : pretty(toolsCallResponse),
toolsCallResponse == null ? "TOOLS_LIST_ONLY" : "SUCCESS"
);
}
private JsonNode post(URI uri, ObjectNode request) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setBasicAuth(properties.security().adminUser(), properties.security().adminPassword());
String response = restTemplate.postForObject(uri, new HttpEntity<>(request, headers), String.class);
try {
return objectMapper.readTree(response);
} catch (Exception e) {
throw new AppException("MCP client 응답 JSON 파싱 실패: " + e.getMessage());
}
}
private URI messageUri(String serverOrigin, String contextPath) {
String path = "default".equals(contextPath) ? "/mcp/messages" : "/mcp/" + contextPath + "/messages";
return UriComponentsBuilder.fromUriString(serverOrigin)
.path(path)
.build()
.toUri();
}
private ObjectNode initializeRequest(int id) {
ObjectNode request = request(id, "initialize");
request.set("params", objectMapper.createObjectNode());
return request;
}
private ObjectNode toolsListRequest(int id) {
ObjectNode request = request(id, "tools/list");
request.set("params", objectMapper.createObjectNode());
return request;
}
private ObjectNode toolsCallRequest(int id, String toolName, String bearerToken, int limit) {
ObjectNode request = request(id, "tools/call");
ObjectNode params = objectMapper.createObjectNode();
params.put("name", toolName);
ObjectNode arguments = objectMapper.createObjectNode();
arguments.put("bearerToken", bearerToken);
arguments.put("limit", limit);
params.set("arguments", arguments);
request.set("params", params);
return request;
}
private ObjectNode request(int id, String method) {
ObjectNode request = objectMapper.createObjectNode();
request.put("jsonrpc", "2.0");
request.put("id", id);
request.put("method", method);
return request;
}
private String normalizeContextPath(String contextPath) {
String normalized = contextPath == null || contextPath.isBlank() ? "default" : contextPath.trim();
if (!normalized.matches("[A-Za-z0-9][A-Za-z0-9_-]{0,63}")) {
throw new AppException("MCP context path는 영문/숫자로 시작하고 영문/숫자/_/-만 사용할 수 있습니다: " + contextPath);
}
return normalized.toLowerCase();
}
private int normalizeLimit(int limit) {
if (limit < 1) {
return 50;
}
return Math.min(limit, 500);
}
private boolean hasText(String value) {
return value != null && !value.isBlank();
}
private String pretty(JsonNode node) {
try {
return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(node);
} catch (Exception e) {
return String.valueOf(node);
}
}
}

View File

@@ -0,0 +1,64 @@
package com.cloudhandson.vpdbackoffice.web;
import com.cloudhandson.vpdbackoffice.service.McpClientDemoService;
import com.cloudhandson.vpdbackoffice.service.McpToolRegistry;
import jakarta.servlet.http.HttpServletRequest;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
@Controller
public class McpClientDemoController {
private final McpToolRegistry toolRegistry;
private final McpClientDemoService demoService;
public McpClientDemoController(McpToolRegistry toolRegistry, McpClientDemoService demoService) {
this.toolRegistry = toolRegistry;
this.demoService = demoService;
}
@GetMapping("/mcp-client-demo")
public String page(Model model) {
addTools(model);
return "mcp-client-demo";
}
@PostMapping("/mcp-client-demo")
public String run(
@RequestParam(defaultValue = "vpd-live") String contextPath,
@RequestParam(defaultValue = "") String toolName,
@RequestParam(defaultValue = "") String bearerToken,
@RequestParam(defaultValue = "50") int limit,
HttpServletRequest request,
Model model
) {
addTools(model);
try {
String serverOrigin = ServletUriComponentsBuilder.fromRequestUri(request)
.replacePath(null)
.replaceQuery(null)
.build()
.toUriString();
model.addAttribute("result", demoService.run(serverOrigin, contextPath, toolName, bearerToken, limit));
} catch (Exception e) {
model.addAttribute("errorMessage", e.getMessage());
}
return "fragments/mcp-client-demo-result :: result";
}
private void addTools(Model model) {
try {
model.addAttribute("tools", toolRegistry.listTools());
} catch (DataAccessException e) {
RuntimeErrorMessage message = RuntimeErrorMessages.dataAccess(e);
model.addAttribute("tools", List.of());
model.addAttribute("runtimeError", message);
}
}
}

View File

@@ -37,6 +37,7 @@
<div class="rw-menu-panel"> <div class="rw-menu-panel">
<a class="nav-link" href="/mcp-reasoning">Reasoning</a> <a class="nav-link" href="/mcp-reasoning">Reasoning</a>
<a class="nav-link" href="/mcp-sse">SSE 서비스</a> <a class="nav-link" href="/mcp-sse">SSE 서비스</a>
<a class="nav-link" href="/mcp-client-demo">Client Demo</a>
</div> </div>
</div> </div>
<div class="rw-menu-group"> <div class="rw-menu-group">

View File

@@ -0,0 +1,44 @@
<!doctype html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<body>
<div th:fragment="result">
<div class="alert alert-danger" th:if="${errorMessage}">
<strong>Java MCP client 호출 실패</strong>
<div th:text="${errorMessage}">error</div>
</div>
<div th:if="${result}">
<div class="section-heading">
<h2>Java Client 결과</h2>
<span class="badge"
th:classappend="${result.status() == 'SUCCESS'} ? ' text-bg-success' : ' text-bg-secondary'"
th:text="${result.status()}">SUCCESS</span>
</div>
<dl class="policy-detail-list">
<dt>Context Path</dt>
<dd><code th:text="${result.contextPath()}">vpd-live</code></dd>
<dt>Message URL</dt>
<dd><code th:text="${result.messageUrl()}">http://localhost:8082/mcp/vpd-live/messages</code></dd>
<dt>Selected Tool</dt>
<dd><code th:text="${result.selectedTool()} ?: '-'">tool</code></dd>
</dl>
<div class="probe-exchange-grid">
<section class="probe-exchange">
<h3>initialize Response</h3>
<pre th:text="${result.initializeResponse()}">{}</pre>
</section>
<section class="probe-exchange">
<h3>tools/list Response</h3>
<pre th:text="${result.toolsListResponse()}">{}</pre>
</section>
<section class="probe-exchange">
<h3>tools/call Response</h3>
<pre th:text="${result.toolsCallResponse()}">{}</pre>
</section>
</div>
</div>
</div>
</body>
</html>

View File

@@ -0,0 +1,76 @@
<!doctype html>
<html lang="ko" xmlns:th="http://www.thymeleaf.org">
<head th:replace="~{fragments/layout :: head('MCP Client Demo')}"></head>
<body>
<nav th:replace="~{fragments/layout :: nav}"></nav>
<main class="container page-shell">
<section class="page-heading">
<h1>MCP Client Demo</h1>
<p>백오피스 Java client가 MCP message endpoint를 호출해 initialize, tools/list, tools/call 결과를 확인합니다.</p>
</section>
<section th:if="${runtimeError}" class="alert alert-warning">
<strong th:text="${runtimeError.title()}">DB 연결 설정이 필요합니다.</strong>
<div th:text="${runtimeError.message()}">DB 연결을 확인할 수 없습니다.</div>
</section>
<section class="content-band">
<h2>Java Client 호출</h2>
<form hx-post="/mcp-client-demo" hx-target="#mcp-client-demo-result" hx-swap="innerHTML" class="form-grid">
<input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}">
<label>
Context Path
<input class="form-control" name="contextPath" value="vpd-live" pattern="[A-Za-z0-9][A-Za-z0-9_-]{0,63}" required>
</label>
<label>
Tool
<select class="form-select" name="toolName">
<option value="">tools/list만 실행</option>
<option th:each="tool : ${tools}"
th:value="${tool.name()}"
th:text="${tool.name() + ' / ' + tool.displayName()}"></option>
</select>
</label>
<label>
Limit
<input class="form-control" name="limit" type="number" min="1" max="500" value="50">
</label>
<label class="span-2">
Bearer Token 원문
<input class="form-control" name="bearerToken" type="password" autocomplete="off"
placeholder="비우면 tools/call은 실행하지 않습니다.">
</label>
<button class="btn rw-btn-primary" type="submit">Java Client 실행</button>
</form>
</section>
<section class="content-band">
<div class="section-heading">
<h2>호출 흐름</h2>
<span class="badge text-bg-secondary">HTTP JSON-RPC</span>
</div>
<div class="mcp-service-grid">
<div class="mcp-service-item">
<span>1</span>
<strong><code>initialize</code></strong>
<small>context path가 반영된 MCP serverInfo와 tools capability를 확인합니다.</small>
</div>
<div class="mcp-service-item">
<span>2</span>
<strong><code>tools/list</code></strong>
<small>현재 보호 객체에서 생성된 ORDS query tool 목록을 조회합니다.</small>
</div>
<div class="mcp-service-item">
<span>3</span>
<strong><code>tools/call</code></strong>
<small>Bearer Token이 입력된 경우 선택한 tool을 호출해 ORDS/VPD 결과를 받습니다.</small>
</div>
</div>
</section>
<section id="mcp-client-demo-result" class="content-band">
<div class="text-muted">Java MCP client 실행 결과가 여기에 표시됩니다.</div>
</section>
</main>
</body>
</html>