Compare commits
6 Commits
b5ff930556
...
feature/ma
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b3908f771f | ||
| 628925dce9 | |||
|
|
9d16b8ef3a | ||
|
|
39f68ccf46 | ||
|
|
1bf09705d1 | ||
|
|
60055dd9ed |
17
build.gradle
17
build.gradle
@@ -49,3 +49,20 @@ subprojects {
|
||||
useJUnitPlatform()
|
||||
}
|
||||
}
|
||||
|
||||
def toolCoreProject = project(':dap-tool-core')
|
||||
|
||||
tasks.register('validateMcpToolNames', JavaExec) {
|
||||
group = 'verification'
|
||||
description = 'Checks duplicate @McpFunction names across all Tool modules before packaging.'
|
||||
dependsOn toolCoreProject.tasks.named('classes')
|
||||
classpath = toolCoreProject.sourceSets.main.runtimeClasspath
|
||||
mainClass.set('io.shinhanlife.dap.lib.validation.McpToolNameValidationRunner')
|
||||
args rootProject.projectDir.absolutePath
|
||||
}
|
||||
|
||||
subprojects {
|
||||
tasks.matching { it.name == 'bootJar' }.configureEach {
|
||||
dependsOn rootProject.tasks.named('validateMcpToolNames')
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>AX HUB - ChatClient</title>
|
||||
<script src="https://unpkg.com/@tailwindcss/browser@4"></script>
|
||||
<script src="/vendor/marked.umd.js"></script>
|
||||
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap" rel="stylesheet">
|
||||
<style>
|
||||
body { font-family: 'Inter', sans-serif; background-color: #0f1115; color: #e2e8f0; }
|
||||
@@ -25,6 +26,20 @@
|
||||
0%, 100% { transform: translateY(0); }
|
||||
50% { transform: translateY(-3px); }
|
||||
}
|
||||
|
||||
.markdown-content > :first-child { margin-top: 0; }
|
||||
.markdown-content > :last-child { margin-bottom: 0; }
|
||||
.markdown-content p { margin: 0.5rem 0; }
|
||||
.markdown-content ul, .markdown-content ol { margin: 0.5rem 0; padding-left: 1.5rem; }
|
||||
.markdown-content ul { list-style: disc; }
|
||||
.markdown-content ol { list-style: decimal; }
|
||||
.markdown-content a { color: #6ee7b7; text-decoration: underline; }
|
||||
.markdown-content code { padding: 0.125rem 0.3rem; border-radius: 0.25rem; background: #0f1115; color: #f1f5f9; }
|
||||
.markdown-content pre { margin: 0.75rem 0; padding: 0.75rem; overflow-x: auto; border-radius: 0.5rem; background: #0f1115; }
|
||||
.markdown-content pre code { padding: 0; background: transparent; }
|
||||
.markdown-content blockquote { margin: 0.5rem 0; padding-left: 0.75rem; border-left: 3px solid #34d399; color: #cbd5e1; }
|
||||
.markdown-content table { width: 100%; margin: 0.5rem 0; border-collapse: collapse; }
|
||||
.markdown-content th, .markdown-content td { padding: 0.4rem; border: 1px solid #475569; text-align: left; }
|
||||
</style>
|
||||
</head>
|
||||
<body class="h-screen flex flex-col items-center justify-center p-4">
|
||||
@@ -150,7 +165,7 @@
|
||||
</div>
|
||||
<div class="flex flex-col gap-1 max-w-[80%]">
|
||||
<span class="text-xs text-slate-500 ml-1 font-medium">Assistant</span>
|
||||
<div class="bg-[#1e2128] px-5 py-3.5 rounded-2xl rounded-tl-sm text-sm text-slate-200 leading-relaxed border border-white/5 shadow-sm whitespace-pre-wrap bot-text"></div>
|
||||
<div class="bg-[#1e2128] px-5 py-3.5 rounded-2xl rounded-tl-sm text-sm text-slate-200 leading-relaxed border border-white/5 shadow-sm markdown-content bot-text"></div>
|
||||
</div>
|
||||
`;
|
||||
chatBox.appendChild(div);
|
||||
@@ -184,6 +199,61 @@
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
function sanitizeRenderedHtml(html) {
|
||||
const template = document.createElement('template');
|
||||
template.innerHTML = html;
|
||||
template.content.querySelectorAll('script, iframe, object, embed, style, link, meta').forEach(element => element.remove());
|
||||
template.content.querySelectorAll('*').forEach(element => {
|
||||
[...element.attributes].forEach(attribute => {
|
||||
const name = attribute.name.toLowerCase();
|
||||
const value = attribute.value.trim();
|
||||
if (name.startsWith('on') || name === 'style' ||
|
||||
(['href', 'src', 'xlink:href'].includes(name) && /^(javascript|data|vbscript):/i.test(value))) {
|
||||
element.removeAttribute(attribute.name);
|
||||
}
|
||||
});
|
||||
});
|
||||
return template.innerHTML;
|
||||
}
|
||||
|
||||
function normalizeMarkdown(markdown) {
|
||||
// 일부 모델은 문단 뒤의 제목 표기(예: "설명입니다.## 제목") 앞 줄바꿈을 생략한다.
|
||||
// 또한 "###제목", "###📝 제목"처럼 해시 뒤 공백을 생략하는 출력도 제목으로 보정한다.
|
||||
return markdown
|
||||
.replace(/\r\n?/g, '\n')
|
||||
.replace(/([^\n])((?:#{1,6})\s+)/g, '$1\n$2')
|
||||
.replace(/(^|\n)(#{1,6})([^\s#])/g, '$1$2 $3');
|
||||
}
|
||||
|
||||
function renderMarkdown(container, markdown) {
|
||||
// 프로젝트에 포함한 표준 GFM 렌더러가 제목, 강조, 표, 목록, 코드, 링크 등을 일괄 처리한다.
|
||||
const normalizedMarkdown = normalizeMarkdown(markdown);
|
||||
if (typeof marked !== 'undefined') {
|
||||
const html = marked.parse(normalizedMarkdown, { breaks: true, gfm: true });
|
||||
container.innerHTML = sanitizeRenderedHtml(html);
|
||||
return;
|
||||
}
|
||||
|
||||
// 로컬 라이브러리 로딩에 실패한 경우에는 안전한 일반 텍스트로 표시한다.
|
||||
container.textContent = normalizedMarkdown;
|
||||
}
|
||||
|
||||
function consumeSseEvents(buffer, onData) {
|
||||
// Spring SSE는 응답 본문의 줄바꿈을 여러 data: 줄로 전송한다.
|
||||
// data 줄을 단순 연결하면 Markdown 표의 행 구분이 사라지므로, 이벤트 단위로 복원한다.
|
||||
let eventEnd;
|
||||
while ((eventEnd = buffer.indexOf('\n\n')) !== -1) {
|
||||
const event = buffer.substring(0, eventEnd);
|
||||
buffer = buffer.substring(eventEnd + 2);
|
||||
const dataLines = event.split('\n')
|
||||
.filter(line => line.startsWith('data:'))
|
||||
.map(line => line.substring(5));
|
||||
|
||||
if (dataLines.length > 0) onData(dataLines.join('\n'));
|
||||
}
|
||||
return buffer;
|
||||
}
|
||||
|
||||
async function sendMessage() {
|
||||
const text = chatInput.value.trim();
|
||||
if (!text || isLoading) return;
|
||||
@@ -214,24 +284,24 @@
|
||||
// 4. 로딩 숨기고 봇 응답 컨테이너 생성
|
||||
hideLoading();
|
||||
const textContainer = appendBotMessageContainer();
|
||||
let responseText = '';
|
||||
|
||||
// 5. 스트림 읽기
|
||||
const reader = response.body.getReader();
|
||||
const decoder = new TextDecoder("utf-8");
|
||||
let sseBuffer = '';
|
||||
|
||||
const appendResponse = (data) => {
|
||||
responseText += data;
|
||||
renderMarkdown(textContainer, responseText);
|
||||
scrollToBottom();
|
||||
};
|
||||
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
sseBuffer += decoder.decode(value || new Uint8Array(), { stream: !done }).replace(/\r\n/g, '\n');
|
||||
sseBuffer = consumeSseEvents(sseBuffer, appendResponse);
|
||||
if (done) break;
|
||||
|
||||
const chunk = decoder.decode(value, { stream: true });
|
||||
const lines = chunk.split('\n');
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data:')) {
|
||||
const data = line.substring(5);
|
||||
textContainer.innerHTML += escapeHtml(data);
|
||||
scrollToBottom();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
|
||||
44
dap-gateway/src/main/resources/static/vendor/MARKED-LICENSE.md
vendored
Normal file
44
dap-gateway/src/main/resources/static/vendor/MARKED-LICENSE.md
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
# License information
|
||||
|
||||
## Contribution License Agreement
|
||||
|
||||
If you contribute code to this project, you are implicitly allowing your code
|
||||
to be distributed under the MIT license. You are also implicitly verifying that
|
||||
all code is your original work. `</legalese>`
|
||||
|
||||
## Marked
|
||||
|
||||
Copyright (c) 2018+, MarkedJS (https://github.com/markedjs/)
|
||||
Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
## Markdown
|
||||
|
||||
Copyright © 2004, John Gruber
|
||||
http://daringfireball.net/
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
|
||||
74
dap-gateway/src/main/resources/static/vendor/marked.umd.js
vendored
Normal file
74
dap-gateway/src/main/resources/static/vendor/marked.umd.js
vendored
Normal file
File diff suppressed because one or more lines are too long
@@ -0,0 +1,21 @@
|
||||
package io.shinhanlife.dap.lib.validation;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
/** Gradle entry point for validating unique MCP Tool names before packaging. */
|
||||
public final class McpToolNameValidationRunner {
|
||||
|
||||
private McpToolNameValidationRunner() {
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
if (args.length != 1) {
|
||||
throw new IllegalArgumentException("Usage: McpToolNameValidationRunner <project-root>");
|
||||
}
|
||||
validate(Path.of(args[0]));
|
||||
}
|
||||
|
||||
static void validate(Path projectRoot) {
|
||||
McpToolNameValidator.assertUnique(projectRoot);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package io.shinhanlife.dap.mcc.mcp;
|
||||
|
||||
/** Holds optional MCP headers for the lifetime of one HTTP request thread. */
|
||||
public final class McpRequestHeaderContext {
|
||||
private static final ThreadLocal<McpRequestHeaders> CURRENT_HEADERS = new ThreadLocal<>();
|
||||
|
||||
private McpRequestHeaderContext() {
|
||||
}
|
||||
|
||||
public static McpRequestHeaders current() {
|
||||
return CURRENT_HEADERS.get();
|
||||
}
|
||||
|
||||
static void set(McpRequestHeaders headers) {
|
||||
CURRENT_HEADERS.set(headers);
|
||||
}
|
||||
|
||||
static void clear() {
|
||||
CURRENT_HEADERS.remove();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package io.shinhanlife.dap.mcc.mcp;
|
||||
|
||||
import java.io.IOException;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
|
||||
/** Captures optional correlation and employee headers for an MCP HTTP call. */
|
||||
@Component
|
||||
public class McpRequestHeaderFilter extends OncePerRequestFilter {
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(HttpServletRequest request) {
|
||||
return !request.getRequestURI().endsWith("/mcp");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
|
||||
FilterChain filterChain) throws ServletException, IOException {
|
||||
McpRequestHeaderContext.set(new McpRequestHeaders(
|
||||
request.getHeader("X-Request-Id"),
|
||||
request.getHeader("trace-id"),
|
||||
request.getHeader("request-id"),
|
||||
request.getHeader("employee-id")));
|
||||
try {
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
McpRequestHeaderContext.clear();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package io.shinhanlife.dap.mcc.mcp;
|
||||
|
||||
/** Optional request headers propagated from an MCP HTTP request to a Tool invocation. */
|
||||
public record McpRequestHeaders(
|
||||
String headerRequestId,
|
||||
String traceId,
|
||||
String requestId,
|
||||
String encryptedEmployeeId) {
|
||||
}
|
||||
@@ -49,11 +49,18 @@ public class ToolPodMcpToolSynchronizer {
|
||||
.openWorldHint(Boolean.TRUE.equals(tool.getOpenWorldHint())).build())
|
||||
.build();
|
||||
return McpServerFeatures.SyncToolSpecification.builder().tool(mcpTool)
|
||||
.callHandler((context, request) -> invoke(tool.getName(), request.arguments())).build();
|
||||
.callHandler((context, request) -> invoke(tool.getName(), McpRequestHeaderContext.current(), request.arguments())).build();
|
||||
}
|
||||
|
||||
private McpSchema.CallToolResult invoke(String toolName, Map<String, Object> arguments) {
|
||||
ResponseEntity<?> response = businessToolController.executeDynamicTool(toolName, null, null, null, arguments);
|
||||
private McpSchema.CallToolResult invoke(String toolName, McpRequestHeaders requestHeaders,
|
||||
Map<String, Object> arguments) {
|
||||
ResponseEntity<?> response = businessToolController.executeDynamicTool(
|
||||
toolName,
|
||||
requestHeaders == null ? null : requestHeaders.headerRequestId(),
|
||||
requestHeaders == null ? null : requestHeaders.traceId(),
|
||||
requestHeaders == null ? null : requestHeaders.requestId(),
|
||||
requestHeaders == null ? null : requestHeaders.encryptedEmployeeId(),
|
||||
arguments);
|
||||
boolean failed = !response.getStatusCode().is2xxSuccessful();
|
||||
Object body = response.getBody();
|
||||
try {
|
||||
|
||||
@@ -70,6 +70,7 @@ public class BusinessToolController {
|
||||
@RequestHeader(value = "X-Request-Id", required = false) String headerRequestId,
|
||||
@RequestHeader(value = "trace-id", required = false) String traceId,
|
||||
@RequestHeader(value = "request-id", required = false) String requestId,
|
||||
@RequestHeader(value = "employee-id", required = false) String encryptedEmployeeId,
|
||||
@RequestBody(required = false) Map<String, Object> arguments) {
|
||||
|
||||
String finalRequestId = headerRequestId;
|
||||
|
||||
@@ -42,6 +42,15 @@ class McpToolNameValidatorTest {
|
||||
assertTrue(exception.getMessage().contains("dap-tool-second"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void validationRunnerRejectsDuplicateMcpFunctionNamesBeforePackaging() throws IOException {
|
||||
writeToolSource("dap-tool-first", "FirstTool.java", "first", "send_sms");
|
||||
writeToolSource("dap-tool-second", "SecondTool.java", "second", "send_sms");
|
||||
|
||||
assertThrows(IllegalStateException.class,
|
||||
() -> McpToolNameValidationRunner.validate(temporaryRoot));
|
||||
}
|
||||
|
||||
@Test
|
||||
void acceptsCurrentProjectToolNames() {
|
||||
assertDoesNotThrow(() -> McpToolNameValidator.assertUnique(findProjectRoot()));
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
package io.shinhanlife.dap.mcc.mcp;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.doReturn;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.modelcontextprotocol.server.McpSyncServer;
|
||||
import io.shinhanlife.dap.mcc.presentation.BusinessToolController;
|
||||
import io.shinhanlife.dap.mcc.usecase.ToolRegistryHeartbeatSender;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Map;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.mock.web.MockHttpServletRequest;
|
||||
import org.springframework.mock.web.MockHttpServletResponse;
|
||||
|
||||
class McpRequestHeaderFilterTest {
|
||||
|
||||
@Test
|
||||
void capturesOptionalMcpHeadersOnlyForTheCurrentRequest() throws Exception {
|
||||
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/mcp");
|
||||
request.addHeader("X-Request-Id", "gateway-request-id");
|
||||
request.addHeader("trace-id", "trace-001");
|
||||
request.addHeader("request-id", "tool-request-001");
|
||||
request.addHeader("employee-id", "encrypted-employee-id");
|
||||
|
||||
new McpRequestHeaderFilter().doFilter(request, new MockHttpServletResponse(), (req, res) -> {
|
||||
McpRequestHeaders headers = McpRequestHeaderContext.current();
|
||||
assertEquals("gateway-request-id", headers.headerRequestId());
|
||||
assertEquals("trace-001", headers.traceId());
|
||||
assertEquals("tool-request-001", headers.requestId());
|
||||
assertEquals("encrypted-employee-id", headers.encryptedEmployeeId());
|
||||
});
|
||||
|
||||
assertNull(McpRequestHeaderContext.current());
|
||||
}
|
||||
|
||||
@Test
|
||||
void forwardsCapturedHeadersToBusinessToolExecution() throws Exception {
|
||||
BusinessToolController controller = mock(BusinessToolController.class);
|
||||
doReturn(ResponseEntity.ok(Map.of("result", "ok")))
|
||||
.when(controller).executeDynamicTool(eq("sampleTool"), eq("gateway-request-id"), eq("trace-001"),
|
||||
eq("tool-request-001"), eq("encrypted-employee-id"), eq(Map.of("key", "value")));
|
||||
ToolPodMcpToolSynchronizer synchronizer = new ToolPodMcpToolSynchronizer(
|
||||
mock(McpSyncServer.class), mock(ToolRegistryHeartbeatSender.class), controller, new ObjectMapper());
|
||||
|
||||
Method invoke = ToolPodMcpToolSynchronizer.class.getDeclaredMethod(
|
||||
"invoke", String.class, McpRequestHeaders.class, Map.class);
|
||||
invoke.setAccessible(true);
|
||||
invoke.invoke(synchronizer, "sampleTool",
|
||||
new McpRequestHeaders("gateway-request-id", "trace-001", "tool-request-001", "encrypted-employee-id"),
|
||||
Map.of("key", "value"));
|
||||
|
||||
verify(controller).executeDynamicTool("sampleTool", "gateway-request-id", "trace-001",
|
||||
"tool-request-001", "encrypted-employee-id", Map.of("key", "value"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
package io.shinhanlife.dap.mcc.presentation;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Parameter;
|
||||
import java.util.Map;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
|
||||
class BusinessToolControllerHeaderContractTest {
|
||||
|
||||
@Test
|
||||
void encryptedEmployeeIdHeaderIsOptional() throws Exception {
|
||||
Method method = BusinessToolController.class.getDeclaredMethod(
|
||||
"executeDynamicTool",
|
||||
String.class,
|
||||
String.class,
|
||||
String.class,
|
||||
String.class,
|
||||
String.class,
|
||||
Map.class);
|
||||
|
||||
Parameter employeeIdParameter = method.getParameters()[4];
|
||||
RequestHeader requestHeader = employeeIdParameter.getAnnotation(RequestHeader.class);
|
||||
|
||||
assertEquals("employee-id", requestHeader.value());
|
||||
assertFalse(requestHeader.required());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user