mod advanced;
mod edit_content;
mod edit_format;
mod edit_structure;
mod exchange;
mod protocol;
mod read;
pub(crate) fn show_mcp_tools(profile: Option<&'static crate::agent_profiles::AgentProfile>) -> i32 {
println!("{}", mcp_manifest_value(profile));
crate::EXIT_OK
}
pub(crate) fn mcp_manifest_value(
profile: Option<&'static crate::agent_profiles::AgentProfile>,
) -> serde_json::Value {
let mut tools = mcp_tool_definitions();
if let Some(p) = profile {
tools.retain(|t| {
t["name"]
.as_str()
.map(|n| crate::agent_profiles::allows_tool(p, n))
.unwrap_or(false)
});
}
crate::provenance::marked(
serde_json::json!({
"schemaVersion": crate::ENVELOPE_SCHEMA_VERSION,
"protocol": "mcp",
"server": {
"suggestedName": "rhwp",
"version": rhwp::version(),
"description": "HWP/HWPX 한국어 문서를 읽고 편집하는 도구 모음",
},
"invocation": {
"transport": "cli",
"note": "각 도구의 cli.args 에서 {name} 자리표시자를 inputSchema 의 같은 이름 값으로 치환해 실행한다. stdout 은 순수 JSON, 진단은 stderr, 종료 코드는 0/1/2(+ir-diff 차이 3). 자리표시자 치환 없이 바로 쓰려면 `rhwp mcp-serve`(stdio JSON-RPC 서버, #3140)를 실행한다.",
"stdinTools": MCP_STDIN_TOOLS,
"server": "mcp-serve",
},
"tools": tools,
"profile": profile.map(|p| serde_json::json!({
"name": p.name,
"summary": p.summary,
"session": crate::agent_profiles::opens_session(p),
"sessionTools": p.session_tools.map(|t| if t.is_empty() { crate::agent_profiles::ALL_SESSION_TOOLS.to_vec() } else { t.to_vec() }),
"recipe": p.recipe,
})),
"profiles": crate::agent_profiles::names(),
}),
"capabilities",
)
}
pub(crate) const MCP_STDIN_TOOLS: [&str; 3] =
["hwp_batch", "hwp_batch_search", "hwp_batch_extract_data"];
fn inspect_unicode_kind_enum() -> Vec<String> {
rhwp::document_core::text_security::DeceptionKind::ALL
.iter()
.map(|kind| kind.filter_name().to_string())
.chain(std::iter::once("all".to_string()))
.collect()
}
fn inspect_watermark_kind_enum() -> Vec<String> {
rhwp::document_core::queries::stego_scan::MarkKind::ALL
.iter()
.map(|kind| kind.filter_name().to_string())
.chain(std::iter::once("all".to_string()))
.collect()
}
fn path_schema(extra: serde_json::Value) -> serde_json::Value {
let mut props = serde_json::json!({
"path": { "type": "string", "description": "HWP/HWPX/HML 문서 경로" }
});
if let (Some(p), Some(e)) = (props.as_object_mut(), extra.as_object()) {
for (k, v) in e {
p.insert(k.clone(), v.clone());
}
}
serde_json::json!({
"type": "object",
"properties": props,
"required": ["path"],
})
}
fn tool(
name: &str,
description: &str,
input_schema: serde_json::Value,
command: &str,
args_template: serde_json::Value,
output_fields: &[&str],
) -> serde_json::Value {
let spec = crate::cli::catalog::find(command)
.unwrap_or_else(|| panic!("MCP CLI 배선이 catalog에 없습니다: {command}"));
assert!(spec.mcp, "MCP 비참여 명령을 도구에 배선했습니다: {command}");
serde_json::json!({
"name": name,
"description": description,
"inputSchema": input_schema,
"cli": { "command": spec.name, "args": args_template },
"outputFields": output_fields,
})
}
fn tool_with_optional_args(
name: &str,
description: &str,
input_schema: serde_json::Value,
command: &str,
args_template: serde_json::Value,
optional_args: serde_json::Value,
output_fields: &[&str],
) -> serde_json::Value {
let mut definition = tool(
name,
description,
input_schema,
command,
args_template,
output_fields,
);
definition["cli"]["optionalArgs"] = optional_args;
definition
}
fn supports_password_stdin(name: &str) -> bool {
matches!(
name,
"hwp_info"
| "hwp_digest"
| "hwp_export_text"
| "hwp_export_structure"
| "hwp_ir_diff"
| "hwp_export_svg"
| "hwp_export_pdf"
| "hwp_export_markdown"
| "hwp_convert_hwpx"
| "hwp_convert_hwp5"
| "hwp_split_document"
| "hwp_export_tables"
| "hwp_search"
| "hwp_extract_data"
| "hwp_fields"
| "hwp_explain"
| "hwp_explore"
| "hwp_inspect_hidden_text"
| "hwp_inspect_injection"
| "hwp_inspect_unicode"
| "hwp_inspect_watermark"
| "hwp_fill_fields"
| "hwp_replace_text"
| "hwp_set_checkbox"
| "hwp_set_cell"
| "hwp_set_cell_props"
| "hwp_set_table_props"
| "hwp_insert_text_in_cell"
| "hwp_delete_text_in_cell"
| "hwp_split_table"
| "hwp_fit_table"
| "hwp_resize_table"
| "hwp_resize_table_cell"
| "hwp_move_table"
| "hwp_merge_table"
| "hwp_apply_para_format_in_cell"
| "hwp_apply_char_format_in_cell"
| "hwp_set_column_widths"
| "hwp_delete_equation"
| "hwp_set_numbering_restart"
| "hwp_set_page_def"
| "hwp_set_section_def"
)
}
fn add_password_stdin_contract(definition: &mut serde_json::Value) {
let Some(properties) = definition["inputSchema"]["properties"].as_object_mut() else {
return;
};
properties.insert(
"password".to_string(),
serde_json::json!({
"type": "string",
"writeOnly": true,
"description": "암호 문서 비밀번호. MCP 서버는 응답·세션에 저장하지 않고, 무상태 도구에서는 자식 CLI stdin으로만 전달한다."
}),
);
definition["cli"]["passwordStdin"] = serde_json::json!({
"argument": "password",
"flag": "--password-stdin",
"format": "utf8-first-line"
});
}
fn add_edit_tool(
tools: &mut Vec<serde_json::Value>,
name: &str,
description: &str,
properties: serde_json::Value,
required: &[&str],
args: serde_json::Value,
optional_args: serde_json::Value,
output_fields: &[&str],
) {
tools.push(tool_with_optional_args(
name,
description,
serde_json::json!({
"type": "object",
"properties": properties,
"required": required,
}),
"edit",
args,
optional_args,
output_fields,
));
}
pub(crate) fn mcp_tool_definitions() -> Vec<serde_json::Value> {
let mut tools = Vec::new();
read::extend(&mut tools);
exchange::extend(&mut tools);
edit_content::extend(&mut tools);
edit_structure::extend(&mut tools);
edit_format::extend(&mut tools);
protocol::extend(&mut tools);
advanced::extend(&mut tools);
for definition in &mut tools {
if definition["name"]
.as_str()
.is_some_and(supports_password_stdin)
{
add_password_stdin_contract(definition);
}
}
for definition in &mut tools {
definition["annotations"] = derive_mcp_tool_annotations(definition);
}
let wired_commands: std::collections::BTreeSet<&str> = tools
.iter()
.filter_map(|definition| definition["cli"]["command"].as_str())
.collect();
for spec in crate::cli::catalog::commands()
.iter()
.filter(|spec| spec.mcp)
{
assert!(
wired_commands.contains(spec.name),
"catalog MCP 참여 명령에 도구가 없습니다: {}",
spec.name
);
}
tools
}
pub(crate) fn mcp_annotations(
read_only: bool,
destructive: bool,
idempotent: bool,
) -> serde_json::Value {
serde_json::json!({
"readOnlyHint": read_only,
"destructiveHint": destructive,
"idempotentHint": idempotent,
"openWorldHint": false,
})
}
fn derive_mcp_tool_annotations(definition: &serde_json::Value) -> serde_json::Value {
let writes_files = definition["outputFields"].as_array().is_some_and(|fields| {
fields
.iter()
.any(|f| matches!(f.as_str(), Some("output" | "outputDir")))
});
let in_place = cli_wiring_has_flag(&definition["cli"], "--in-place");
mcp_annotations(!writes_files, in_place, true)
}
fn cli_wiring_has_flag(cli: &serde_json::Value, flag: &str) -> bool {
let args_contain = |args: &serde_json::Value| {
args.as_array()
.is_some_and(|a| a.iter().any(|t| t.as_str() == Some(flag)))
};
args_contain(&cli["args"])
|| cli["optionalArgs"]
.as_array()
.is_some_and(|opts| opts.iter().any(|o| args_contain(&o["args"])))
}