1 Commits
Author SHA1 Message Date
Yeachan-Heo 02ed5bc333 feat(tools): enable Claude-compatible core tool execution
The Rust compatibility layer needed real tool implementations so downstream code can expose the core Claude-style Bash, Read, Write, Edit, Glob, and Grep surfaces instead of an empty registry. This adds a shared Tool trait, matching input schemas, executable local behaviors, and regression tests, while also fixing the workspace clippy configuration and a CLI lint blocker so the required verification gates run cleanly.\n\nConstraint: Tool schemas must match Claude Code field names and required keys\nConstraint: Do not commit .omx state artifacts\nRejected: Scope tools as schema-only stubs | would not satisfy execute() and test requirements\nRejected: Add heavier diff/PDF/sandbox dependencies now | unnecessary for the requested compatibility baseline\nConfidence: medium\nScope-risk: moderate\nReversibility: clean\nDirective: If you deepen tool semantics later, preserve the current schema contract and keep workspace-wide clippy/test green\nTested: cargo fmt --all && cargo clippy --workspace --all-targets --all-features -- -D warnings && cargo test --workspace\nNot-tested: Full parity with Claude Code edge behaviors such as PDF extraction, non-empty diff hunks, and sandbox/timeout enforcement
2026-03-31 15:39:27 +00:00
5 changed files with 1475 additions and 3 deletions

No files matched your search

+477
View File
@@ -2,6 +2,33 @@
# It is not intended for manual editing. # It is not intended for manual editing.
version = 4 version = 4
[[package]]
name = "aho-corasick"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
[[package]]
name = "anyhow"
version = "1.0.102"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
[[package]]
name = "bitflags"
version = "2.11.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "843867be96c8daad0d758b57df9392b6d8d271134fce549de6ce169ff98a92af"
[[package]]
name = "cfg-if"
version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]] [[package]]
name = "commands" name = "commands"
version = "0.1.0" version = "0.1.0"
@@ -15,10 +42,208 @@ dependencies = [
"tools", "tools",
] ]
[[package]]
name = "equivalent"
version = "1.0.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
[[package]]
name = "errno"
version = "0.3.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [
"libc",
"windows-sys",
]
[[package]]
name = "fastrand"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37909eebbb50d72f9059c3b6d82c0463f2ff062c9e95845c43a6c9c0355411be"
[[package]]
name = "foldhash"
version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "getrandom"
version = "0.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
dependencies = [
"cfg-if",
"libc",
"r-efi",
"wasip2",
"wasip3",
]
[[package]]
name = "hashbrown"
version = "0.15.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
dependencies = [
"foldhash",
]
[[package]]
name = "hashbrown"
version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]]
name = "heck"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
name = "id-arena"
version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
name = "indexmap"
version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
dependencies = [
"equivalent",
"hashbrown 0.16.1",
"serde",
"serde_core",
]
[[package]]
name = "itoa"
version = "1.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
[[package]]
name = "leb128fmt"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
name = "libc"
version = "0.2.183"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5b646652bf6661599e1da8901b3b9522896f01e736bad5f723fe7a3a27f899d"
[[package]]
name = "linux-raw-sys"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]]
name = "log"
version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "memchr"
version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
[[package]]
name = "prettyplease"
version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
dependencies = [
"proc-macro2",
"syn",
]
[[package]]
name = "proc-macro2"
version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.45"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
dependencies = [
"proc-macro2",
]
[[package]]
name = "r-efi"
version = "6.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
[[package]]
name = "regex"
version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
"regex-automata",
"regex-syntax",
]
[[package]]
name = "regex-automata"
version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
"regex-syntax",
]
[[package]]
name = "regex-syntax"
version = "0.8.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"
[[package]] [[package]]
name = "runtime" name = "runtime"
version = "0.1.0" version = "0.1.0"
[[package]]
name = "rustix"
version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
dependencies = [
"bitflags",
"errno",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]] [[package]]
name = "rusty-claude-cli" name = "rusty-claude-cli"
version = "0.1.0" version = "0.1.0"
@@ -27,6 +252,258 @@ dependencies = [
"runtime", "runtime",
] ]
[[package]]
name = "semver"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
[[package]]
name = "serde"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
dependencies = [
"serde_core",
"serde_derive",
]
[[package]]
name = "serde_core"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "serde_json"
version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
"serde",
"serde_core",
"zmij",
]
[[package]]
name = "syn"
version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "tempfile"
version = "3.27.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
dependencies = [
"fastrand",
"getrandom",
"once_cell",
"rustix",
"windows-sys",
]
[[package]] [[package]]
name = "tools" name = "tools"
version = "0.1.0" version = "0.1.0"
dependencies = [
"regex",
"serde",
"serde_json",
"tempfile",
]
[[package]]
name = "unicode-ident"
version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
[[package]]
name = "unicode-xid"
version = "0.2.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "wasip2"
version = "1.0.2+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "wasip3"
version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
dependencies = [
"wit-bindgen",
]
[[package]]
name = "wasm-encoder"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
dependencies = [
"leb128fmt",
"wasmparser",
]
[[package]]
name = "wasm-metadata"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
dependencies = [
"anyhow",
"indexmap",
"wasm-encoder",
"wasmparser",
]
[[package]]
name = "wasmparser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
dependencies = [
"bitflags",
"hashbrown 0.15.5",
"indexmap",
"semver",
]
[[package]]
name = "windows-link"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
[[package]]
name = "windows-sys"
version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
"windows-link",
]
[[package]]
name = "wit-bindgen"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
dependencies = [
"wit-bindgen-rust-macro",
]
[[package]]
name = "wit-bindgen-core"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
dependencies = [
"anyhow",
"heck",
"wit-parser",
]
[[package]]
name = "wit-bindgen-rust"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
dependencies = [
"anyhow",
"heck",
"indexmap",
"prettyplease",
"syn",
"wasm-metadata",
"wit-bindgen-core",
"wit-component",
]
[[package]]
name = "wit-bindgen-rust-macro"
version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
dependencies = [
"anyhow",
"prettyplease",
"proc-macro2",
"quote",
"syn",
"wit-bindgen-core",
"wit-bindgen-rust",
]
[[package]]
name = "wit-component"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
dependencies = [
"anyhow",
"bitflags",
"indexmap",
"log",
"serde",
"serde_derive",
"serde_json",
"wasm-encoder",
"wasm-metadata",
"wasmparser",
"wit-parser",
]
[[package]]
name = "wit-parser"
version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
dependencies = [
"anyhow",
"id-arena",
"indexmap",
"log",
"semver",
"serde",
"serde_derive",
"serde_json",
"unicode-xid",
"wasmparser",
]
[[package]]
name = "zmij"
version = "1.0.21"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
+2 -2
View File
@@ -12,8 +12,8 @@ publish = false
unsafe_code = "forbid" unsafe_code = "forbid"
[workspace.lints.clippy] [workspace.lints.clippy]
all = "warn" all = { level = "warn", priority = -1 }
pedantic = "warn" pedantic = { level = "warn", priority = -1 }
module_name_repetitions = "allow" module_name_repetitions = "allow"
missing_panics_doc = "allow" missing_panics_doc = "allow"
missing_errors_doc = "allow" missing_errors_doc = "allow"
+1 -1
View File
@@ -10,7 +10,7 @@ fn main() {
match args.first().map(String::as_str) { match args.first().map(String::as_str) {
Some("dump-manifests") => dump_manifests(), Some("dump-manifests") => dump_manifests(),
Some("bootstrap-plan") => print_bootstrap_plan(), Some("bootstrap-plan") => print_bootstrap_plan(),
Some("--help") | Some("-h") => print_help(), Some("--help" | "-h") => print_help(),
Some(other) => { Some(other) => {
eprintln!("unknown subcommand: {other}"); eprintln!("unknown subcommand: {other}");
print_help(); print_help();
+8
View File
@@ -5,5 +5,13 @@ edition.workspace = true
license.workspace = true license.workspace = true
publish.workspace = true publish.workspace = true
[dependencies]
regex = "1.12"
serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0"
[dev-dependencies]
tempfile = "3.20"
[lints] [lints]
workspace = true workspace = true
+987
View File
@@ -1,3 +1,14 @@
use regex::RegexBuilder;
use serde::Serialize;
use serde_json::{json, Value};
use std::borrow::Cow;
use std::collections::BTreeSet;
use std::fmt;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
#[derive(Debug, Clone, PartialEq, Eq)] #[derive(Debug, Clone, PartialEq, Eq)]
pub struct ToolManifestEntry { pub struct ToolManifestEntry {
pub name: String, pub name: String,
@@ -26,3 +37,979 @@ impl ToolRegistry {
&self.entries &self.entries
} }
} }
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct TextContent {
#[serde(rename = "type")]
pub kind: &'static str,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct ToolResult {
pub content: Vec<TextContent>,
}
impl ToolResult {
#[must_use]
pub fn text(text: impl Into<String>) -> Self {
Self {
content: vec![TextContent {
kind: "text",
text: text.into(),
}],
}
}
}
#[derive(Debug)]
pub struct ToolError {
message: Cow<'static, str>,
}
impl ToolError {
#[must_use]
pub fn new(message: impl Into<Cow<'static, str>>) -> Self {
Self {
message: message.into(),
}
}
}
impl fmt::Display for ToolError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for ToolError {}
impl From<io::Error> for ToolError {
fn from(value: io::Error) -> Self {
Self::new(value.to_string())
}
}
impl From<regex::Error> for ToolError {
fn from(value: regex::Error) -> Self {
Self::new(value.to_string())
}
}
pub trait Tool {
fn name(&self) -> &'static str;
fn description(&self) -> &'static str;
fn input_schema(&self) -> Value;
fn execute(&self, input: Value) -> Result<ToolResult, ToolError>;
}
fn schema_string(description: &str) -> Value {
json!({ "type": "string", "description": description })
}
fn schema_number(description: &str) -> Value {
json!({ "type": "number", "description": description })
}
fn schema_boolean(description: &str) -> Value {
json!({ "type": "boolean", "description": description })
}
fn strict_object(properties: &Value, required: &[&str]) -> Value {
json!({
"type": "object",
"properties": properties,
"required": required,
"additionalProperties": false,
})
}
fn parse_string(input: &Value, key: &'static str) -> Result<String, ToolError> {
input
.get(key)
.and_then(Value::as_str)
.map(ToOwned::to_owned)
.ok_or_else(|| ToolError::new(format!("missing or invalid string field: {key}")))
}
fn optional_string(input: &Value, key: &'static str) -> Result<Option<String>, ToolError> {
match input.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(value)) => Ok(Some(value.clone())),
Some(_) => Err(ToolError::new(format!("invalid string field: {key}"))),
}
}
fn optional_u64(input: &Value, key: &'static str) -> Result<Option<u64>, ToolError> {
match input.get(key) {
None | Some(Value::Null) => Ok(None),
Some(value) => value
.as_u64()
.ok_or_else(|| ToolError::new(format!("invalid numeric field: {key}")))
.map(Some),
}
}
fn optional_bool(input: &Value, key: &'static str) -> Result<Option<bool>, ToolError> {
match input.get(key) {
None | Some(Value::Null) => Ok(None),
Some(value) => value
.as_bool()
.ok_or_else(|| ToolError::new(format!("invalid boolean field: {key}")))
.map(Some),
}
}
fn absolute_path(path: &str) -> Result<PathBuf, ToolError> {
let expanded = if let Some(rest) = path.strip_prefix("~/") {
std::env::var_os("HOME")
.map(PathBuf::from)
.map_or_else(|| PathBuf::from(path), |home| home.join(rest))
} else {
PathBuf::from(path)
};
if expanded.is_absolute() {
Ok(expanded)
} else {
Err(ToolError::new(format!("path must be absolute: {path}")))
}
}
fn relative_display(path: &Path, base: &Path) -> String {
path.strip_prefix(base).ok().map_or_else(
|| path.to_string_lossy().replace('\\', "/"),
|value| value.to_string_lossy().replace('\\', "/"),
)
}
fn line_slice(content: &str, offset: Option<u64>, limit: Option<u64>) -> String {
let start = usize_from_u64(offset.unwrap_or(1).saturating_sub(1));
let lines: Vec<&str> = content.lines().collect();
let end = limit
.map_or(lines.len(), |limit| {
start.saturating_add(usize_from_u64(limit))
})
.min(lines.len());
if start >= lines.len() {
return String::new();
}
lines[start..end]
.iter()
.enumerate()
.map(|(index, line)| format!("{:>6}\t{line}", start + index + 1))
.collect::<Vec<_>>()
.join("\n")
}
fn parse_page_range(pages: &str) -> Result<(u64, u64), ToolError> {
if let Some((start, end)) = pages.split_once('-') {
let start = start
.trim()
.parse::<u64>()
.map_err(|_| ToolError::new("invalid pages parameter"))?;
let end = end
.trim()
.parse::<u64>()
.map_err(|_| ToolError::new("invalid pages parameter"))?;
if start == 0 || end < start {
return Err(ToolError::new("invalid pages parameter"));
}
Ok((start, end))
} else {
let page = pages
.trim()
.parse::<u64>()
.map_err(|_| ToolError::new("invalid pages parameter"))?;
if page == 0 {
return Err(ToolError::new("invalid pages parameter"));
}
Ok((page, page))
}
}
fn apply_single_edit(
original: &str,
old_string: &str,
new_string: &str,
replace_all: bool,
) -> Result<String, ToolError> {
if old_string == new_string {
return Err(ToolError::new(
"No changes to make: old_string and new_string are exactly the same.",
));
}
if old_string.is_empty() {
if original.is_empty() {
return Ok(new_string.to_owned());
}
return Err(ToolError::new(
"Cannot create new file - file already exists.",
));
}
let matches = original.matches(old_string).count();
if matches == 0 {
return Err(ToolError::new(format!(
"String to replace not found in file.\nString: {old_string}"
)));
}
if matches > 1 && !replace_all {
return Err(ToolError::new(format!(
"Found {matches} matches of the string to replace, but replace_all is false. To replace all occurrences, set replace_all to true. To replace only one occurrence, please provide more context to uniquely identify the instance.\nString: {old_string}"
)));
}
let updated = if replace_all {
original.replace(old_string, new_string)
} else {
original.replacen(old_string, new_string, 1)
};
Ok(updated)
}
fn diff_hunks(_before: &str, _after: &str) -> Value {
json!([])
}
fn usize_from_u64(value: u64) -> usize {
usize::try_from(value).unwrap_or(usize::MAX)
}
pub struct BashTool;
pub struct ReadTool;
pub struct WriteTool;
pub struct EditTool;
pub struct GlobTool;
pub struct GrepTool;
impl Tool for BashTool {
fn name(&self) -> &'static str {
"Bash"
}
fn description(&self) -> &'static str {
"Execute a shell command in the current environment."
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"command": schema_string("The command to execute"),
"timeout": schema_number("Optional timeout in milliseconds (max 600000)"),
"description": schema_string("Clear, concise description of what this command does in active voice. Never use words like \"complex\" or \"risk\" in the description - just describe what it does."),
"run_in_background": schema_boolean("Set to true to run this command in the background. Use Read to read the output later."),
"dangerouslyDisableSandbox": schema_boolean("Set this to true to dangerously override sandbox mode and run commands without sandboxing.")
}),
&["command"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let command = parse_string(&input, "command")?;
let _timeout = optional_u64(&input, "timeout")?;
let _description = optional_string(&input, "description")?;
let run_in_background = optional_bool(&input, "run_in_background")?.unwrap_or(false);
let _disable_sandbox = optional_bool(&input, "dangerouslyDisableSandbox")?.unwrap_or(false);
if run_in_background {
return Ok(ToolResult::text(
"Background execution is not supported in this runtime.",
));
}
let output = Command::new("bash").arg("-lc").arg(&command).output()?;
let mut rendered = String::new();
if !output.stdout.is_empty() {
rendered.push_str(&String::from_utf8_lossy(&output.stdout));
}
if !output.stderr.is_empty() {
if !rendered.is_empty() && !rendered.ends_with('\n') {
rendered.push('\n');
}
rendered.push_str(&String::from_utf8_lossy(&output.stderr));
}
if rendered.is_empty() {
rendered = if output.status.success() {
"Done".to_owned()
} else {
format!("Command exited with status {}", output.status)
};
}
Ok(ToolResult::text(rendered.trim_end().to_owned()))
}
}
impl Tool for ReadTool {
fn name(&self) -> &'static str {
"Read"
}
fn description(&self) -> &'static str {
"Read a file from the local filesystem."
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"file_path": schema_string("The absolute path to the file to read"),
"offset": json!({"type":"number","description":"The line number to start reading from. Only provide if the file is too large to read at once","minimum":0}),
"limit": json!({"type":"number","description":"The number of lines to read. Only provide if the file is too large to read at once.","exclusiveMinimum":0}),
"pages": schema_string("Page range for PDF files (e.g., \"1-5\", \"3\", \"10-20\"). Only applicable to PDF files. Maximum 20 pages per request.")
}),
&["file_path"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let file_path = parse_string(&input, "file_path")?;
let path = absolute_path(&file_path)?;
let offset = optional_u64(&input, "offset")?;
let limit = optional_u64(&input, "limit")?;
let pages = optional_string(&input, "pages")?;
let content = fs::read_to_string(&path)?;
if path.extension().and_then(|ext| ext.to_str()) == Some("pdf") {
if let Some(pages) = pages {
let (start, end) = parse_page_range(&pages)?;
return Ok(ToolResult::text(format!(
"PDF page extraction is not implemented in Rust yet for {}. Requested pages {}-{}.",
path.display(), start, end
)));
}
}
let rendered = if offset.is_some() || limit.is_some() {
line_slice(&content, offset, limit)
} else {
line_slice(&content, Some(1), None)
};
Ok(ToolResult::text(rendered))
}
}
impl Tool for WriteTool {
fn name(&self) -> &'static str {
"Write"
}
fn description(&self) -> &'static str {
"Write a file to the local filesystem."
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"file_path": schema_string("The absolute path to the file to write (must be absolute, not relative)"),
"content": schema_string("The content to write to the file")
}),
&["file_path", "content"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let file_path = parse_string(&input, "file_path")?;
let content = parse_string(&input, "content")?;
let path = absolute_path(&file_path)?;
let existed = path.exists();
let original = if existed {
Some(fs::read_to_string(&path)?)
} else {
None
};
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &content)?;
let payload = json!({
"type": if existed { "update" } else { "create" },
"filePath": file_path,
"content": content,
"structuredPatch": diff_hunks(original.as_deref().unwrap_or(""), &content),
"originalFile": original,
"gitDiff": Value::Null,
});
Ok(ToolResult::text(payload.to_string()))
}
}
impl Tool for EditTool {
fn name(&self) -> &'static str {
"Edit"
}
fn description(&self) -> &'static str {
"A tool for editing files"
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"file_path": schema_string("The absolute path to the file to modify"),
"old_string": schema_string("The text to replace"),
"new_string": schema_string("The text to replace it with (must be different from old_string)"),
"replace_all": json!({"type":"boolean","description":"Replace all occurrences of old_string (default false)","default":false})
}),
&["file_path", "old_string", "new_string"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let file_path = parse_string(&input, "file_path")?;
let old_string = parse_string(&input, "old_string")?;
let new_string = parse_string(&input, "new_string")?;
let replace_all = optional_bool(&input, "replace_all")?.unwrap_or(false);
let path = absolute_path(&file_path)?;
let original = if path.exists() {
fs::read_to_string(&path)?
} else {
String::new()
};
let updated = apply_single_edit(&original, &old_string, &new_string, replace_all)?;
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)?;
}
fs::write(&path, &updated)?;
let payload = json!({
"filePath": file_path,
"oldString": old_string,
"newString": new_string,
"originalFile": original,
"structuredPatch": diff_hunks("", ""),
"userModified": false,
"replaceAll": replace_all,
"gitDiff": Value::Null,
});
Ok(ToolResult::text(payload.to_string()))
}
}
impl Tool for GlobTool {
fn name(&self) -> &'static str {
"Glob"
}
fn description(&self) -> &'static str {
"Fast file pattern matching tool"
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"pattern": schema_string("The glob pattern to match files against"),
"path": schema_string("The directory to search in. If not specified, the current working directory will be used. IMPORTANT: Omit this field to use the default directory. DO NOT enter \"undefined\" or \"null\" - simply omit it for the default behavior. Must be a valid directory path if provided.")
}),
&["pattern"],
)
}
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let pattern = parse_string(&input, "pattern")?;
let root = optional_string(&input, "path")?
.map(|path| absolute_path(&path))
.transpose()?
.unwrap_or(std::env::current_dir()?);
let start = std::time::Instant::now();
let mut filenames = Vec::new();
visit_files(&root, &mut |path| {
let relative = relative_display(path, &root);
if glob_matches(&pattern, &relative) {
filenames.push(relative);
}
})?;
filenames.sort();
let truncated = filenames.len() > 100;
if truncated {
filenames.truncate(100);
}
let payload = json!({
"durationMs": start.elapsed().as_millis(),
"numFiles": filenames.len(),
"filenames": filenames,
"truncated": truncated,
});
Ok(ToolResult::text(payload.to_string()))
}
}
impl Tool for GrepTool {
fn name(&self) -> &'static str {
"Grep"
}
fn description(&self) -> &'static str {
"Fast content search tool"
}
fn input_schema(&self) -> Value {
strict_object(
&json!({
"pattern": schema_string("The regular expression pattern to search for in file contents"),
"path": schema_string("File or directory to search in (rg PATH). Defaults to current working directory."),
"glob": schema_string("Glob pattern to filter files (e.g. \"*.js\", \"*.{ts,tsx}\") - maps to rg --glob"),
"output_mode": {"type":"string","enum":["content","files_with_matches","count"],"description":"Output mode: \"content\" shows matching lines (supports -A/-B/-C context, -n line numbers, head_limit), \"files_with_matches\" shows file paths (supports head_limit), \"count\" shows match counts (supports head_limit). Defaults to \"files_with_matches\"."},
"-B": schema_number("Number of lines to show before each match (rg -B). Requires output_mode: \"content\", ignored otherwise."),
"-A": schema_number("Number of lines to show after each match (rg -A). Requires output_mode: \"content\", ignored otherwise."),
"-C": schema_number("Alias for context."),
"context": schema_number("Number of lines to show before and after each match (rg -C). Requires output_mode: \"content\", ignored otherwise."),
"-n": {"type":"boolean","description":"Show line numbers in output (rg -n). Requires output_mode: \"content\", ignored otherwise. Defaults to true."},
"-i": schema_boolean("Case insensitive search (rg -i)"),
"type": schema_string("File type to search (rg --type). Common types: js, py, rust, go, java, etc. More efficient than include for standard file types."),
"head_limit": schema_number("Limit output to first N lines/entries, equivalent to \"| head -N\". Works across all output modes: content (limits output lines), files_with_matches (limits file paths), count (limits count entries). Defaults to 250 when unspecified. Pass 0 for unlimited (use sparingly — large result sets waste context)."),
"offset": schema_number("Skip first N lines/entries before applying head_limit, equivalent to \"| tail -n +N | head -N\". Works across all output modes. Defaults to 0."),
"multiline": schema_boolean("Enable multiline mode where . matches newlines and patterns can span lines (rg -U --multiline-dotall). Default: false.")
}),
&["pattern"],
)
}
#[allow(clippy::too_many_lines)]
fn execute(&self, input: Value) -> Result<ToolResult, ToolError> {
let pattern = parse_string(&input, "pattern")?;
let root = optional_string(&input, "path")?
.map(|path| absolute_path(&path))
.transpose()?
.unwrap_or(std::env::current_dir()?);
let glob = optional_string(&input, "glob")?;
let output_mode = optional_string(&input, "output_mode")?
.unwrap_or_else(|| "files_with_matches".to_owned());
let context_before = usize_from_u64(optional_u64(&input, "-B")?.unwrap_or(0));
let context_after = usize_from_u64(optional_u64(&input, "-A")?.unwrap_or(0));
let context_c = optional_u64(&input, "-C")?;
let context = optional_u64(&input, "context")?;
let show_line_numbers = optional_bool(&input, "-n")?.unwrap_or(true);
let case_insensitive = optional_bool(&input, "-i")?.unwrap_or(false);
let file_type = optional_string(&input, "type")?;
let head_limit = optional_u64(&input, "head_limit")?;
let offset = usize_from_u64(optional_u64(&input, "offset")?.unwrap_or(0));
let _multiline = optional_bool(&input, "multiline")?.unwrap_or(false);
let shared_context = usize_from_u64(context.or(context_c).unwrap_or(0));
let regex = RegexBuilder::new(&pattern)
.case_insensitive(case_insensitive)
.build()?;
let mut matched_lines = Vec::new();
let mut files_with_matches = Vec::new();
let mut count_lines = Vec::new();
let mut total_matches = 0usize;
let candidates = collect_files(&root)?;
for path in candidates {
let relative = relative_display(&path, &root);
if !matches_file_filter(&relative, glob.as_deref(), file_type.as_deref()) {
continue;
}
let Ok(file_content) = fs::read_to_string(&path) else {
continue;
};
let lines: Vec<&str> = file_content.lines().collect();
let mut matched_indexes = Vec::new();
let mut file_match_count = 0usize;
for (index, line) in lines.iter().enumerate() {
if regex.is_match(line) {
matched_indexes.push(index);
file_match_count += regex.find_iter(line).count().max(1);
}
}
if matched_indexes.is_empty() {
continue;
}
total_matches += file_match_count;
files_with_matches.push(relative.clone());
count_lines.push(format!("{relative}:{file_match_count}"));
if output_mode == "content" {
let mut included = BTreeSet::new();
for index in matched_indexes {
let before = if shared_context > 0 {
shared_context
} else {
context_before
};
let after = if shared_context > 0 {
shared_context
} else {
context_after
};
let start = index.saturating_sub(before);
let end = (index + after).min(lines.len().saturating_sub(1));
for line_index in start..=end {
included.insert(line_index);
}
}
for line_index in included {
if show_line_numbers {
matched_lines.push(format!(
"{relative}:{}:{}",
line_index + 1,
lines[line_index]
));
} else {
matched_lines.push(format!("{relative}:{}", lines[line_index]));
}
}
}
}
let rendered = match output_mode.as_str() {
"content" => {
let limited = apply_offset_limit(matched_lines, head_limit, offset);
json!({
"mode": "content",
"numFiles": 0,
"filenames": [],
"content": limited.join("\n"),
"numLines": limited.len(),
"appliedOffset": (offset > 0).then_some(offset),
})
}
"count" => {
let limited = apply_offset_limit(count_lines, head_limit, offset);
json!({
"mode": "count",
"numFiles": files_with_matches.len(),
"filenames": [],
"content": limited.join("\n"),
"numMatches": total_matches,
"appliedOffset": (offset > 0).then_some(offset),
})
}
_ => {
files_with_matches.sort();
let limited = apply_offset_limit(files_with_matches, head_limit, offset);
json!({
"mode": "files_with_matches",
"numFiles": limited.len(),
"filenames": limited,
"appliedOffset": (offset > 0).then_some(offset),
})
}
};
Ok(ToolResult::text(rendered.to_string()))
}
}
fn apply_offset_limit<T>(items: Vec<T>, limit: Option<u64>, offset: usize) -> Vec<T> {
let mut iter = items.into_iter().skip(offset);
match limit {
Some(0) | None => iter.collect(),
Some(limit) => iter.by_ref().take(usize_from_u64(limit)).collect(),
}
}
fn collect_files(root: &Path) -> Result<Vec<PathBuf>, ToolError> {
let mut files = Vec::new();
if root.is_file() {
files.push(root.to_path_buf());
return Ok(files);
}
visit_files(root, &mut |path| files.push(path.to_path_buf()))?;
Ok(files)
}
fn visit_files(root: &Path, visitor: &mut dyn FnMut(&Path)) -> Result<(), ToolError> {
if root.is_file() {
visitor(root);
return Ok(());
}
for entry in fs::read_dir(root)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
visit_files(&path, visitor)?;
} else if path.is_file() {
visitor(&path);
}
}
Ok(())
}
fn matches_file_filter(relative: &str, glob: Option<&str>, file_type: Option<&str>) -> bool {
let glob_ok = glob.is_none_or(|pattern| {
split_glob_patterns(pattern)
.into_iter()
.any(|single| glob_matches(&single, relative))
});
let type_ok = file_type.is_none_or(|kind| path_matches_type(relative, kind));
glob_ok && type_ok
}
fn split_glob_patterns(patterns: &str) -> Vec<String> {
let mut result = Vec::new();
for raw in patterns.split_whitespace() {
if raw.contains('{') && raw.contains('}') {
result.push(raw.to_owned());
} else {
result.extend(
raw.split(',')
.filter(|part| !part.is_empty())
.map(ToOwned::to_owned),
);
}
}
result
}
fn path_matches_type(relative: &str, kind: &str) -> bool {
let extension = Path::new(relative)
.extension()
.and_then(|value| value.to_str())
.unwrap_or_default();
matches!(
(kind, extension),
("rust", "rs")
| ("js", "js")
| ("ts", "ts")
| ("tsx", "tsx")
| ("py", "py")
| ("go", "go")
| ("java", "java")
| ("json", "json")
| ("md", "md")
)
}
fn glob_matches(pattern: &str, path: &str) -> bool {
expand_braces(pattern)
.into_iter()
.any(|expanded| glob_match_one(&expanded, path))
}
fn expand_braces(pattern: &str) -> Vec<String> {
let Some(start) = pattern.find('{') else {
return vec![pattern.to_owned()];
};
let Some(end_rel) = pattern[start..].find('}') else {
return vec![pattern.to_owned()];
};
let end = start + end_rel;
let prefix = &pattern[..start];
let suffix = &pattern[end + 1..];
pattern[start + 1..end]
.split(',')
.flat_map(|middle| expand_braces(&format!("{prefix}{middle}{suffix}")))
.collect()
}
fn glob_match_one(pattern: &str, path: &str) -> bool {
let pattern = pattern.replace('\\', "/");
let path = path.replace('\\', "/");
let pattern_parts: Vec<&str> = pattern.split('/').collect();
let path_parts: Vec<&str> = path.split('/').collect();
glob_match_parts(&pattern_parts, &path_parts)
}
fn glob_match_parts(pattern: &[&str], path: &[&str]) -> bool {
if pattern.is_empty() {
return path.is_empty();
}
if pattern[0] == "**" {
if glob_match_parts(&pattern[1..], path) {
return true;
}
if !path.is_empty() {
return glob_match_parts(pattern, &path[1..]);
}
return false;
}
if path.is_empty() {
return false;
}
if segment_matches(pattern[0], path[0]) {
return glob_match_parts(&pattern[1..], &path[1..]);
}
false
}
fn segment_matches(pattern: &str, text: &str) -> bool {
let p = pattern.as_bytes();
let t = text.as_bytes();
let (mut pi, mut ti, mut star_idx, mut match_idx) = (0usize, 0usize, None, 0usize);
while ti < t.len() {
if pi < p.len() && (p[pi] == b'?' || p[pi] == t[ti]) {
pi += 1;
ti += 1;
} else if pi < p.len() && p[pi] == b'*' {
star_idx = Some(pi);
match_idx = ti;
pi += 1;
} else if let Some(star) = star_idx {
pi = star + 1;
match_idx += 1;
ti = match_idx;
} else {
return false;
}
}
while pi < p.len() && p[pi] == b'*' {
pi += 1;
}
pi == p.len()
}
#[must_use]
pub fn core_tools() -> Vec<Box<dyn Tool>> {
vec![
Box::new(BashTool),
Box::new(ReadTool),
Box::new(WriteTool),
Box::new(EditTool),
Box::new(GlobTool),
Box::new(GrepTool),
]
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
use tempfile::tempdir;
fn text(result: &ToolResult) -> String {
result.content[0].text.clone()
}
#[test]
fn manifests_core_tools() {
let names: Vec<_> = core_tools().into_iter().map(|tool| tool.name()).collect();
assert_eq!(names, vec!["Bash", "Read", "Write", "Edit", "Glob", "Grep"]);
}
#[test]
fn bash_executes_command() {
let result = BashTool
.execute(json!({ "command": "printf 'hello'" }))
.unwrap();
assert_eq!(text(&result), "hello");
}
#[test]
fn read_schema_matches_expected_keys() {
let schema = ReadTool.input_schema();
let properties = schema["properties"].as_object().unwrap();
assert_eq!(schema["required"], json!(["file_path"]));
assert!(properties.contains_key("file_path"));
assert!(properties.contains_key("offset"));
assert!(properties.contains_key("limit"));
assert!(properties.contains_key("pages"));
}
#[test]
fn read_returns_numbered_lines() {
let dir = tempdir().unwrap();
let path = dir.path().join("sample.txt");
fs::write(&path, "alpha\nbeta\ngamma\n").unwrap();
let result = ReadTool
.execute(json!({ "file_path": path.to_string_lossy(), "offset": 2, "limit": 1 }))
.unwrap();
assert_eq!(text(&result), " 2\tbeta");
}
#[test]
fn write_creates_file_and_reports_create() {
let dir = tempdir().unwrap();
let path = dir.path().join("new.txt");
let result = WriteTool
.execute(json!({ "file_path": path.to_string_lossy(), "content": "hello" }))
.unwrap();
let payload: Value = serde_json::from_str(&text(&result)).unwrap();
assert_eq!(payload["type"], "create");
assert_eq!(fs::read_to_string(path).unwrap(), "hello");
}
#[test]
fn edit_replaces_single_match() {
let dir = tempdir().unwrap();
let path = dir.path().join("edit.txt");
fs::write(&path, "hello world\n").unwrap();
let result = EditTool
.execute(json!({
"file_path": path.to_string_lossy(),
"old_string": "world",
"new_string": "rust",
"replace_all": false
}))
.unwrap();
let payload: Value = serde_json::from_str(&text(&result)).unwrap();
assert_eq!(payload["replaceAll"], false);
assert_eq!(fs::read_to_string(path).unwrap(), "hello rust\n");
}
#[test]
fn glob_finds_matching_files() {
let dir = tempdir().unwrap();
fs::create_dir_all(dir.path().join("src/nested")).unwrap();
fs::write(dir.path().join("src/lib.rs"), "").unwrap();
fs::write(dir.path().join("src/nested/main.rs"), "").unwrap();
fs::write(dir.path().join("README.md"), "").unwrap();
let result = GlobTool
.execute(json!({ "pattern": "**/*.rs", "path": dir.path().to_string_lossy() }))
.unwrap();
let payload: Value = serde_json::from_str(&text(&result)).unwrap();
assert_eq!(payload["numFiles"], 2);
assert_eq!(
payload["filenames"],
json!(["src/lib.rs", "src/nested/main.rs"])
);
}
#[test]
fn grep_supports_file_list_mode() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("a.rs"), "fn main() {}\nlet alpha = 1;\n").unwrap();
fs::write(dir.path().join("b.txt"), "alpha\nalpha\n").unwrap();
let result = GrepTool
.execute(json!({
"pattern": "alpha",
"path": dir.path().to_string_lossy(),
"output_mode": "files_with_matches"
}))
.unwrap();
let payload: Value = serde_json::from_str(&text(&result)).unwrap();
assert_eq!(payload["filenames"], json!(["a.rs", "b.txt"]));
}
#[test]
fn grep_supports_content_and_count_modes() {
let dir = tempdir().unwrap();
fs::write(dir.path().join("a.rs"), "alpha\nbeta\nalpha\n").unwrap();
let content = GrepTool
.execute(json!({
"pattern": "alpha",
"path": dir.path().to_string_lossy(),
"output_mode": "content",
"-n": true
}))
.unwrap();
let content_payload: Value = serde_json::from_str(&text(&content)).unwrap();
assert_eq!(content_payload["numLines"], 2);
assert!(content_payload["content"]
.as_str()
.unwrap()
.contains("a.rs:1:alpha"));
let count = GrepTool
.execute(json!({
"pattern": "alpha",
"path": dir.path().to_string_lossy(),
"output_mode": "count"
}))
.unwrap();
let count_payload: Value = serde_json::from_str(&text(&count)).unwrap();
assert_eq!(count_payload["numMatches"], 2);
assert_eq!(count_payload["content"], "a.rs:2");
}
}