1use agent_runtime::{Tool, ToolContext, ToolDefinition, ToolError, ToolRegistry};
3use async_trait::async_trait;
4use rabel_tool::{CatalogueItem, RabelClient};
5use serde_json::{Value, json};
6
7use crate::{Book, BookInput, BookStore, BookUpdate};
8
9pub fn register_tools(registry: &mut ToolRegistry, store: BookStore) -> Result<(), agent_config::ConfigError> {
10 registry.register(def("books.list", "List books in the authenticated user's personal collection.", object(json!({}), &[])), List(store.clone()))?;
11 registry.register(def("books.get", "Get a book from the authenticated user's personal collection.", object(json!({"id":{"type":"string","minLength":1}}), &["id"])), Get(store.clone()))?;
12 registry.register(def("books.add", "Add a book to the authenticated user's personal collection.", book_input_schema()), Add(store.clone()))?;
13 registry.register(def("books.update", "Update catalogue or personal metadata for a book in the authenticated user's collection.", book_update_schema()), Update(store.clone()))?;
14 registry.register(def("books.remove", "Remove a book from the authenticated user's personal collection.", object(json!({"id":{"type":"string","minLength":1}}), &["id"])), Remove(store.clone()))?;
15
16 registry.register(def(
17 "books.list_libraries",
18 "List RABEL libraries and identify which ones are selected as this user's preferred libraries.",
19 object(json!({}), &[])),
20 ListLibraries(store.clone()),
21 )?;
22 registry.register(def(
23 "books.set_preferred_libraries",
24 "Replace the authenticated user's preferred RABEL libraries. Use library IDs returned by books.list_libraries; an empty list clears the selection.",
25 object(json!({"library_ids":{"type":"array","items":{"type":"string","minLength":1},"uniqueItems":true}}), &["library_ids"])),
26 SetPreferredLibraries(store.clone()),
27 )?;
28 registry.register(def(
29 "books.check_availability",
30 "Fetch live copy-level availability for a book in every preferred library. This performs fresh RABEL catalogue requests and does not infer availability from stored metadata.",
31 object(json!({"id":{"type":"string","minLength":1}}), &["id"])),
32 CheckAvailability(store.clone()),
33 )?;
34 registry.register(def(
35 "books.check_catalogue_availability",
36 "Check a catalogue title or ISBN in every preferred RABEL library without first adding it to the personal collection. Returns fresh copy-level holdings per library.",
37 object(json!({"title":{"type":"string","minLength":1},"isbn":{"type":["string","null"]}}), &["title"])),
38 CheckCatalogueAvailability(store.clone()),
39 )?;
40 registry.register(def(
41 "books.refresh_catalogue",
42 "Refresh bibliographic metadata for a collection book from RABEL, matching by ISBN first and exact parsed title as a fallback. Personal rating, reading status, purchase intent and review are preserved.",
43 object(json!({"id":{"type":"string","minLength":1}}), &["id"])),
44 RefreshCatalogue(store),
45 )?;
46 Ok(())
47}
48
49fn object(properties: Value, required: &[&str]) -> Value {
50 json!({"type":"object","properties":properties,"required":required,"additionalProperties":false})
51}
52fn def(name: &str, description: &str, parameters: Value) -> ToolDefinition {
53 ToolDefinition { name: name.into(), description: description.into(), parameters }
54}
55fn book_input_schema() -> Value {
56 object(json!({
57 "title":{"type":"string","minLength":1},
58 "authors":{"type":"array","items":{"type":"string"}},
59 "isbn":{"type":["string","null"]},"publisher":{"type":["string","null"]},
60 "publication_year":{"type":["integer","null"]},"responsibility":{"type":["string","null"]},
61 "publication_statement":{"type":["string","null"]},"physical_description":{"type":["string","null"]},
62 "series":{"type":["string","null"]},"notes":{"type":"array","items":{"type":"string"}},
63 "subjects":{"type":"array","items":{"type":"string"}},"catalogue_url":{"type":["string","null"]},
64 "rating":{"type":["integer","null"],"minimum":1,"maximum":5},
65 "reading_status":{"type":"string","enum":["pending","reading","read"]},
66 "want_to_buy":{"type":"boolean"},"review":{"type":["string","null"]}
67 }), &["title"])
68}
69fn book_update_schema() -> Value {
70 let mut properties = book_input_schema()["properties"].clone();
71 properties.as_object_mut().unwrap().insert("id".into(), json!({"type":"string","minLength":1}));
72 object(properties, &["id"])
73}
74fn user(context: &ToolContext) -> Result<&str, ToolError> {
75 context.user_id.as_deref().filter(|value| !value.trim().is_empty())
76 .ok_or_else(|| execution("book collection requires an authenticated user context"))
77}
78fn execution(error: impl std::fmt::Display) -> ToolError { ToolError::Execution(error.to_string()) }
79fn normalize_isbn(value: &str) -> String {
80 value.chars().filter(|character| character.is_ascii_alphanumeric())
81 .map(|character| character.to_ascii_uppercase()).collect()
82}
83fn normalize_title(value: &str) -> String {
84 value.to_lowercase().split_whitespace().collect::<Vec<_>>().join(" ")
85}
86fn title_matches(search_title: &str, parsed_title: &str) -> bool {
87 let prefix = search_title.split(" / ").next().unwrap_or(search_title);
88 let search = normalize_title(prefix);
89 let parsed = normalize_title(parsed_title);
90 search == parsed || (parsed.split_whitespace().count() >= 2 && search.ends_with(&format!(" {parsed}")))
91}
92async fn find_catalogue_record(client: &RabelClient, book: &Book) -> Result<Option<(String, CatalogueItem)>, ToolError> {
93 find_catalogue_record_by_identity(client, book.isbn.as_deref(), &book.title).await
94}
95async fn find_catalogue_record_by_identity(
96 client: &RabelClient,
97 isbn: Option<&str>,
98 title: &str,
99) -> Result<Option<(String, CatalogueItem)>, ToolError> {
100 let isbn_query = isbn.filter(|value| !value.trim().is_empty());
101 let mut queries = Vec::new();
102 if let Some(isbn) = isbn_query { queries.push((isbn.to_owned(), true)); }
103 queries.push((title.to_owned(), false));
104 let mut matches = Vec::new();
105 for (query, isbn_lookup) in queries {
106 let results = client.search(&query, 20).await.map_err(execution)?;
107 for result in results {
108 let item = match client.get_item(&result.record_ref).await {
109 Ok(item) => item,
110 Err(_) => continue,
111 };
112 let matched = if isbn_lookup {
113 let wanted = normalize_isbn(isbn_query.unwrap_or_default());
114 item.isbn.as_deref().or(result.isbn.as_deref())
115 .is_some_and(|candidate| normalize_isbn(candidate) == wanted)
116 } else {
117 item.title.as_deref().is_some_and(|parsed| title_matches(&result.title, parsed) && title_matches(title, parsed))
118 };
119 if matched { matches.push((result.record_ref, item)); }
120 }
121 if !matches.is_empty() { break; }
122 }
123 match matches.len() {
124 0 => Ok(None),
125 1 => Ok(matches.pop()),
126 _ => Err(execution("Multiple RABEL records match this title/ISBN; narrow the lookup before using availability or refreshing metadata")),
127 }
128}
129
130struct List(BookStore);
131struct Get(BookStore);
132struct Add(BookStore);
133struct Update(BookStore);
134struct Remove(BookStore);
135struct ListLibraries(BookStore);
136struct SetPreferredLibraries(BookStore);
137struct CheckAvailability(BookStore);
138struct CheckCatalogueAvailability(BookStore);
139struct RefreshCatalogue(BookStore);
140
141#[async_trait]
142impl Tool for List {
143 async fn execute(&self, context: &ToolContext, _: Value) -> Result<String, ToolError> {
144 serde_json::to_string(&self.0.list(user(context)?).await.map_err(execution)?).map_err(execution)
145 }
146}
147#[async_trait]
148impl Tool for Get {
149 async fn execute(&self, context: &ToolContext, args: Value) -> Result<String, ToolError> {
150 let id = args["id"].as_str().filter(|value| !value.trim().is_empty()).ok_or_else(|| execution("id is required"))?;
151 serde_json::to_string(&self.0.get(user(context)?, id).await.map_err(execution)?).map_err(execution)
152 }
153}
154#[async_trait]
155impl Tool for Add {
156 async fn execute(&self, context: &ToolContext, args: Value) -> Result<String, ToolError> {
157 let input: BookInput = serde_json::from_value(args).map_err(execution)?;
158 serde_json::to_string(&self.0.add(user(context)?, input).await.map_err(execution)?).map_err(execution)
159 }
160}
161#[async_trait]
162impl Tool for Update {
163 async fn execute(&self, context: &ToolContext, mut args: Value) -> Result<String, ToolError> {
164 let object = args.as_object_mut().ok_or_else(|| execution("arguments must be an object"))?;
165 let id = object.remove("id").and_then(|value| value.as_str().map(str::to_owned))
166 .filter(|value| !value.trim().is_empty()).ok_or_else(|| execution("id is required"))?;
167 let update: BookUpdate = serde_json::from_value(args).map_err(execution)?;
168 serde_json::to_string(&self.0.update(user(context)?, &id, update).await.map_err(execution)?).map_err(execution)
169 }
170}
171#[async_trait]
172impl Tool for Remove {
173 async fn execute(&self, context: &ToolContext, args: Value) -> Result<String, ToolError> {
174 let id = args["id"].as_str().filter(|value| !value.trim().is_empty()).ok_or_else(|| execution("id is required"))?;
175 self.0.remove(user(context)?, id).await.map_err(execution)?;
176 Ok(json!({"removed":true}).to_string())
177 }
178}
179#[async_trait]
180impl Tool for ListLibraries {
181 async fn execute(&self, context: &ToolContext, _: Value) -> Result<String, ToolError> {
182 let user = user(context)?;
183 let client = RabelClient::new().map_err(execution)?;
184 let available = client.libraries().await.map_err(execution)?;
185 let selected = self.0.preferred_libraries(user).await.map_err(execution)?;
186 serde_json::to_string(&json!({"available":available,"selected":selected})).map_err(execution)
187 }
188}
189#[async_trait]
190impl Tool for SetPreferredLibraries {
191 async fn execute(&self, context: &ToolContext, args: Value) -> Result<String, ToolError> {
192 let user = user(context)?;
193 let ids = args["library_ids"].as_array().ok_or_else(|| execution("library_ids must be an array"))?;
194 let client = RabelClient::new().map_err(execution)?;
195 let available = client.libraries().await.map_err(execution)?;
196 let previous = self.0.preferred_libraries(user).await.map_err(execution)?;
197 let mut selected = Vec::new();
198 for id in ids {
199 let id = id.as_str().filter(|value| !value.trim().is_empty()).ok_or_else(|| execution("library IDs must be non-empty strings"))?;
200 if let Some(library) = available.iter().find(|library| library.id == id) {
201 selected.push((library.id.clone(), library.name.clone()));
202 } else if let Some(saved) = previous.iter().find(|(saved_id, _)| saved_id == id) {
203 selected.push(saved.clone());
204 } else {
205 return Err(execution(format!("unknown RABEL library ID: {id}")));
206 }
207 }
208 self.0.set_preferred_libraries(user, &selected).await.map_err(execution)?;
209 serde_json::to_string(&json!({"selected":selected})).map_err(execution)
210 }
211}
212#[async_trait]
213impl Tool for CheckAvailability {
214 async fn execute(&self, context: &ToolContext, args: Value) -> Result<String, ToolError> {
215 let user = user(context)?;
216 let id = args["id"].as_str().filter(|value| !value.trim().is_empty()).ok_or_else(|| execution("id is required"))?;
217 let book = self.0.get(user, id).await.map_err(execution)?;
218 let libraries = self.0.preferred_libraries(user).await.map_err(execution)?;
219 let mut results = Vec::new();
220 for (library_id, library_name) in libraries {
221 let client = match RabelClient::for_subcatalog(&library_id) {
222 Ok(client) => client,
223 Err(error) => { results.push(json!({"library_id":library_id,"library_name":library_name,"status":"error","error":error.to_string(),"copies":[]})); continue; }
224 };
225 let (record_ref, record) = match find_catalogue_record(&client, &book).await {
226 Ok(Some(record)) => record,
227 Ok(None) => { results.push(json!({"library_id":library_id,"library_name":library_name,"status":"not_found","copies":[]})); continue; }
228 Err(error) => { results.push(json!({"library_id":library_id,"library_name":library_name,"status":"error","error":error.to_string(),"copies":[]})); continue; }
229 };
230 match client.get_holdings(&record_ref).await {
231 Ok(holdings) => results.push(json!({"library_id":library_id,"library_name":library_name,"status":"found","catalogue_title":record.title,"checked_at":holdings.checked_at,"copies":holdings.copies})),
232 Err(error) => results.push(json!({"library_id":library_id,"library_name":library_name,"status":"error","error":error.to_string(),"copies":[]})),
233 }
234 }
235 serde_json::to_string(&json!({"book_id":book.id,"libraries":results})).map_err(execution)
236 }
237}
238#[async_trait]
239impl Tool for CheckCatalogueAvailability {
240 async fn execute(&self, context: &ToolContext, args: Value) -> Result<String, ToolError> {
241 let user = user(context)?;
242 let title = args["title"].as_str().filter(|value| !value.trim().is_empty()).ok_or_else(|| execution("title is required"))?;
243 let isbn = args["isbn"].as_str().filter(|value| !value.trim().is_empty());
244 let libraries = self.0.preferred_libraries(user).await.map_err(execution)?;
245 let mut results = Vec::new();
246 for (library_id, library_name) in libraries {
247 let client = match RabelClient::for_subcatalog(&library_id) {
248 Ok(client) => client,
249 Err(error) => { results.push(json!({"library_id":library_id,"library_name":library_name,"status":"error","error":error.to_string(),"copies":[]})); continue; }
250 };
251 let (record_ref, record) = match find_catalogue_record_by_identity(&client, isbn, title).await {
252 Ok(Some(record)) => record,
253 Ok(None) => { results.push(json!({"library_id":library_id,"library_name":library_name,"status":"not_found","copies":[]})); continue; }
254 Err(error) => { results.push(json!({"library_id":library_id,"library_name":library_name,"status":"error","error":error.to_string(),"copies":[]})); continue; }
255 };
256 match client.get_holdings(&record_ref).await {
257 Ok(holdings) => results.push(json!({"library_id":library_id,"library_name":library_name,"status":"found","catalogue_title":record.title,"checked_at":holdings.checked_at,"copies":holdings.copies})),
258 Err(error) => results.push(json!({"library_id":library_id,"library_name":library_name,"status":"error","error":error.to_string(),"copies":[]})),
259 }
260 }
261 serde_json::to_string(&json!({"title":title,"isbn":isbn,"libraries":results})).map_err(execution)
262 }
263}
264
265#[async_trait]
266impl Tool for RefreshCatalogue {
267 async fn execute(&self, context: &ToolContext, args: Value) -> Result<String, ToolError> {
268 let user = user(context)?;
269 let id = args["id"].as_str().filter(|value| !value.trim().is_empty()).ok_or_else(|| execution("id is required"))?;
270 let book = self.0.get(user, id).await.map_err(execution)?;
271 let client = RabelClient::new().map_err(execution)?;
272 let (_, item) = find_catalogue_record(&client, &book).await?.ok_or_else(|| execution("No exact matching RABEL record was found; collection data was left unchanged"))?;
273 let updated = self.0.update(user, id, BookUpdate {
274 title: item.title.clone(),
275 authors: Some(item.authors.clone()),
276 isbn: Some(item.isbn.clone()),
277 publisher: Some(item.publisher.clone()),
278 publication_year: Some(item.publication_year),
279 responsibility: Some(item.responsibility.clone()),
280 publication_statement: Some(item.publication_statement.clone()),
281 physical_description: Some(item.physical_description.clone()),
282 series: Some(item.series.clone()),
283 notes: Some(item.notes.clone()),
284 subjects: Some(item.subjects.clone()),
285 ..Default::default()
286 }).await.map_err(execution)?;
287 serde_json::to_string(&json!({"book":updated,"catalogue_item":item})).map_err(execution)
288 }
289}