refs #732: add dynamic HMM HTML report MCP tool
This commit is contained in:
@@ -2633,6 +2633,14 @@ def _mcp_response_payload(mcp_result: Any) -> Mapping[str, Any]:
|
||||
if isinstance(mcp_result, Mapping):
|
||||
response = mcp_result.get("response")
|
||||
if isinstance(response, Mapping):
|
||||
nested_result = response.get("result")
|
||||
if isinstance(nested_result, str):
|
||||
try:
|
||||
parsed = json.loads(nested_result)
|
||||
except ValueError:
|
||||
parsed = None
|
||||
if isinstance(parsed, Mapping):
|
||||
return parsed
|
||||
return response
|
||||
return mcp_result
|
||||
return {}
|
||||
@@ -2643,6 +2651,19 @@ def _mcp_generated_sql(mcp_result: Any) -> str:
|
||||
return str(payload.get("generatedSql") or payload.get("generated_sql") or "").strip()
|
||||
|
||||
|
||||
def _mcp_rendered_html(mcp_result: Any) -> str:
|
||||
"""Extract an HTML artifact without coupling the UI to a tool name."""
|
||||
|
||||
payload = _mcp_response_payload(mcp_result)
|
||||
candidate = payload.get("html") or payload.get("rendered_html")
|
||||
if not isinstance(candidate, str):
|
||||
return ""
|
||||
html_text = candidate.strip()
|
||||
if len(html_text) > 1_000_000 or "<" not in html_text or ">" not in html_text:
|
||||
return ""
|
||||
return html_text
|
||||
|
||||
|
||||
def _mcp_items(mcp_result: Any) -> list[Any]:
|
||||
payload = _mcp_response_payload(mcp_result)
|
||||
items = payload.get("items")
|
||||
@@ -2692,11 +2713,91 @@ def _agent_tool_catalog(
|
||||
if isinstance(properties, Mapping)
|
||||
else [],
|
||||
"read_only": route.tool.read_only,
|
||||
"consumes_previous_result": _is_presentation_route(route),
|
||||
}
|
||||
)
|
||||
return catalog, routes
|
||||
|
||||
|
||||
def _is_presentation_route(route: RoutedMcpTool) -> bool:
|
||||
"""Identify a renderer from its discovered description and input schema."""
|
||||
|
||||
properties = route.tool.schema.get("properties")
|
||||
names = (
|
||||
[str(name).casefold() for name in properties]
|
||||
if isinstance(properties, Mapping)
|
||||
else []
|
||||
)
|
||||
has_payload_input = any(
|
||||
any(marker in name for marker in ("report", "payload", "render_data"))
|
||||
and any(marker in name for marker in ("json", "data", "payload"))
|
||||
for name in names
|
||||
)
|
||||
description = f"{route.tool.name} {route.tool.description}".casefold()
|
||||
has_presentation_intent = any(
|
||||
marker in description
|
||||
for marker in ("render", "html", "dashboard", "presentation", "report")
|
||||
)
|
||||
has_prior_result_contract = any(
|
||||
marker in description
|
||||
for marker in (
|
||||
"supplied",
|
||||
"already-authorized",
|
||||
"previous result",
|
||||
"input data",
|
||||
"후속 처리",
|
||||
"조회 결과",
|
||||
"선행 결과",
|
||||
)
|
||||
)
|
||||
return has_payload_input and has_presentation_intent and has_prior_result_contract
|
||||
|
||||
|
||||
def _question_requests_presentation(question: str) -> bool:
|
||||
text = str(question or "").casefold()
|
||||
return any(
|
||||
marker in text
|
||||
for marker in (
|
||||
"리포트",
|
||||
"보고서",
|
||||
"대시보드",
|
||||
"차트",
|
||||
"그래프",
|
||||
"html",
|
||||
"화면으로 만들어",
|
||||
"문서로 만들어",
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def _presentation_route(
|
||||
routes_by_key: Mapping[str, RoutedMcpTool],
|
||||
attempted_route_keys: set[str],
|
||||
) -> tuple[str, RoutedMcpTool] | None:
|
||||
return next(
|
||||
(
|
||||
(key, route)
|
||||
for key, route in routes_by_key.items()
|
||||
if key not in attempted_route_keys and _is_presentation_route(route)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _primary_data_route(
|
||||
routes_by_key: Mapping[str, RoutedMcpTool],
|
||||
attempted_route_keys: set[str],
|
||||
) -> tuple[str, RoutedMcpTool] | None:
|
||||
return next(
|
||||
(
|
||||
(key, route)
|
||||
for key, route in routes_by_key.items()
|
||||
if key not in attempted_route_keys and not _is_presentation_route(route)
|
||||
),
|
||||
None,
|
||||
)
|
||||
|
||||
|
||||
def _complex_reasoning_model_profile(default_model_profile: str) -> str:
|
||||
configured = (
|
||||
os.environ.get(COMPLEX_REASONING_MODEL_PROFILE_ENV)
|
||||
@@ -2740,6 +2841,120 @@ def _clean_agent_tool_query(value: object, fallback: str) -> str:
|
||||
return " ".join(cleaned).strip() or fallback
|
||||
|
||||
|
||||
def _camel_case_key(value: object) -> str:
|
||||
text = str(value or "")
|
||||
if "_" not in text:
|
||||
return text[:1].lower() + text[1:]
|
||||
parts = [part for part in text.casefold().split("_") if part]
|
||||
return (
|
||||
parts[0] + "".join(part[:1].upper() + part[1:] for part in parts[1:])
|
||||
if parts
|
||||
else text
|
||||
)
|
||||
|
||||
|
||||
def _normalize_presentation_value(value: Any) -> Any:
|
||||
if isinstance(value, Mapping):
|
||||
return {
|
||||
_camel_case_key(key): _normalize_presentation_value(item)
|
||||
for key, item in value.items()
|
||||
}
|
||||
if isinstance(value, list):
|
||||
return [_normalize_presentation_value(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
def _presentation_payload(question: str, steps: list[Mapping[str, Any]]) -> dict[str, Any]:
|
||||
"""Build a renderer payload only from the preceding authorized tool result."""
|
||||
|
||||
source = next(
|
||||
(
|
||||
step
|
||||
for step in reversed(steps)
|
||||
if not bool(step.get("consumes_previous_result"))
|
||||
),
|
||||
{},
|
||||
)
|
||||
raw_result = source.get("mcp_result", {}) if isinstance(source, Mapping) else {}
|
||||
payload = _mcp_response_payload(raw_result)
|
||||
source_rows = _mcp_items(raw_result)
|
||||
if not source_rows:
|
||||
for key in ("results", "rows"):
|
||||
candidate = payload.get(key) if isinstance(payload, Mapping) else None
|
||||
if isinstance(candidate, list):
|
||||
source_rows = candidate
|
||||
break
|
||||
rows = [
|
||||
_normalize_presentation_value(row)
|
||||
for row in source_rows
|
||||
if isinstance(row, Mapping)
|
||||
]
|
||||
requester = re.search(r"\bE\d{4,}\b", str(question or ""), flags=re.IGNORECASE)
|
||||
source_tool = str(source.get("tool_name") or "MCP data query")
|
||||
return {
|
||||
"report": {
|
||||
"id": "MCP-REPORT",
|
||||
"category": "MCP Business Intelligence",
|
||||
"title": str(question or "MCP 결과 리포트"),
|
||||
"question": str(question or ""),
|
||||
"requestedBy": requester.group(0).upper() if requester else "-",
|
||||
"generatedAt": datetime.now(timezone.utc).isoformat(),
|
||||
"answer": (
|
||||
f"{source_tool}에서 권한 범위 내 결과 {len(rows)}건을 받아 "
|
||||
"리포트로 구성했습니다."
|
||||
),
|
||||
"execution": {
|
||||
"server": str(source.get("server_id") or ""),
|
||||
"tool": source_tool,
|
||||
"calls": len(steps) + 1,
|
||||
},
|
||||
"evidence": [f"MCP {source_tool} 결과 {len(rows)}건 반환"],
|
||||
"limitation": "표시 값은 선행 MCP 데이터 조회 결과만 사용했습니다.",
|
||||
},
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def _build_mcp_arguments(
|
||||
*,
|
||||
route: RoutedMcpTool,
|
||||
tool_query: str,
|
||||
limit: int,
|
||||
preferred_tool: str,
|
||||
steps: list[Mapping[str, Any]],
|
||||
) -> dict[str, Any]:
|
||||
if not _is_presentation_route(route):
|
||||
return build_mcp_tool_arguments(
|
||||
route.tool,
|
||||
tool_query,
|
||||
int(limit),
|
||||
preferred_tool=preferred_tool,
|
||||
)
|
||||
properties = route.tool.schema.get("properties")
|
||||
if not isinstance(properties, Mapping):
|
||||
raise McpToolRouterError("렌더링 MCP tool의 입력 스키마가 없습니다.")
|
||||
input_name = next(
|
||||
(
|
||||
str(name)
|
||||
for name in properties
|
||||
if "report" in str(name).casefold()
|
||||
and any(
|
||||
marker in str(name).casefold()
|
||||
for marker in ("json", "payload", "data")
|
||||
)
|
||||
),
|
||||
"",
|
||||
)
|
||||
if not input_name:
|
||||
raise McpToolRouterError("렌더링 MCP tool이 report payload 입력을 선언하지 않았습니다.")
|
||||
return {
|
||||
input_name: json.dumps(
|
||||
_presentation_payload(tool_query, steps),
|
||||
ensure_ascii=False,
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
def _mcp_has_actionable_result(mcp_result: Any) -> bool:
|
||||
if _mcp_generated_sql(mcp_result) or _mcp_items(mcp_result):
|
||||
return True
|
||||
@@ -3231,6 +3446,29 @@ def plan_mcp_execution_mode(
|
||||
"reason": f"사용자 선택: {override}",
|
||||
"model_profile": "",
|
||||
}
|
||||
presentation_routes = [route for route in routed_tools if _is_presentation_route(route)]
|
||||
if _question_requests_presentation(question) and presentation_routes:
|
||||
data_routes = [route for route in routed_tools if not _is_presentation_route(route)]
|
||||
primary = data_routes[0] if data_routes else fallback
|
||||
if len(data_routes) > 1:
|
||||
try:
|
||||
primary = route_mcp_tool_across_servers_with_llm(
|
||||
data_routes,
|
||||
question,
|
||||
router_model_profile=model_profile_key,
|
||||
)
|
||||
except McpToolRouterError:
|
||||
pass
|
||||
if primary is not fallback or len(routed_tools) > 1:
|
||||
return {
|
||||
"mode": "agent",
|
||||
"route_key": _route_key(primary.server_id, primary.tool.name),
|
||||
"reason": (
|
||||
"리포트·차트·HTML 요청이며, 발견된 렌더링 도구가 이전 구조화 "
|
||||
"결과를 입력으로 선언했습니다. 데이터 조회 후 렌더링을 순차 실행합니다."
|
||||
),
|
||||
"model_profile": model_profile_key,
|
||||
}
|
||||
if len(routed_tools) <= 1:
|
||||
return {
|
||||
"mode": "single",
|
||||
@@ -3276,7 +3514,10 @@ def plan_mcp_execution_mode(
|
||||
"the user's Korean question should be answered with one MCP "
|
||||
"tool call or with a multi-tool ReAct loop. Prefer mode=single "
|
||||
"unless the question explicitly requires comparing, combining, "
|
||||
"or validating evidence across different MCP tools/sources. "
|
||||
"or validating evidence across different MCP tools/sources. A route "
|
||||
"whose consumes_previous_result flag is true is a presentation renderer: "
|
||||
"when the user asks for a report, dashboard, chart, document, or HTML, "
|
||||
"choose mode=agent so a data route runs first and that renderer runs next. "
|
||||
"Return only JSON matching the schema. Never request or expose "
|
||||
"bearer tokens."
|
||||
),
|
||||
@@ -3290,7 +3531,8 @@ def plan_mcp_execution_mode(
|
||||
),
|
||||
"agent_policy": (
|
||||
"use agent only for cross-source comparison, contract "
|
||||
"plus terms/document search, or multi-step validation"
|
||||
"plus terms/document search, multi-step validation, or a "
|
||||
"data-result-to-presentation rendering sequence"
|
||||
),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
@@ -3360,6 +3602,10 @@ def _plan_agent_step(
|
||||
"If no tool has been called yet, choose action=call_tool. "
|
||||
"After each observation, decide whether another tool call is needed "
|
||||
"or action=final_answer is enough. Do not expose or request bearer tokens. "
|
||||
"A route with consumes_previous_result=true is a renderer. For a report, "
|
||||
"dashboard, chart, document, or HTML request, call a data route first, "
|
||||
"then call that renderer using the previous structured result; do not "
|
||||
"finish with text only before the renderer has been attempted. "
|
||||
"tool_query must be plain natural-language query text only; do not include "
|
||||
"argument labels such as limit:, prompt:, query:, top_k:, or candidate_k:. "
|
||||
"Do not write SQL. Preserve identifiers exactly. If the user says "
|
||||
@@ -3417,6 +3663,7 @@ def run_mcp_agent_loop(
|
||||
bearer_token: str,
|
||||
limit: int,
|
||||
model_profile_key: str,
|
||||
initial_route_key: str = "",
|
||||
progress_callback: Any = None,
|
||||
) -> dict[str, Any]:
|
||||
tool_catalog, routes_by_key = _agent_tool_catalog(routed_tools)
|
||||
@@ -3431,8 +3678,21 @@ def run_mcp_agent_loop(
|
||||
|
||||
for step_no in range(1, MAX_AGENT_TOOL_STEPS + 1):
|
||||
forced_plan = None
|
||||
wants_presentation = _question_requests_presentation(question)
|
||||
if wants_presentation and _presentation_route(routes_by_key, attempted_route_keys):
|
||||
forced_plan = (
|
||||
(
|
||||
(initial_route_key, routes_by_key[initial_route_key])
|
||||
if not observations
|
||||
and initial_route_key in routes_by_key
|
||||
and not _is_presentation_route(routes_by_key[initial_route_key])
|
||||
else _primary_data_route(routes_by_key, attempted_route_keys)
|
||||
)
|
||||
if not observations
|
||||
else _presentation_route(routes_by_key, attempted_route_keys)
|
||||
)
|
||||
if step_no == 1 and _question_needs_cross_source(question):
|
||||
forced_plan = _select_unvisited_route(
|
||||
forced_plan = forced_plan or _select_unvisited_route(
|
||||
question,
|
||||
routes_by_key,
|
||||
attempted_route_keys,
|
||||
@@ -3522,36 +3782,48 @@ def run_mcp_agent_loop(
|
||||
tool_query = _clean_agent_tool_query(plan.get("tool_query"), question)
|
||||
|
||||
if action == "final_answer" and observations:
|
||||
forced = _select_unvisited_route(
|
||||
question,
|
||||
routes_by_key,
|
||||
attempted_route_keys,
|
||||
renderer = (
|
||||
_presentation_route(routes_by_key, attempted_route_keys)
|
||||
if wants_presentation
|
||||
else None
|
||||
)
|
||||
if forced is None or not _question_needs_cross_source(question):
|
||||
stop_reason = "planner가 추가 MCP 호출이 불필요하다고 판단했습니다."
|
||||
break
|
||||
route_key, route = forced
|
||||
action = "call_tool"
|
||||
tool_query = _fallback_tool_query_for_route(
|
||||
question,
|
||||
route,
|
||||
observations,
|
||||
)
|
||||
thought = (
|
||||
f"{thought} / 비교·약관 질문인데 미호출 MCP route가 있어 "
|
||||
f"{route_key} 호출로 전환합니다."
|
||||
).strip(" /")
|
||||
if renderer is not None:
|
||||
route_key, route = renderer
|
||||
action = "call_tool"
|
||||
tool_query = question
|
||||
thought = "사용자 요청에 따른 이전 구조화 결과의 리포트 렌더링"
|
||||
else:
|
||||
forced = _select_unvisited_route(
|
||||
question,
|
||||
routes_by_key,
|
||||
attempted_route_keys,
|
||||
)
|
||||
if forced is None or not _question_needs_cross_source(question):
|
||||
stop_reason = "planner가 추가 MCP 호출이 불필요하다고 판단했습니다."
|
||||
break
|
||||
route_key, route = forced
|
||||
action = "call_tool"
|
||||
tool_query = _fallback_tool_query_for_route(
|
||||
question,
|
||||
route,
|
||||
observations,
|
||||
)
|
||||
thought = (
|
||||
f"{thought} / 비교·약관 질문인데 미호출 MCP route가 있어 "
|
||||
f"{route_key} 호출로 전환합니다."
|
||||
).strip(" /")
|
||||
if action != "call_tool" and not observations:
|
||||
action = "call_tool"
|
||||
route = routes_by_key.get(route_key)
|
||||
if route is None:
|
||||
route = next(iter(routes_by_key.values()))
|
||||
route_key = _route_key(route.server_id, route.tool.name)
|
||||
tool_query = append_query_contract_guidance(
|
||||
tool_query,
|
||||
original_question=question,
|
||||
tool_name=route.tool.name,
|
||||
)
|
||||
if not _is_presentation_route(route):
|
||||
tool_query = append_query_contract_guidance(
|
||||
tool_query,
|
||||
original_question=question,
|
||||
tool_name=route.tool.name,
|
||||
)
|
||||
is_distinct_vector_query = (
|
||||
_is_vector_route(route)
|
||||
and tool_query not in completed_vector_queries
|
||||
@@ -3576,11 +3848,12 @@ def run_mcp_agent_loop(
|
||||
route,
|
||||
observations,
|
||||
)
|
||||
tool_query = append_query_contract_guidance(
|
||||
tool_query,
|
||||
original_question=question,
|
||||
tool_name=route.tool.name,
|
||||
)
|
||||
if not _is_presentation_route(route):
|
||||
tool_query = append_query_contract_guidance(
|
||||
tool_query,
|
||||
original_question=question,
|
||||
tool_name=route.tool.name,
|
||||
)
|
||||
thought = (
|
||||
f"{thought} / 중복 MCP route {repeated_route_key} 대신 "
|
||||
f"미호출 route {route_key}로 전환합니다."
|
||||
@@ -3590,11 +3863,12 @@ def run_mcp_agent_loop(
|
||||
raise PublicMcpError("선택된 MCP 서버 설정을 찾지 못했습니다.")
|
||||
|
||||
started = perf_counter()
|
||||
arguments = build_mcp_tool_arguments(
|
||||
route.tool,
|
||||
tool_query,
|
||||
int(limit),
|
||||
arguments = _build_mcp_arguments(
|
||||
route=route,
|
||||
tool_query=question if _is_presentation_route(route) else tool_query,
|
||||
limit=int(limit),
|
||||
preferred_tool=server.default_tool,
|
||||
steps=steps,
|
||||
)
|
||||
raw_result = call_tool(
|
||||
base_url=server.endpoint_url,
|
||||
@@ -3618,6 +3892,7 @@ def run_mcp_agent_loop(
|
||||
"mcp_result": mcp_result,
|
||||
"result_summary": summary,
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"consumes_previous_result": _is_presentation_route(route),
|
||||
}
|
||||
steps.append(step)
|
||||
observations.append(
|
||||
@@ -3642,6 +3917,9 @@ def run_mcp_agent_loop(
|
||||
actionable_route_keys.add(route_key)
|
||||
if progress_callback:
|
||||
progress_callback(step)
|
||||
if _is_presentation_route(route):
|
||||
stop_reason = "이전 구조화 결과를 렌더링 MCP tool로 전달했습니다."
|
||||
break
|
||||
|
||||
if last is None:
|
||||
raise PublicMcpError("MCP agent가 실행한 tool 호출이 없습니다.")
|
||||
@@ -3666,6 +3944,11 @@ def _render_mcp_result_sections(
|
||||
execution_events = details.get("execution_events")
|
||||
generated_sql = _mcp_generated_sql(mcp_result)
|
||||
items = _mcp_items(mcp_result)
|
||||
rendered_html = _mcp_rendered_html(mcp_result)
|
||||
|
||||
if rendered_html:
|
||||
st.markdown("#### 생성된 리포트")
|
||||
components.html(rendered_html, height=1420, scrolling=True)
|
||||
|
||||
if isinstance(execution_events, list) and execution_events:
|
||||
with st.expander(f"처리 시간 로그 · {len(execution_events)}건"):
|
||||
@@ -5031,6 +5314,10 @@ def _process_submitted_question(
|
||||
bearer_token=bearer_token,
|
||||
limit=int(limit),
|
||||
model_profile_key=reasoning_model_profile,
|
||||
initial_route_key=_route_key(
|
||||
selected_route.server_id,
|
||||
selected_route.tool.name,
|
||||
),
|
||||
progress_callback=on_agent_step,
|
||||
)
|
||||
selected_server = agent_result["server"]
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
<!doctype html>
|
||||
<html lang="ko">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>HMM | 팀 포트폴리오 선사 실적</title>
|
||||
<style>
|
||||
:root { --hmm:#0065ad; --hmm-deep:#004a84; --ink:#102c43; --copy:#3d5363; --muted:#71818c; --line:#0d78c4; --pale:#edf7fc; --canvas:#f4f5f6; --green:#16815d; --amber:#b66b00; --red:#c5413c; font-family:"Noto Sans KR","Malgun Gothic",Arial,sans-serif; color:var(--ink); }
|
||||
* { box-sizing:border-box; }
|
||||
body { margin:0; min-width:320px; background:var(--canvas); }
|
||||
.page { min-height:100vh; max-width:1480px; margin:0 auto; background:#fff; box-shadow:0 0 40px rgba(12,38,60,.08); }
|
||||
.wordmark { display:flex; align-items:flex-end; gap:9px; font-size:18px; font-weight:900; letter-spacing:-.03em; }
|
||||
.wordmark::before { content:""; width:24px; height:21px; display:inline-block; background:linear-gradient(155deg,transparent 37%,#0571bc 38% 47%,transparent 48%),linear-gradient(26deg,transparent 42%,#0571bc 43% 52%,transparent 53%); border-left:2px solid #0571bc; border-bottom:2px solid #0571bc; }
|
||||
.report-name { margin:24px 0 31px; font-weight:800; font-size:13px; line-height:1.3; }
|
||||
.report-name span { display:block; color:var(--hmm); }
|
||||
.side-tools { padding:12px 0 22px; border-bottom:1px solid #8f969a; color:#056bad; font-size:16px; letter-spacing:6px; }
|
||||
nav { margin-top:22px; } .nav-group { padding:15px 0; border-bottom:1px solid #8f969a; }
|
||||
.nav-group-title { margin:0 0 11px; font-size:12px; font-weight:850; text-transform:uppercase; }
|
||||
.nav-item { display:block; padding:5px 9px; color:#69747b; font-size:11px; line-height:1.3; text-decoration:none; }
|
||||
.nav-item.active { color:#fff; background:linear-gradient(90deg,#0066ae,#52a9d9); font-weight:800; }
|
||||
.side-foot { margin-top:28px; color:#748087; font-size:10px; line-height:1.6; }
|
||||
.content { padding:42px min(6vw,92px) 45px; }
|
||||
.brand-banner { display:flex; align-items:center; justify-content:space-between; gap:18px; padding-bottom:18px; }
|
||||
.brand-banner img { display:block; width:128px; height:auto; }
|
||||
.brand-banner span { color:#627887; font-size:10px; font-weight:750; letter-spacing:.12em; text-transform:uppercase; }
|
||||
.top-line { height:4px; background:#045fa5; margin-bottom:32px; }
|
||||
.report-head { display:flex; justify-content:space-between; align-items:flex-start; gap:28px; padding-bottom:35px; border-bottom:1px solid var(--line); }
|
||||
.kicker { margin:0 0 10px; color:#0070ba; font-size:12px; font-weight:850; letter-spacing:.025em; }
|
||||
h1 { margin:0; color:#075b9f; font-size:clamp(30px,3.25vw,50px); line-height:1.16; letter-spacing:-.07em; font-weight:700; }
|
||||
h1 b { font-weight:850; }
|
||||
.head-meta { min-width:195px; padding-left:22px; border-left:1px solid #96c8e7; color:#647682; font-size:11px; line-height:1.65; }
|
||||
.head-meta strong { display:block; color:#075b9f; font-size:12px; }
|
||||
.intro { padding:18px 0 23px; color:var(--copy); font-size:15px; line-height:1.75; border-bottom:1px solid #8ac5e8; }
|
||||
.section-heading { margin:0 0 16px; color:#005fa9; font-size:21px; letter-spacing:-.05em; }
|
||||
.section-heading small { margin-left:8px; color:#71818c; font-size:11px; letter-spacing:0; font-weight:500; }
|
||||
.executive { display:grid; grid-template-columns:1.45fr 1fr; gap:42px; padding:29px 0 30px; border-bottom:1px solid var(--line); }
|
||||
.metrics { display:grid; grid-template-columns:repeat(2,1fr); border-top:2px solid #1478bb; border-left:1px solid #c8dce9; }
|
||||
.metric { min-height:111px; padding:17px 18px; border-right:1px solid #c8dce9; border-bottom:1px solid #c8dce9; }
|
||||
.metric-label { color:#5b6f7e; font-size:11px; font-weight:700; }.metric-value { margin:8px 0 5px; color:#075b9f; font-size:27px; letter-spacing:-.055em; font-weight:850; font-variant-numeric:tabular-nums; }.metric-value.money { font-size:23px; }.metric-note { color:#75848c; font-size:10px; }
|
||||
.risk-panel { padding:2px 0 0 25px; border-left:1px dotted #1478bb; }.risk-panel h2 { margin:0 0 15px; color:#005fa9; font-size:20px; letter-spacing:-.05em; }
|
||||
.risk-message { margin:0 0 17px; color:var(--copy); font-size:12px; line-height:1.65; }.risk-list { display:grid; gap:9px; }.risk-item { display:flex; align-items:center; gap:10px; padding-bottom:8px; border-bottom:1px solid #d7e8f3; font-size:11px; }.risk-item:last-child { border-bottom:0; }.risk-item-name { flex:1; font-weight:750; }.pill { padding:3px 7px; border-radius:2px; font-size:10px; font-weight:850; }.pill.red { color:var(--red); background:#fff1f0; }.pill.amber { color:var(--amber); background:#fff6e7; }.pill.green { color:var(--green); background:#eaf7f0; }
|
||||
.portfolio { padding:31px 0 28px; border-bottom:1px solid var(--line); }.portfolio-grid { display:grid; grid-template-columns:minmax(0,1.65fr) minmax(260px,.8fr); gap:43px; }.chart-note { margin:-8px 0 22px; color:#73838e; font-size:11px; }.bar-chart { display:grid; gap:12px; }.bar-row { display:grid; grid-template-columns:146px minmax(100px,1fr) 112px; align-items:center; gap:12px; }.bar-person { font-size:11px; }.bar-person b { display:block; color:#134f7f; font-size:12px; }.bar-person span { color:#788791; }.bar-lane { height:24px; background:#ebf2f6; overflow:hidden; }.bar { height:100%; min-width:4px; background:linear-gradient(90deg,#0073bb,#1aa2d8); position:relative; }.bar.critical { background:linear-gradient(90deg,#0073bb 0 84%,#d75349 84%); }.bar-value { color:#15486f; text-align:right; font-size:11px; font-weight:800; font-variant-numeric:tabular-nums; }.bar-value span { display:block; color:#72828c; font-size:9px; font-weight:500; }
|
||||
.chart-aside { padding:14px 0 0 22px; border-left:1px dotted #1478bb; }.chart-aside h3 { margin:0 0 14px; color:#005fa9; font-size:16px; }.legend { display:flex; justify-content:space-between; align-items:end; padding:10px 0; border-bottom:1px solid #d5e4ed; }.legend:last-child { border-bottom:0; }.legend-label { display:flex; align-items:center; gap:8px; font-size:11px; }.dot { width:10px; height:10px; border-radius:50%; }.dot.green { background:var(--green); }.dot.amber { background:var(--amber); }.dot.red { background:var(--red); }.legend strong { color:#075b9f; font-size:20px; }
|
||||
.detail { padding:31px 0 28px; }.detail-head { display:flex; justify-content:space-between; align-items:end; gap:16px; }.detail-head p { margin:0 0 16px; color:#75848c; font-size:11px; }.detail-table { width:100%; border-collapse:collapse; border-top:2px solid #1478bb; }.detail-table th { padding:11px 10px; background:#eff8fd; color:#176aa4; text-align:left; font-size:10px; font-weight:800; }.detail-table td { padding:12px 10px; border-bottom:1px solid #d4e3eb; color:#334f62; font-size:11px; }.detail-table .code { display:block; margin-bottom:2px; color:#75848c; font-size:9px; font-family:ui-monospace,SFMono-Regular,Menlo,monospace; }.detail-table .name { font-weight:750; }.number { text-align:right; font-variant-numeric:tabular-nums; }.negative { color:var(--red)!important; }.empty { padding:35px; color:#77868f; text-align:center; border:1px solid #d5e4ed; }
|
||||
.footnotes { display:grid; grid-template-columns:1.4fr 1fr; gap:25px; padding-top:19px; border-top:1px solid var(--line); color:#697d89; font-size:10px; line-height:1.7; }.footnotes h3 { margin:0 0 5px; color:#075b9f; font-size:11px; }.footnotes p,.footnotes ul { margin:0; padding-left:15px; }.footnotes p { padding-left:0; }
|
||||
@media(max-width:1000px){.content{padding:32px 35px 42px}.executive,.portfolio-grid{gap:25px}.bar-row{grid-template-columns:118px minmax(80px,1fr) 95px}}
|
||||
@media(max-width:760px){.content{padding:24px 18px 35px}.top-line{margin-bottom:20px}.report-head,.executive,.portfolio-grid,.footnotes{grid-template-columns:1fr;display:grid}.report-head{gap:17px;padding-bottom:24px}.head-meta{padding-left:0;border-left:0;border-top:1px solid #96c8e7;padding-top:10px}.intro{font-size:13px}.risk-panel,.chart-aside{padding:24px 0 0;border-left:0;border-top:1px dotted #1478bb}.bar-row{grid-template-columns:105px minmax(30px,1fr) 80px;gap:7px}.detail{overflow-x:auto}.detail-table{min-width:690px}.footnotes{gap:14px}}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main id="report-root" class="page" aria-live="polite"></main>
|
||||
<script>
|
||||
// 서버가 이미 권한 검사를 마친 조회 결과 JSON을 이 위치에 주입한다.
|
||||
const reportData = __REPORT_DATA__;
|
||||
const esc=(v)=>String(v??"").replace(/[&<>'"]/g,c=>({"&":"&","<":"<",">":">","'":"'","\"":"""}[c]));
|
||||
const n=(v,d=2)=>new Intl.NumberFormat("en-US",{maximumFractionDigits:d}).format(Number(v||0));
|
||||
const usd=(v)=>`${n(v)} USD`; const pct=(v)=>`${n(v)}%`; const when=(v)=>new Intl.DateTimeFormat("ko-KR",{dateStyle:"medium",timeStyle:"short",timeZone:"Asia/Seoul"}).format(new Date(v));
|
||||
const riskClass=(v)=>String(v||"").toLowerCase(); const riskLabel=(v)=>({GREEN:"정상",AMBER:"주의",RED:"위험"}[v]||v||"미분류");
|
||||
function aggregate(rows){ const risks={GREEN:0,AMBER:0,RED:0}; const people=new Map(); rows.forEach(row=>{const revenue=Number(row.latestRevenueUsd||0); const margin=Number(row.latestGrossMarginUsd||0); risks[row.latestRiskLevel]=(risks[row.latestRiskLevel]||0)+1; if(!people.has(row.employeeCode)) people.set(row.employeeCode,{code:row.employeeCode,name:row.employeeName,revenue:0,carriers:0,hasRisk:false}); const p=people.get(row.employeeCode);p.revenue+=revenue;p.carriers+=1;p.hasRisk||=row.latestRiskLevel==="RED"||row.latestRiskLevel==="AMBER";}); const totalRevenue=rows.reduce((s,r)=>s+Number(r.latestRevenueUsd||0),0); const totalMargin=rows.reduce((s,r)=>s+Number(r.latestGrossMarginUsd||0),0); return {risks,people:[...people.values()].sort((a,b)=>b.revenue-a.revenue),totalRevenue,totalMargin,avgReliability:rows.length?rows.reduce((s,r)=>s+Number(r.latestScheduleReliabilityPct||0),0)/rows.length:0}; }
|
||||
function badge(value){return `<span class="pill ${riskClass(value)}">${esc(riskLabel(value))}</span>`;}
|
||||
function detailRow(row){return `<tr><td><span class="code">${esc(row.employeeCode)}</span><span class="name">${esc(row.employeeName)}</span></td><td><span class="code">${esc(row.carrierCode)}</span><span class="name">${esc(row.carrierName)}</span></td><td class="number">${usd(row.latestRevenueUsd)}</td><td class="number ${Number(row.latestGrossMarginUsd)<0?"negative":""}">${usd(row.latestGrossMarginUsd)}</td><td class="number">${pct(row.latestScheduleReliabilityPct)}</td><td>${badge(row.latestRiskLevel)}</td></tr>`;}
|
||||
function renderHmmCarrierPerformanceReport(payload,target=document.getElementById("report-root")){const report=payload?.report||{};const rows=Array.isArray(payload?.rows)?payload.rows:[];const s=aggregate(rows);const max=Math.max(...s.people.map(p=>p.revenue),1);const watch=rows.filter(r=>r.latestRiskLevel!=="GREEN").sort((a,b)=>a.latestRiskLevel.localeCompare(b.latestRiskLevel));target.innerHTML=`
|
||||
<section class="content"><div class="brand-banner"><img src="https://eu-images.contentstack.com/v3/assets/bltdcfe6aab5515629e/bltaf50776e73f3149f/668ea7b97dc26754645e1830/hmmci.png?width=1400&auto=webp&quality=80&disable=upscale" alt="HMM"><span>HMM Management Report · Internal Demo</span></div><div class="top-line"></div><header class="report-head"><div><p class="kicker">${esc(report.id||"FEDERATION")} · ${esc(report.category||"HMM Business Intelligence")}</p><h1><b>${esc(report.title||"팀 포트폴리오")}</b> — 최신 선사 실적</h1></div><div class="head-meta"><strong>${esc(report.requestedBy||"-")} 팀장 조회</strong>생성 ${esc(when(report.generatedAt))}<br>MCP ${esc(report.execution?.calls||0)}회 호출<br>${esc(report.execution?.tool||"-")}</div></header>
|
||||
<p class="intro">${esc(report.answer||report.question||"조회된 선사 실적입니다.")} 전체 ${n(rows.length,0)}개 담당 선사의 매출·수익성·운항 지표를 담당자별 포트폴리오 관점에서 요약했습니다.</p>
|
||||
<section id="summary" class="executive"><div><h2 class="section-heading">핵심 요약 <small>Latest performance snapshot</small></h2><div class="metrics"><article class="metric"><div class="metric-label">담당 선사</div><div class="metric-value">${n(rows.length,0)}<small>개</small></div><div class="metric-note">팀원 ${n(s.people.length,0)}명 기준</div></article><article class="metric"><div class="metric-label">최신 매출 합계</div><div class="metric-value money">${usd(s.totalRevenue)}</div><div class="metric-note">담당 선사별 최신 기준월 합산</div></article><article class="metric"><div class="metric-label">매출총이익 합계</div><div class="metric-value money ${s.totalMargin<0?"negative":""}">${usd(s.totalMargin)}</div><div class="metric-note">음수 마진 선사 포함</div></article><article class="metric"><div class="metric-label">평균 정시 운항률</div><div class="metric-value">${pct(s.avgReliability)}</div><div class="metric-note">담당 선사 단순 평균</div></article></div></div><aside id="risk" class="risk-panel"><h2>위험 신호</h2><p class="risk-message">주의·위험 등급 선사 ${n(s.risks.AMBER+s.risks.RED,0)}개를 우선 점검 대상으로 표시합니다.</p><div class="risk-list">${watch.length?watch.map(r=>`<div class="risk-item">${badge(r.latestRiskLevel)}<span class="risk-item-name">${esc(r.carrierName)}</span><span>${esc(r.employeeName)}</span></div>`).join(""):'<div class="risk-item">현재 주의·위험 선사가 없습니다.</div>'}</div></aside></section>
|
||||
<section id="portfolio" class="portfolio"><h2 class="section-heading">담당자별 포트폴리오 매출 <small>Latest revenue by employee</small></h2><div class="portfolio-grid"><div><p class="chart-note">각 막대는 담당 선사 최신 매출의 합계입니다. 막대 끝의 색상은 해당 담당자 포트폴리오에 주의·위험 선사가 있는 경우를 나타냅니다.</p><div class="bar-chart">${s.people.map(p=>`<div class="bar-row"><div class="bar-person"><b>${esc(p.name)}</b><span>${esc(p.code)} · ${n(p.carriers,0)}개 선사</span></div><div class="bar-lane"><div class="bar ${p.hasRisk?"critical":""}" style="width:${(p.revenue/max*100).toFixed(2)}%"></div></div><div class="bar-value">${usd(p.revenue)}<span>팀 매출 ${(p.revenue/s.totalRevenue*100).toFixed(1)}%</span></div></div>`).join("")||'<div class="empty">차트 데이터가 없습니다.</div>'}</div></div><aside class="chart-aside"><h3>위험 등급 분포</h3><div class="legend"><span class="legend-label"><i class="dot green"></i>정상</span><strong>${n(s.risks.GREEN,0)}</strong></div><div class="legend"><span class="legend-label"><i class="dot amber"></i>주의</span><strong>${n(s.risks.AMBER,0)}</strong></div><div class="legend"><span class="legend-label"><i class="dot red"></i>위험</span><strong>${n(s.risks.RED,0)}</strong></div></aside></div></section>
|
||||
<section id="detail" class="detail"><div class="detail-head"><h2 class="section-heading">선사별 최신 지표 <small>Carrier detail</small></h2><p>총 ${n(rows.length,0)}건 · 최신순 1~${n(rows.length,0)}건 표시</p></div>${rows.length?`<table class="detail-table"><thead><tr><th>담당자</th><th>선사</th><th class="number">최신 매출</th><th class="number">매출총이익</th><th class="number">정시 운항률</th><th>위험 등급</th></tr></thead><tbody>${rows.map(detailRow).join("")}</tbody></table>`:'<div class="empty">표시할 상세 데이터가 없습니다.</div>'}</section>
|
||||
<footer id="notes" class="footnotes"><section><h3>답변 근거</h3><ul>${(report.evidence||[]).map(e=>`<li>${esc(e)}</li>`).join("")||'<li>제공된 근거가 없습니다.</li>'}</ul></section><section><h3>제약 및 주의</h3><p>${esc(report.limitation||"제약 정보가 제공되지 않았습니다.")}</p></section></footer></section>`;}
|
||||
window.renderHmmCarrierPerformanceReport=renderHmmCarrierPerformanceReport;renderHmmCarrierPerformanceReport(reportData);
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -6,7 +6,7 @@
|
||||
"enabled": true,
|
||||
"provider": "hmm_compat_mcp",
|
||||
"transport": "http",
|
||||
"endpoint_url": "https://hmm-mcp.cloud-handson.com/mcp",
|
||||
"endpoint_url": "https://hmm-backoffice.cloud-handson.com/mcp",
|
||||
"auth_token_env": "HMM_MCP_BEARER_TOKEN",
|
||||
"timeout_seconds_env": "AI_WEB_AGENT_CONSOLE_MCP_TIMEOUT_SECONDS",
|
||||
"default_tool": "search_hr_data",
|
||||
@@ -15,7 +15,8 @@
|
||||
"search_hr_data",
|
||||
"resolve_hr_term",
|
||||
"search_hr_policy",
|
||||
"search_carrier_performance"
|
||||
"search_carrier_performance",
|
||||
"render_hmm_carrier_report"
|
||||
],
|
||||
"description": "HMM HR knowledge, ADB employee assignment, and RDS carrier performance MCP server"
|
||||
}
|
||||
|
||||
@@ -123,6 +123,34 @@ class DemoScenarioConfigTest(unittest.TestCase):
|
||||
server["tool_allowlist"],
|
||||
)
|
||||
|
||||
def test_hmm_mcp_allows_dynamic_html_renderer(self) -> None:
|
||||
root = Path(__file__).parents[1]
|
||||
payload = json.loads(
|
||||
(root / "config" / "mcp_servers.json").read_text(encoding="utf-8")
|
||||
)
|
||||
server = next(
|
||||
item for item in payload["servers"] if item["id"] == "hmm_hr_mcp"
|
||||
)
|
||||
source = (root / "app.py").read_text(encoding="utf-8")
|
||||
|
||||
self.assertEqual(
|
||||
server["endpoint_url"],
|
||||
"https://hmm-backoffice.cloud-handson.com/mcp",
|
||||
)
|
||||
self.assertIn("render_hmm_carrier_report", server["tool_allowlist"])
|
||||
self.assertNotIn('tool.name == "render_hmm_carrier_report"', source)
|
||||
|
||||
def test_hmm_report_template_contains_only_dynamic_payload_slot(self) -> None:
|
||||
template = (
|
||||
Path(__file__).parents[1]
|
||||
/ "assets"
|
||||
/ "hmm-carrier-performance-report.html"
|
||||
).read_text(encoding="utf-8")
|
||||
|
||||
self.assertEqual(template.count("__REPORT_DATA__"), 1)
|
||||
self.assertNotIn("Bluewave Maritime", template)
|
||||
self.assertNotIn("Southern Cross Marine", template)
|
||||
|
||||
def test_hmm_demo_user_presets_reference_runtime_token_only(self) -> None:
|
||||
path = Path(__file__).parents[1] / "config" / "vpd_token_presets.json"
|
||||
payload = json.loads(path.read_text(encoding="utf-8"))
|
||||
|
||||
Reference in New Issue
Block a user