Files
kebab/crates/kebab-mcp/tests/tools_call_fetch.rs
altair823 7c85de065a chore: workspace-wide cleanup — clippy::pedantic baseline + auto-fix
cut PR v0.18.0 전 마지막 정리. 사용자 요청: "전체 코드베이스를 깔끔하고 알아보기 쉽게".

## Workspace lints

- `Cargo.toml` 의 `[workspace.lints.clippy]` 에 `pedantic = "warn"` (priority -1) + 의도적 allow-list 추가:
  - cast_possible_truncation / cast_possible_wrap / cast_sign_loss / cast_precision_loss — ONNX i64 / hash modular reduction 등 의도적 truncation.
  - doc_markdown / missing_errors_doc / missing_panics_doc — cosmetic doc style.
  - too_many_lines / module_name_repetitions / must_use_candidate / needless_pass_by_value / manual_let_else / items_after_statements / similar_names — informational only.
  - format_collect / match_wildcard_for_single_variants / trivially_copy_pass_by_ref / unnecessary_wraps — intentional patterns (exhaustive match, future Result variants 등).
  - default_trait_access — `Foo::default()` 가 idiomatic.
  - float_cmp — NLI / RRF score 의 explicit threshold 비교 의도.
  - struct_excessive_bools / case_sensitive_file_extension_comparisons / naive_bytecount / ignore_without_reason — domain-specific 의도.
  - format_push_string / return_self_not_must_use / match_same_arms — builder / wire-label / hot-path 패턴 보존.
  - needless_continue / used_underscore_binding / nonminimal_bool / unreadable_literal / many_single_char_names / doc_link_with_quotes / assigning_clones / collapsible_str_replace / trivial_regex / elidable_lifetime_names / range_plus_one / explicit_iter_loop / implicit_hasher / ref_option — remaining low-value style.
- 각 24 crate `Cargo.toml` 에 `[lints] workspace = true` 추가.

## Auto-fix

`cargo clippy --workspace --all-targets --fix` 적용 — 128 files changed, 552 insertions / 472 deletions. 주로:
- uninlined_format_args (~18): `format!("{}", x)` → `format!("{x}")`.
- redundant_closure_for_method_calls (~33): `.map(|x| x.foo())` → `.map(T::foo)`.
- 그 외 mechanical refactor.

## 검증

- `cargo clippy --workspace --all-targets -j 1 -- -D warnings` clean (pedantic + 모든 lint group).
- `cargo test --workspace --no-fail-fast -j 1` — **1293 tests pass + 1 pre-existing flaky fail** (`kebab-mcp::tools_call_ask_multi_hop::ask_tool_routes_multi_hop_true_to_decompose_first`, HOTFIX candidate, cleanup 무관). 회귀 0.

Wire 영향: 없음.
Behavior 영향: 없음 (mechanical refactor only).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 03:01:58 +00:00

223 lines
6.9 KiB
Rust

//! p9-fb-35: tools/call name=fetch — chunk happy path + invalid_input.
//!
//! Mirrors `tools_call_search.rs` setup: a TempDir KB with embedding
//! provider = "none" (no Ollama / fastembed) and a single ingested
//! markdown doc. We discover a `chunk_id` via the search tool, call
//! `fetch` with it, then exercise the missing-arg branch separately.
use std::fs;
use kebab_config::Config;
use kebab_core::SourceScope;
use kebab_mcp::{KebabAppState, KebabHandler};
use rmcp::model::RawContent;
fn minimal_config(data_dir: &std::path::Path, workspace_root: &std::path::Path) -> Config {
let mut cfg = Config::defaults();
cfg.storage.data_dir = data_dir.to_string_lossy().into_owned();
cfg.storage.model_dir = data_dir
.join("models")
.to_string_lossy()
.into_owned();
cfg.workspace.root = workspace_root.to_string_lossy().into_owned();
cfg.workspace.exclude.clear();
cfg.models.embedding.provider = "none".to_string();
cfg.models.embedding.dimensions = 0;
cfg
}
#[tokio::test]
async fn fetch_tool_chunk_returns_fetch_result_v1() {
let dir = tempfile::tempdir().unwrap();
let data_dir = dir.path().join("data");
let workspace_root = dir.path().join("notes");
fs::create_dir_all(&data_dir).unwrap();
fs::create_dir_all(&workspace_root).unwrap();
let config = minimal_config(&data_dir, &workspace_root);
fs::write(
workspace_root.join("a.md"),
"# Alpha\n\nThis document mentions kebab and bread.",
)
.unwrap();
let scope = SourceScope {
root: workspace_root.clone(),
include: vec![],
exclude: vec![],
};
let _ = kebab_app::ingest_with_config(config.clone(), scope, false).unwrap();
let state = KebabAppState::new(config, None);
let handler = KebabHandler::new(state);
// Discover a chunk_id via the search tool.
let search_result = kebab_mcp::tools::search::handle(
handler.state(),
kebab_mcp::tools::search::SearchInput {
query: "kebab".to_string(),
mode: Some("lexical".to_string()),
k: Some(1),
max_tokens: None,
snippet_chars: None,
cursor: None,
tags: None,
lang: None,
path_glob: None,
trust_min: None,
media: None,
ingested_after: None,
doc_id: None,
trace: None,
},
);
let search_text = match &search_result.content.first().unwrap().raw {
RawContent::Text(t) => t.text.clone(),
other => panic!("expected text content, got {other:?}"),
};
let search_v: serde_json::Value = serde_json::from_str(&search_text).unwrap();
let chunk_id = search_v["hits"][0]["chunk_id"]
.as_str()
.expect("chunk_id on first hit")
.to_string();
// Call fetch with kind=chunk.
let result = kebab_mcp::tools::fetch::handle(
handler.state(),
kebab_mcp::tools::fetch::FetchInput {
kind: "chunk".to_string(),
chunk_id: Some(chunk_id),
doc_id: None,
line_start: None,
line_end: None,
context: None,
max_tokens: None,
},
);
assert!(
!result.is_error.unwrap_or(false),
"expected isError=false, got {result:?}"
);
let content = result
.content
.first()
.expect("expected at least one content item");
let text = match &content.raw {
RawContent::Text(t) => &t.text,
other => panic!("expected text content, got {other:?}"),
};
let v: serde_json::Value = serde_json::from_str(text).unwrap();
assert_eq!(
v.get("schema_version").and_then(|s| s.as_str()),
Some("fetch_result.v1"),
"envelope must carry schema_version=fetch_result.v1"
);
assert_eq!(
v.get("kind").and_then(|s| s.as_str()),
Some("chunk"),
"kind must be 'chunk'"
);
assert!(
v.get("chunk").is_some_and(serde_json::Value::is_object),
"chunk payload must be populated for kind=chunk"
);
}
#[tokio::test]
async fn fetch_tool_invalid_kind_returns_invalid_input() {
let dir = tempfile::tempdir().unwrap();
let data_dir = dir.path().join("data");
let workspace_root = dir.path().join("notes");
fs::create_dir_all(&data_dir).unwrap();
fs::create_dir_all(&workspace_root).unwrap();
let config = minimal_config(&data_dir, &workspace_root);
let state = KebabAppState::new(config, None);
let handler = KebabHandler::new(state);
let result = kebab_mcp::tools::fetch::handle(
handler.state(),
kebab_mcp::tools::fetch::FetchInput {
kind: "garbage".to_string(),
chunk_id: None,
doc_id: None,
line_start: None,
line_end: None,
context: None,
max_tokens: None,
},
);
assert!(
result.is_error.unwrap_or(false),
"expected isError=true for unknown kind"
);
let content = result
.content
.first()
.expect("expected at least one content item");
let text = match &content.raw {
RawContent::Text(t) => &t.text,
other => panic!("expected text content, got {other:?}"),
};
let v: serde_json::Value = serde_json::from_str(text).unwrap();
assert_eq!(
v.get("schema_version").and_then(|s| s.as_str()),
Some("error.v1"),
"must carry error.v1 envelope"
);
assert_eq!(
v.get("code").and_then(|s| s.as_str()),
Some("invalid_input"),
"code must be invalid_input for unknown kind"
);
}
#[tokio::test]
async fn fetch_tool_chunk_missing_id_returns_invalid_input() {
let dir = tempfile::tempdir().unwrap();
let data_dir = dir.path().join("data");
let workspace_root = dir.path().join("notes");
fs::create_dir_all(&data_dir).unwrap();
fs::create_dir_all(&workspace_root).unwrap();
let config = minimal_config(&data_dir, &workspace_root);
let state = KebabAppState::new(config, None);
let handler = KebabHandler::new(state);
// kind=chunk but no chunk_id — invalid_input.
let result = kebab_mcp::tools::fetch::handle(
handler.state(),
kebab_mcp::tools::fetch::FetchInput {
kind: "chunk".to_string(),
chunk_id: None,
doc_id: None,
line_start: None,
line_end: None,
context: None,
max_tokens: None,
},
);
assert!(
result.is_error.unwrap_or(false),
"expected isError=true when chunk_id is missing"
);
let content = result.content.first().unwrap();
let text = match &content.raw {
RawContent::Text(t) => &t.text,
other => panic!("expected text content, got {other:?}"),
};
let v: serde_json::Value = serde_json::from_str(text).unwrap();
assert_eq!(
v.get("code").and_then(|s| s.as_str()),
Some("invalid_input")
);
}