Skip to main content

rpfm_server/
server_mcp.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! [Model Context Protocol][mcp] server exposed at the `/mcp` endpoint.
12//!
13//! Wraps every [`Command`] the [`crate::background_thread`] dispatcher
14//! understands as an MCP **tool**, plus a handful of MCP **resources**
15//! (game lists, enum dumps, examples, reference docs) and **prompts** for
16//! common workflows ("open and inspect a pack", "edit a DB table",
17//! "manage dependencies", …). Each MCP client gets its own dedicated
18//! [`Session`] and [`McpServer`] — same isolation guarantees as the
19//! WebSocket clients.
20//!
21//! Each tool call:
22//!
23//! 1. Translates its `*Args` payload into a [`Command`] and ships it
24//!    through the session's
25//!    [`background_loop`](crate::background_thread::background_loop) via
26//!    the `send_and_respond!` helper.
27//! 2. Wraps the resulting [`Response`] back into a [`CallToolResult`].
28//!
29//! The `*Args` structs are the canonical schema for every tool. Their
30//! `JsonSchema` derive is what `rmcp` ships to clients to advertise tool
31//! arguments, so docstrings on individual fields show up directly in MCP
32//! tool listings.
33//!
34//! [mcp]: https://modelcontextprotocol.io/
35//! [`Session`]: crate::session::Session
36//! [`CallToolResult`]: rmcp::model::CallToolResult
37
38use rmcp::ErrorData as McpError;
39use rmcp::handler::server::{router::prompt::PromptRouter, tool::ToolRouter, wrapper::Parameters};
40use rmcp::model::{
41    CallToolResult, CompletionInfo, CompleteRequestParams, CompleteResult,
42    ContentBlock, ErrorCode, ListResourcesResult, ListResourceTemplatesResult,
43    PaginatedRequestParams, PromptMessage,
44    ReadResourceRequestParams, ReadResourceResult, ReadResourceResponse,
45    Resource, ResourceContents, Role, ServerCapabilities, ServerInfo,
46};
47use rmcp::service::RequestContext;
48use rmcp::{prompt, prompt_handler, prompt_router, tool, tool_handler, tool_router, RoleServer};
49use schemars::JsonSchema;
50use serde::{Deserialize, Serialize};
51
52use std::collections::{BTreeMap, HashMap, HashSet};
53use std::sync::Arc;
54use std::path::PathBuf;
55
56use rpfm_extensions::merge::MergeOptions;
57
58use rpfm_ipc::helpers::DataSource;
59use rpfm_ipc::messages::{Command, Response};
60use rpfm_lib::files::{ContainerPath, RFile, RFileDecoded};
61use rpfm_telemetry::sentry;
62
63use crate::session::{Session, recv_response};
64
65//-------------------------------------------------------------------------------//
66//                              Helper macro
67//-------------------------------------------------------------------------------//
68
69/// Helper to send a command and return the JSON response.
70///
71/// Each tool call starts an independent Sentry transaction following the MCP tracing spec,
72/// so it gets reported regardless of the long-lived rmcp service span.
73macro_rules! send_and_respond {
74    ($self:expr, $tool_name:expr, $cmd:expr) => {{
75        let tx_ctx = sentry::TransactionContext::new(
76            &format!("tools/call {}", $tool_name),
77            "mcp.server",
78        );
79        let tx = sentry::start_transaction(tx_ctx);
80        tx.set_data("mcp.method.name", sentry::protocol::Value::from("tools/call"));
81        tx.set_data("mcp.tool.name", sentry::protocol::Value::from($tool_name));
82        tx.set_data("mcp.transport", sentry::protocol::Value::from("streamable-http"));
83
84        sentry::configure_scope(|scope| scope.set_span(Some(tx.clone().into())));
85
86        let mut receiver = $self.session.send($cmd);
87        let response = recv_response(&mut receiver).await;
88
89        tx.finish();
90
91        let is_error = matches!(&response, Response::Error(_));
92
93        let json = serde_json::to_string(&response).map_err(|e| McpError {
94            code: ErrorCode::INTERNAL_ERROR,
95            message: format!("Failed to serialize response: {e}").into(),
96            data: None,
97        })?;
98
99        if is_error {
100            Ok(CallToolResult::error(vec![ContentBlock::text(json)]))
101        } else {
102            Ok(CallToolResult::success(vec![ContentBlock::text(json)]))
103        }
104    }};
105}
106
107/// Build a `Resource` with common fields set.
108fn resource(uri: &str, name: &str, description: &str, mime_type: &str) -> Resource {
109    Resource::new(uri, name)
110        .with_description(description)
111        .with_mime_type(mime_type)
112}
113
114/// Parse a JSON string into the expected type, returning a tool-level error on failure.
115///
116/// This is a macro (not a function) so that `return Ok(...)` exits the calling tool method,
117/// keeping invalid-JSON errors as tool results instead of protocol-level `McpError`s that
118/// would tear down the MCP session.
119macro_rules! parse_json {
120    ($input:expr) => {
121        match serde_json::from_str($input) {
122            Ok(v) => v,
123            Err(e) => return Ok(CallToolResult::error(vec![ContentBlock::text(format!("Invalid JSON parameter: {e}"))])),
124        }
125    };
126}
127
128//-------------------------------------------------------------------------------//
129//                              Enums & Structs
130//-------------------------------------------------------------------------------//
131
132/// MCP server bound to a single [`Session`].
133///
134/// One instance is constructed per MCP client connection by the
135/// `StreamableHttpService` factory wired in `main.rs`. The
136/// `tool_router` and `prompt_router` fields are built once at construction
137/// time from the `#[tool_router]` / `#[prompt_router]` attribute macros
138/// applied further down in this module.
139///
140/// Cheap to clone — only `Arc` and small router structs.
141#[derive(Clone)]
142pub struct McpServer {
143    /// The session this MCP client is bound to.
144    session: Arc<Session>,
145    /// The router auto-generated from `#[tool_router]` annotations.
146    tool_router: ToolRouter<Self>,
147    /// The router auto-generated from `#[prompt_router]` annotations.
148    prompt_router: PromptRouter<Self>,
149}
150
151// -- Generic / Existing Args --
152
153#[derive(Debug, Deserialize, JsonSchema, Serialize)]
154#[schemars(description = "Call any IPC command directly.")]
155pub struct CallCommandArgs {
156    /// The JSON representation of the Command enum.
157    pub command: String,
158}
159
160#[derive(Debug, Deserialize, JsonSchema, Serialize)]
161pub struct OpenPackfilesArgs {
162    /// The paths of the PackFiles to open.
163    pub paths: Vec<PathBuf>,
164}
165
166#[derive(Debug, Deserialize, JsonSchema, Serialize)]
167pub struct SetGameSelectedArgs {
168    /// The name of the game to select.
169    pub game_name: String,
170    /// Whether to rebuild dependencies.
171    pub rebuild_dependencies: bool,
172}
173
174#[derive(Debug, Deserialize, JsonSchema, Serialize)]
175pub struct TsvExportArgs {
176    /// The key of the target pack.
177    pub pack_key: String,
178    /// The path of the TSV file to export to.
179    pub tsv_path: PathBuf,
180    /// The path of the table to export.
181    pub table_path: String,
182}
183
184#[derive(Debug, Deserialize, JsonSchema, Serialize)]
185pub struct TsvImportArgs {
186    /// The key of the target pack.
187    pub pack_key: String,
188    /// The path of the TSV file to import from.
189    pub tsv_path: PathBuf,
190    /// The path of the table to import to.
191    pub table_path: String,
192}
193
194#[derive(Debug, Deserialize, JsonSchema, Serialize)]
195pub struct DecodePackedFileArgs {
196    /// The key of the target pack.
197    pub pack_key: String,
198    /// The path of the file inside the data source.
199    pub path: String,
200    /// The data source to decode from.
201    pub source: DataSource,
202}
203
204// -- Pack Lifecycle Args --
205
206#[derive(Debug, Deserialize, JsonSchema, Serialize)]
207pub struct PathArg {
208    /// The file path.
209    pub path: PathBuf,
210}
211
212// -- Pack Key Args (multi-pack support) --
213
214#[derive(Debug, Deserialize, JsonSchema, Serialize)]
215pub struct PackKeyArg {
216    /// The key of the target pack. Use `list_open_packs` to get available keys.
217    pub pack_key: String,
218}
219
220#[derive(Debug, Deserialize, JsonSchema, Serialize)]
221pub struct PackKeyBoolArg {
222    /// The key of the target pack.
223    pub pack_key: String,
224    /// A boolean value.
225    pub value: bool,
226}
227
228#[derive(Debug, Deserialize, JsonSchema, Serialize)]
229pub struct PackKeyStringArg {
230    /// The key of the target pack.
231    pub pack_key: String,
232    /// A string value.
233    pub value: String,
234}
235
236#[derive(Debug, Deserialize, JsonSchema, Serialize)]
237pub struct PackKeyStringsArg {
238    /// The key of the target pack.
239    pub pack_key: String,
240    /// A list of string values.
241    pub values: Vec<String>,
242}
243
244#[derive(Debug, Deserialize, JsonSchema, Serialize)]
245pub struct PackKeyPathArg {
246    /// The key of the target pack.
247    pub pack_key: String,
248    /// The file path.
249    pub path: PathBuf,
250}
251
252// -- Pack Metadata Args --
253
254#[derive(Debug, Deserialize, JsonSchema, Serialize)]
255pub struct SetPackFileTypeArgs {
256    /// The key of the target pack.
257    pub pack_key: String,
258    /// The JSON representation of the PFHFileType enum.
259    pub pack_file_type: String,
260}
261
262#[derive(Debug, Deserialize, JsonSchema, Serialize)]
263pub struct ChangeCompressionFormatArgs {
264    /// The key of the target pack.
265    pub pack_key: String,
266    /// The JSON representation of the CompressionFormat enum.
267    pub format: String,
268}
269
270#[derive(Debug, Deserialize, JsonSchema, Serialize)]
271pub struct BoolArg {
272    /// A boolean value.
273    pub value: bool,
274}
275
276#[derive(Debug, Deserialize, JsonSchema, Serialize)]
277pub struct SetPackSettingsArgs {
278    /// The key of the target pack.
279    pub pack_key: String,
280    /// The JSON representation of the PackSettings struct.
281    pub settings: String,
282}
283
284#[derive(Debug, Deserialize, JsonSchema, Serialize)]
285pub struct SetDependencyPackFilesListArgs {
286    /// The key of the target pack.
287    pub pack_key: String,
288    /// The JSON representation of Vec<(bool, String)> for the dependency list.
289    pub list: String,
290}
291
292// -- File Operations Args --
293
294#[derive(Debug, Deserialize, JsonSchema, Serialize)]
295pub struct NewPackedFileArgs {
296    /// The key of the target pack.
297    pub pack_key: String,
298    /// The path for the new file inside the pack.
299    pub path: String,
300    /// The JSON representation of the NewFile enum.
301    pub new_file: String,
302}
303
304#[derive(Debug, Deserialize, JsonSchema, Serialize)]
305pub struct AddPackedFilesArgs {
306    /// The key of the target pack.
307    pub pack_key: String,
308    /// The source filesystem paths.
309    pub source_paths: Vec<PathBuf>,
310    /// The JSON representation of Vec<ContainerPath> for destination paths.
311    pub destination_paths: String,
312    /// The optional paths to ignore (JSON representation of Option<Vec<PathBuf>>).
313    pub ignore_paths: Option<Vec<PathBuf>>,
314}
315
316#[derive(Debug, Deserialize, JsonSchema, Serialize)]
317pub struct AddPackedFilesFromPackFileArgs {
318    /// The key of the target pack.
319    pub pack_key: String,
320    /// The key of the source PackFile.
321    pub source_pack_path: String,
322    /// The JSON representation of Vec<ContainerPath> for files to add.
323    pub container_paths: String,
324}
325
326#[derive(Debug, Deserialize, JsonSchema, Serialize)]
327pub struct AddPackedFilesFromPackFileToAnimpackArgs {
328    /// The key of the source pack the files are copied from.
329    pub source_pack_key: String,
330    /// The key of the pack that owns the target AnimPack (may differ from the source).
331    pub pack_key: String,
332    /// The animpack path.
333    pub animpack_path: String,
334    /// The JSON representation of Vec<ContainerPath> for files to add.
335    pub container_paths: String,
336}
337
338#[derive(Debug, Deserialize, JsonSchema, Serialize)]
339pub struct AddPackedFilesFromAnimpackArgs {
340    /// The key of the pack that owns the AnimPack (only used when `source` is a PackFile).
341    pub anim_pack_key: String,
342    /// The key of the destination pack the files are copied into (may differ from the AnimPack's).
343    pub pack_key: String,
344    /// The data source to get the animpack from.
345    pub source: DataSource,
346    /// The animpack path.
347    pub animpack_path: String,
348    /// The JSON representation of Vec<ContainerPath> for files to add.
349    pub container_paths: String,
350}
351
352#[derive(Debug, Deserialize, JsonSchema, Serialize)]
353pub struct ContainerPathsArg {
354    /// The key of the target pack.
355    pub pack_key: String,
356    /// The JSON representation of Vec<ContainerPath>.
357    pub paths: String,
358}
359
360#[derive(Debug, Deserialize, JsonSchema, Serialize)]
361pub struct DeleteFromAnimpackArgs {
362    /// The key of the target pack.
363    pub pack_key: String,
364    /// The animpack path.
365    pub animpack_path: String,
366    /// The JSON representation of Vec<ContainerPath> for files to delete.
367    pub container_paths: String,
368}
369
370#[derive(Debug, Deserialize, JsonSchema, Serialize)]
371pub struct ExtractPackedFilesArgs {
372    /// The key of the target pack.
373    pub pack_key: String,
374    /// The JSON representation of BTreeMap<DataSource, Vec<ContainerPath>>.
375    pub source_paths: String,
376    /// The destination path on disk.
377    pub destination_path: PathBuf,
378    /// Whether to export tables as TSV.
379    pub export_as_tsv: bool,
380}
381
382#[derive(Debug, Deserialize, JsonSchema, Serialize)]
383pub struct RenamePackedFilesArgs {
384    /// The key of the target pack.
385    pub pack_key: String,
386    /// The JSON representation of Vec<(ContainerPath, ContainerPath)>.
387    pub renames: String,
388}
389
390#[derive(Debug, Deserialize, JsonSchema, Serialize)]
391pub struct CopyOrCutPackedFilesArgs {
392    /// A JSON object mapping pack key to ContainerPath arrays, e.g. {"my_pack.pack": [{"File": "db/table/file"}]}.
393    pub paths_by_pack: String,
394}
395
396#[derive(Debug, Deserialize, JsonSchema, Serialize)]
397pub struct PastePackedFilesArgs {
398    /// The key of the target pack to paste into.
399    pub pack_key: String,
400    /// The destination folder path inside the pack (use empty string for root).
401    pub destination_path: String,
402}
403
404#[derive(Debug, Deserialize, JsonSchema, Serialize)]
405pub struct DuplicatePackedFilesArgs {
406    /// The key of the target pack.
407    pub pack_key: String,
408    /// The JSON representation of Vec<ContainerPath> for files to duplicate.
409    pub paths: String,
410}
411
412#[derive(Debug, Deserialize, JsonSchema, Serialize)]
413pub struct SavePackedFileFromViewArgs {
414    /// The key of the target pack.
415    pub pack_key: String,
416    /// The path of the file inside the pack.
417    pub path: String,
418    /// The JSON representation of the RFileDecoded enum.
419    pub data: String,
420}
421
422#[derive(Debug, Deserialize, JsonSchema, Serialize)]
423pub struct SavePackedFileFromExternalViewArgs {
424    /// The key of the target pack.
425    pub pack_key: String,
426    /// The internal path of the file in the pack.
427    pub internal_path: String,
428    /// The external file path on disk.
429    pub external_path: PathBuf,
430}
431
432#[derive(Debug, Deserialize, JsonSchema, Serialize)]
433pub struct SavePackedFilesToPackFileAndCleanArgs {
434    /// The key of the target pack.
435    pub pack_key: String,
436    /// The JSON representation of Vec<RFile>.
437    pub files: String,
438    /// Whether to optimize after saving.
439    pub optimize: bool,
440}
441
442#[derive(Debug, Deserialize, JsonSchema, Serialize)]
443pub struct StringArg {
444    /// A string value.
445    pub value: String,
446}
447
448#[derive(Debug, Deserialize, JsonSchema, Serialize)]
449pub struct OpenPackedFileInExternalProgramArgs {
450    /// The key of the target pack.
451    pub pack_key: String,
452    /// The data source of the file.
453    pub source: DataSource,
454    /// The JSON representation of the ContainerPath.
455    pub container_path: String,
456}
457
458#[derive(Debug, Deserialize, JsonSchema, Serialize)]
459pub struct StringsArg {
460    /// A list of string values.
461    pub values: Vec<String>,
462}
463
464// -- Dependency Args --
465
466#[derive(Debug, Deserialize, JsonSchema, Serialize)]
467pub struct ImportDependenciesArgs {
468    /// The key of the target pack.
469    pub pack_key: String,
470    /// The JSON representation of BTreeMap<DataSource, Vec<ContainerPath>>.
471    pub paths: String,
472}
473
474#[derive(Debug, Deserialize, JsonSchema, Serialize)]
475pub struct GetRFilesFromAllSourcesArgs {
476    /// The JSON representation of Vec<ContainerPath>.
477    pub paths: String,
478    /// Whether to lowercase paths.
479    pub lowercase: bool,
480}
481
482#[derive(Debug, Deserialize, JsonSchema, Serialize)]
483pub struct ContainerPathArg {
484    /// The JSON representation of the ContainerPath.
485    pub path: String,
486}
487
488// -- Search Args --
489
490#[derive(Debug, Deserialize, JsonSchema, Serialize)]
491pub struct GlobalSearchArgs {
492    /// The key of the target pack.
493    pub pack_key: String,
494    /// The JSON representation of the GlobalSearch struct.
495    pub search: String,
496}
497
498#[derive(Debug, Deserialize, JsonSchema, Serialize)]
499pub struct GlobalSearchReplaceMatchesArgs {
500    /// The key of the target pack.
501    pub pack_key: String,
502    /// The JSON representation of the GlobalSearch struct.
503    pub search: String,
504    /// The JSON representation of Vec<MatchHolder>.
505    pub matches: String,
506}
507
508#[derive(Debug, Deserialize, JsonSchema, Serialize)]
509pub struct SearchReferencesArgs {
510    /// The key of the target pack.
511    pub pack_key: String,
512    /// The JSON representation of HashMap<String, Vec<String>>.
513    pub reference_map: String,
514    /// The value to search for.
515    pub value: String,
516}
517
518#[derive(Debug, Deserialize, JsonSchema, Serialize)]
519pub struct GetReferenceDataFromDefinitionArgs {
520    /// The key of the target pack.
521    pub pack_key: String,
522    /// The table name.
523    pub table_name: String,
524    /// The JSON representation of the Definition struct.
525    pub definition: String,
526    /// Force local reference regeneration.
527    pub force: bool,
528}
529
530#[derive(Debug, Deserialize, JsonSchema, Serialize)]
531pub struct GoToDefinitionArgs {
532    /// The key of the target pack.
533    pub pack_key: String,
534    /// The table name.
535    pub table_name: String,
536    /// The column name.
537    pub column_name: String,
538    /// The values to search for.
539    pub values: Vec<String>,
540}
541
542// -- Schema Args --
543
544#[derive(Debug, Deserialize, JsonSchema, Serialize)]
545pub struct SaveSchemaArgs {
546    /// The JSON representation of the Schema struct.
547    pub schema: String,
548}
549
550#[derive(Debug, Deserialize, JsonSchema, Serialize)]
551pub struct StringI32Args {
552    /// A string value (e.g., table name).
553    pub name: String,
554    /// An integer value (e.g., version).
555    pub version: i32,
556}
557
558#[derive(Debug, Deserialize, JsonSchema, Serialize)]
559pub struct ReferencingColumnsForDefinitionArgs {
560    /// The table name.
561    pub table_name: String,
562    /// The JSON representation of the Definition struct.
563    pub definition: String,
564}
565
566#[derive(Debug, Deserialize, JsonSchema, Serialize)]
567pub struct DefinitionArg {
568    /// The JSON representation of the Definition struct.
569    pub definition: String,
570}
571
572#[derive(Debug, Deserialize, JsonSchema, Serialize)]
573pub struct SchemaPatchArgs {
574    /// The JSON representation of HashMap<String, DefinitionPatch>.
575    pub patches: String,
576}
577
578// -- Table Ops Args --
579
580#[derive(Debug, Deserialize, JsonSchema, Serialize)]
581pub struct MergeFilesArgs {
582    /// The key of the target pack.
583    pub pack_key: String,
584    /// The JSON representation of Vec<ContainerPath> for files to merge.
585    pub paths: String,
586    /// The path for the merged file.
587    pub merged_path: String,
588    /// Whether to delete source files after merging.
589    pub delete_source: bool,
590    /// Merge rows by key instead of concatenating them. If some rows can't be reconciled
591    /// automatically, nothing is written and the response is `Response::MergeConflicts` instead.
592    /// Defaults to false.
593    #[serde(default)]
594    pub delta_merge: bool,
595}
596
597#[derive(Debug, Deserialize, JsonSchema, Serialize)]
598pub struct CascadeEditionArgs {
599    /// The key of the target pack.
600    pub pack_key: String,
601    /// The table name.
602    pub table_name: String,
603    /// The JSON representation of the Definition struct.
604    pub definition: String,
605    /// The JSON representation of Vec<(Field, String, String)> for field changes.
606    pub changes: String,
607}
608
609#[derive(Debug, Deserialize, JsonSchema, Serialize)]
610pub struct AddKeysToKeyDeletesArgs {
611    /// The key of the target pack.
612    pub pack_key: String,
613    /// The table file name.
614    pub table_file_name: String,
615    /// The key table name.
616    pub key_table_name: String,
617    /// The keys to add.
618    pub keys: HashSet<String>,
619}
620
621// -- Diagnostics Args --
622
623#[derive(Debug, Deserialize, JsonSchema, Serialize)]
624pub struct DiagnosticsCheckArgs {
625    /// The list of ignored diagnostics.
626    pub ignored: Vec<String>,
627    /// Whether to check AK-only references.
628    pub check_ak_only_refs: bool,
629}
630
631#[derive(Debug, Deserialize, JsonSchema, Serialize)]
632pub struct DiagnosticsUpdateArgs {
633    /// The JSON representation of the Diagnostics struct.
634    pub diagnostics: String,
635    /// The JSON representation of Vec<ContainerPath> for paths to check.
636    pub paths: String,
637    /// Whether to check AK-only references.
638    pub check_ak_only_refs: bool,
639}
640
641// -- Notes Args --
642
643#[derive(Debug, Deserialize, JsonSchema, Serialize)]
644pub struct AddNoteArgs {
645    /// The key of the target pack.
646    pub pack_key: String,
647    /// The JSON representation of the Note struct.
648    pub note: String,
649}
650
651#[derive(Debug, Deserialize, JsonSchema, Serialize)]
652pub struct DeleteNoteArgs {
653    /// The key of the target pack.
654    pub pack_key: String,
655    /// The path the note belongs to.
656    pub path: String,
657    /// The note ID.
658    pub id: u64,
659}
660
661// -- Optimization Args --
662
663#[derive(Debug, Deserialize, JsonSchema, Serialize)]
664pub struct OptimizePackFileArgs {
665    /// The key of the target pack.
666    pub pack_key: String,
667    /// The JSON representation of the OptimizerOptions struct.
668    pub options: String,
669}
670
671// -- Settings Args --
672
673#[derive(Debug, Deserialize, JsonSchema, Serialize)]
674pub struct SettingsSetBoolArgs {
675    /// The setting key.
676    pub key: String,
677    /// The boolean value.
678    pub value: bool,
679}
680
681#[derive(Debug, Deserialize, JsonSchema, Serialize)]
682pub struct SettingsSetI32Args {
683    /// The setting key.
684    pub key: String,
685    /// The integer value.
686    pub value: i32,
687}
688
689#[derive(Debug, Deserialize, JsonSchema, Serialize)]
690pub struct SettingsSetF32Args {
691    /// The setting key.
692    pub key: String,
693    /// The float value.
694    pub value: f32,
695}
696
697#[derive(Debug, Deserialize, JsonSchema, Serialize)]
698pub struct SettingsSetStringArgs {
699    /// The setting key.
700    pub key: String,
701    /// The string value.
702    pub value: String,
703}
704
705#[derive(Debug, Deserialize, JsonSchema, Serialize)]
706pub struct SettingsSetPathBufArgs {
707    /// The setting key.
708    pub key: String,
709    /// The path value.
710    pub value: PathBuf,
711}
712
713#[derive(Debug, Deserialize, JsonSchema, Serialize)]
714pub struct SettingsSetVecStringArgs {
715    /// The setting key.
716    pub key: String,
717    /// The list of string values.
718    pub value: Vec<String>,
719}
720
721#[derive(Debug, Deserialize, JsonSchema, Serialize)]
722pub struct SettingsSetVecRawArgs {
723    /// The setting key.
724    pub key: String,
725    /// The raw byte values.
726    pub value: Vec<u8>,
727}
728
729// -- Specialized Args --
730
731#[derive(Debug, Deserialize, JsonSchema, Serialize)]
732pub struct InitializeMyModFolderArgs {
733    /// The mod name.
734    pub name: String,
735    /// The game key.
736    pub game: String,
737    /// Whether to add Sublime Text support.
738    pub sublime: bool,
739    /// Whether to add VS Code support.
740    pub vscode: bool,
741    /// Optional gitignore template content.
742    pub gitignore: Option<String>,
743}
744
745#[derive(Debug, Deserialize, JsonSchema, Serialize)]
746pub struct PackMapArgs {
747    /// The key of the target pack.
748    pub pack_key: String,
749    /// The tile map paths.
750    pub tile_maps: Vec<PathBuf>,
751    /// The JSON representation of Vec<(PathBuf, String)> for tile path/name pairs.
752    pub tiles: String,
753}
754
755#[derive(Debug, Deserialize, JsonSchema, Serialize)]
756pub struct BuildStarposArgs {
757    /// The key of the target pack.
758    pub pack_key: String,
759    /// The campaign ID.
760    pub campaign_id: String,
761    /// Whether to process HLP/SPD data.
762    pub process_hlp_spd: bool,
763}
764
765#[derive(Debug, Deserialize, JsonSchema, Serialize)]
766pub struct UpdateAnimIdsArgs {
767    /// The key of the target pack.
768    pub pack_key: String,
769    /// The starting animation ID.
770    pub starting_id: i32,
771    /// The offset to apply.
772    pub offset: i32,
773}
774
775#[derive(Debug, Deserialize, JsonSchema, Serialize)]
776pub struct ExportRigidToGltfArgs {
777    /// The JSON representation of the RigidModel struct.
778    pub rigid_model: String,
779    /// The output path.
780    pub output_path: String,
781}
782
783#[derive(Debug, Deserialize, JsonSchema, Serialize)]
784pub struct SetVideoFormatArgs {
785    /// The key of the target pack.
786    pub pack_key: String,
787    /// The path of the video file in the pack.
788    pub path: String,
789    /// The JSON representation of the SupportedFormats enum.
790    pub format: String,
791}
792
793#[derive(Debug, Deserialize, JsonSchema, Serialize)]
794pub struct GetPackTranslationArgs {
795    /// The key of the target pack.
796    pub pack_key: String,
797    /// The language code.
798    pub language: String,
799}
800
801//-------------------------------------------------------------------------------//
802//                             Implementations
803//-------------------------------------------------------------------------------//
804
805#[tool_handler(router = self.tool_router)]
806#[prompt_handler(router = self.prompt_router)]
807impl rmcp::ServerHandler for McpServer {
808    fn get_info(&self) -> ServerInfo {
809        let capabilities = ServerCapabilities::builder()
810            .enable_tools()
811            .enable_prompts()
812            .enable_resources()
813            .enable_completions()
814            .build();
815
816        // `ServerInfo` is `#[non_exhaustive]` in rmcp, so it must be built through its constructor instead of a struct literal.
817        ServerInfo::new(capabilities).with_instructions("\
818This is the MCP server for RPFM (Rusted PackFile Manager), a tool for modding Total War games by \
819Creative Assembly. It lets you read, edit, create, and manage PackFiles (.pack) — the archive \
820format used by all modern Total War titles.
821
822## Key Concepts
823
824- **PackFile**: An archive containing game data files (DB tables, localisation, textures, models, etc.). \
825  Mods are distributed as PackFiles.
826- **pack_key**: When you open one or more PackFiles, each gets a unique key string. Use `list_open_packs` \
827  to discover available keys. Most tools require a `pack_key` parameter.
828- **DataSource**: Where data lives — `\"PackFile\"` (the user's mod), `\"GameFiles\"` (vanilla game data), \
829  `\"ParentFiles\"` (dependency mods), `\"AssKitFiles\"` (Assembly Kit data), `\"ExternalFile\"` (disk file).
830- **ContainerPath**: A path inside a pack — either `{\"File\": \"db/land_units_tables/my_table\"}` or \
831  `{\"Folder\": \"db/land_units_tables\"}`. Use an empty string for root folder.
832
833## Required Initialization Sequence
834
8351. **Set the game** — Call `set_game_selected` with the game key (e.g. `\"warhammer_3\"`) and \
836   `rebuild_dependencies: true`. This loads schemas and vanilla data.
8372. **Open a pack** — Call `open_packfiles` with filesystem path(s). Note the returned pack key(s).
8383. **Verify schema** — Call `is_schema_loaded`; if false, call `update_schemas` first.
839
840## Supported Games
841
842Valid game keys: `pharaoh_dynasties`, `pharaoh`, `warhammer_3`, `troy`, `three_kingdoms`, \
843`warhammer_2`, `warhammer`, `thrones_of_britannia`, `attila`, `rome_2`, `shogun_2`, `napoleon`, \
844`empire`, `arena`.
845
846## Common File Path Conventions
847
848- DB tables: `db/<table_name>/<file_name>` (e.g. `db/land_units_tables/my_mod`)
849- Localisation: `text/db/<file_name>.loc`
850- Scripts: `script/<path>.lua`
851- Images: `ui/<path>.png`
852
853## Pack File Types (PFHFileType)
854
855`\"Boot\"`, `\"Release\"`, `\"Patch\"`, `\"Mod\"` (default for mods), `\"Movie\"`.
856
857## Compression Formats
858
859`\"None\"` (default), `\"Lzma1\"` (legacy), `\"Lz4\"` (WH3 6.2+), `\"Zstd\"` (WH3 6.2+).
860
861## Creating New Files (NewFile)
862
863- DB table: `{\"DB\": [\"file_name\", \"table_name\", version]}` — e.g. `{\"DB\": [\"my_mod\", \"land_units_tables\", 0]}`
864- Loc file: `{\"Loc\": \"file_name\"}`
865- Text file: `{\"Text\": [\"file_name\", \"Plain\"]}` — formats: `\"Plain\"`, `\"Html\"`, `\"Xml\"`, `\"Lua\"`, `\"Cpp\"`, `\"Json\"`, `\"Markdown\"`, `\"Smithy\"`
866- AnimPack: `{\"AnimPack\": \"file_name\"}`
867- PortraitSettings: `{\"PortraitSettings\": [\"file_name\", version, [[\"entry_key\", \"entry_value\"]]]}`
868- VMD: `{\"VMD\": \"file_name\"}`
869- WSModel: `{\"WSModel\": \"file_name\"}`
870
871## Resources
872
873Use `resources/list` and `resources/read` to browse reference data: valid enum values, game lists, \
874and example JSON payloads without needing tool calls.
875
876## Responses
877
878All tool responses are JSON-serialized. On failure, an error message is returned instead of the expected data.
879")
880    }
881
882    //-----------------------------------------------------------------------//
883    // Resources
884    //-----------------------------------------------------------------------//
885
886    async fn list_resources(
887        &self,
888        _request: Option<PaginatedRequestParams>,
889        _context: RequestContext<RoleServer>,
890    ) -> Result<ListResourcesResult, McpError> {
891        let resources = vec![
892            resource("rpfm://games", "games", "List of all supported Total War game keys.", "application/json"),
893            resource("rpfm://enums/PFHFileType", "PFHFileType", "Valid PackFile type values (Boot, Release, Patch, Mod, Movie).", "application/json"),
894            resource("rpfm://enums/CompressionFormat", "CompressionFormat", "Valid compression format values (None, Lzma1, Lz4, Zstd).", "application/json"),
895            resource("rpfm://enums/DataSource", "DataSource", "Valid data source values indicating where data comes from.", "application/json"),
896            resource("rpfm://enums/ContainerPath", "ContainerPath", "ContainerPath enum variants with JSON examples.", "application/json"),
897            resource("rpfm://enums/NewFile", "NewFile", "NewFile enum variants for creating files inside packs, with JSON examples.", "application/json"),
898            resource("rpfm://enums/SupportedFormats", "SupportedFormats", "Valid video format values (CaVp8, Ivf).", "application/json"),
899            resource("rpfm://examples/global_search", "GlobalSearch example", "Example JSON for the GlobalSearch struct used by search tools.", "application/json"),
900            resource("rpfm://examples/optimizer_options", "OptimizerOptions example", "Example JSON for OptimizerOptions with all boolean fields.", "application/json"),
901            resource("rpfm://reference/initialization", "Initialization guide", "Step-by-step guide for initializing the RPFM MCP server session.", "text/plain"),
902            resource("rpfm://reference/path_conventions", "Path conventions", "Common file path conventions inside Total War PackFiles.", "text/plain"),
903        ];
904        Ok(ListResourcesResult {
905            resources,
906            ..Default::default()
907        })
908    }
909
910    async fn list_resource_templates(
911        &self,
912        _request: Option<PaginatedRequestParams>,
913        _context: RequestContext<RoleServer>,
914    ) -> Result<ListResourceTemplatesResult, McpError> {
915        Ok(ListResourceTemplatesResult {
916            resource_templates: vec![],
917            ..Default::default()
918        })
919    }
920
921    async fn read_resource(
922        &self,
923        request: ReadResourceRequestParams,
924        _context: RequestContext<RoleServer>,
925    ) -> Result<ReadResourceResponse, McpError> {
926        let uri = &request.uri;
927        let content = match uri.as_str() {
928            "rpfm://games" => serde_json::json!({
929                "supported_games": [
930                    {"key": "pharaoh_dynasties", "display_name": "Total War: Pharaoh Dynasties"},
931                    {"key": "pharaoh", "display_name": "Total War: Pharaoh"},
932                    {"key": "warhammer_3", "display_name": "Total War: Warhammer III"},
933                    {"key": "troy", "display_name": "A Total War Saga: Troy"},
934                    {"key": "three_kingdoms", "display_name": "Total War: Three Kingdoms"},
935                    {"key": "warhammer_2", "display_name": "Total War: Warhammer II"},
936                    {"key": "warhammer", "display_name": "Total War: Warhammer"},
937                    {"key": "thrones_of_britannia", "display_name": "A Total War Saga: Thrones of Britannia"},
938                    {"key": "attila", "display_name": "Total War: Attila"},
939                    {"key": "rome_2", "display_name": "Total War: Rome II"},
940                    {"key": "shogun_2", "display_name": "Total War: Shogun 2"},
941                    {"key": "napoleon", "display_name": "Total War: Napoleon"},
942                    {"key": "empire", "display_name": "Total War: Empire"},
943                    {"key": "arena", "display_name": "Total War: Arena"}
944                ]
945            }).to_string(),
946
947            "rpfm://enums/PFHFileType" => serde_json::json!({
948                "enum": "PFHFileType",
949                "description": "The type/priority of a PackFile. Games load packs in type order (Boot first, Movie last).",
950                "variants": [
951                    {"name": "Boot", "value": 0, "description": "Core game boot files, loaded first."},
952                    {"name": "Release", "value": 1, "description": "Main game data files."},
953                    {"name": "Patch", "value": 2, "description": "Official patch and update files."},
954                    {"name": "Mod", "value": 3, "description": "User mod files. This is the default for mods."},
955                    {"name": "Movie", "value": 4, "description": "Cinematic and always-loaded files, loaded last."}
956                ],
957                "json_example": "\"Mod\""
958            }).to_string(),
959
960            "rpfm://enums/CompressionFormat" => serde_json::json!({
961                "enum": "CompressionFormat",
962                "description": "Compression algorithm for pack file data.",
963                "variants": [
964                    {"name": "None", "description": "No compression (default)."},
965                    {"name": "Lzma1", "description": "Legacy LZMA compression (all PFH5 games)."},
966                    {"name": "Lz4", "description": "LZ4 compression (Warhammer 3 v6.2+)."},
967                    {"name": "Zstd", "description": "Zstandard compression (Warhammer 3 v6.2+)."}
968                ],
969                "json_example": "\"None\""
970            }).to_string(),
971
972            "rpfm://enums/DataSource" => serde_json::json!({
973                "enum": "DataSource",
974                "description": "Identifies where data comes from when working with files.",
975                "variants": [
976                    {"name": "PackFile", "description": "Data from the user's currently open pack (mod files)."},
977                    {"name": "GameFiles", "description": "Data from vanilla game files."},
978                    {"name": "ParentFiles", "description": "Data from parent/dependency pack files."},
979                    {"name": "AssKitFiles", "description": "Data from the Assembly Kit (modding tools)."},
980                    {"name": "ExternalFile", "description": "Data from an external file on disk."}
981                ],
982                "json_example": "\"PackFile\""
983            }).to_string(),
984
985            "rpfm://enums/ContainerPath" => serde_json::json!({
986                "enum": "ContainerPath",
987                "description": "A path reference inside a PackFile, pointing to either a file or a folder.",
988                "variants": [
989                    {
990                        "name": "File",
991                        "description": "Path to a single file inside the pack.",
992                        "json_example": {"File": "db/land_units_tables/my_table"}
993                    },
994                    {
995                        "name": "Folder",
996                        "description": "Path to a folder inside the pack. Use empty string for root.",
997                        "json_example": {"Folder": "db/land_units_tables"}
998                    }
999                ],
1000                "usage_notes": "Most tools accept a JSON array of ContainerPath objects, e.g. [{\"File\": \"path1\"}, {\"Folder\": \"path2\"}]"
1001            }).to_string(),
1002
1003            "rpfm://enums/NewFile" => serde_json::json!({
1004                "enum": "NewFile",
1005                "description": "Specifies what type of file to create inside a pack.",
1006                "variants": [
1007                    {
1008                        "name": "DB",
1009                        "description": "Create a new DB table. Args: [file_name, table_name, version].",
1010                        "json_example": {"DB": ["my_mod", "land_units_tables", 0]}
1011                    },
1012                    {
1013                        "name": "Loc",
1014                        "description": "Create a new localisation file. Arg: file_name.",
1015                        "json_example": {"Loc": "my_mod"}
1016                    },
1017                    {
1018                        "name": "Text",
1019                        "description": "Create a new text file. Args: [file_name, format]. Formats: Bat, Cpp, Html, Hlsl, Json, Js, Css, Lua, Markdown, Plain, Python, Sql, Xml, Yaml.",
1020                        "json_example": {"Text": ["my_script", "Lua"]}
1021                    },
1022                    {
1023                        "name": "AnimPack",
1024                        "description": "Create a new AnimPack file. Arg: file_name.",
1025                        "json_example": {"AnimPack": "my_anim"}
1026                    },
1027                    {
1028                        "name": "PortraitSettings",
1029                        "description": "Create a new portrait settings file. Args: [file_name, version, entries].",
1030                        "json_example": {"PortraitSettings": ["my_portraits", 3, []]}
1031                    },
1032                    {
1033                        "name": "VMD",
1034                        "description": "Create a new VMD file. Arg: file_name.",
1035                        "json_example": {"VMD": "my_vmd"}
1036                    },
1037                    {
1038                        "name": "WSModel",
1039                        "description": "Create a new WSModel file. Arg: file_name.",
1040                        "json_example": {"WSModel": "my_model"}
1041                    }
1042                ]
1043            }).to_string(),
1044
1045            "rpfm://enums/SupportedFormats" => serde_json::json!({
1046                "enum": "SupportedFormats",
1047                "description": "Video format options for CA VP8 video files.",
1048                "variants": [
1049                    {"name": "CaVp8", "description": "CA's custom VP8 format (default)."},
1050                    {"name": "Ivf", "description": "Standard VP8 IVF format."}
1051                ],
1052                "json_example": "\"CaVp8\""
1053            }).to_string(),
1054
1055            "rpfm://examples/global_search" => serde_json::json!({
1056                "description": "Example GlobalSearch JSON for use with global_search, global_search_replace_all, etc.",
1057                "example": {
1058                    "pattern": "old_unit_name",
1059                    "replace_text": "new_unit_name",
1060                    "case_sensitive": false,
1061                    "use_regex": false,
1062                    "sources": [{"Pack": "my_mod.pack"}],
1063                    "search_on": {
1064                        "anim": false, "anim_fragment_battle": false, "anim_pack": false,
1065                        "anims_table": false, "atlas": false, "audio": false, "bmd": false,
1066                        "db": true, "esf": false, "group_formations": false, "image": false,
1067                        "loc": true, "matched_combat": false, "pack": false,
1068                        "portrait_settings": false, "rigid_model": false, "sound_bank": false,
1069                        "text": true, "uic": false, "unit_variant": false, "unknown": false,
1070                        "video": false, "schema": false
1071                    },
1072                    "matches": {
1073                        "anim": [], "anim_fragment_battle": [], "anim_pack": [],
1074                        "anims_table": [], "atlas": [], "audio": [], "bmd": [],
1075                        "db": [], "esf": [], "group_formations": [], "image": [],
1076                        "loc": [], "matched_combat": [], "pack": [],
1077                        "portrait_settings": [], "rigid_model": [], "sound_bank": [],
1078                        "text": [], "uic": [], "unit_variant": [], "unknown": [],
1079                        "video": [], "schema": {"matches": []}
1080                    },
1081                    "game_key": "warhammer_3"
1082                },
1083                "notes": "The `matches` field is populated by the search results. When calling `global_search`, pass it empty. The `sources` field uses SearchSource: {\"Pack\": \"key\"}, \"ParentFiles\", \"GameFiles\", \"AssKitFiles\"."
1084            }).to_string(),
1085
1086            "rpfm://examples/optimizer_options" => serde_json::json!({
1087                "description": "OptimizerOptions struct with all boolean fields for pack optimization.",
1088                "example": {
1089                    "pack_remove_itm_files": true,
1090                    "pack_apply_compression": true,
1091                    "pack_remove_duplicated_files": false,
1092                    "db_import_datacores_into_twad_key_deletes": false,
1093                    "db_optimize_datacored_tables": false,
1094                    "table_remove_duplicated_entries": true,
1095                    "table_remove_itm_entries": true,
1096                    "table_remove_itnr_entries": true,
1097                    "table_remove_empty_file": true,
1098                    "text_remove_unused_xml_map_folders": false,
1099                    "text_remove_unused_xml_prefab_folder": false,
1100                    "text_remove_agf_files": false,
1101                    "text_remove_model_statistics_files": false,
1102                    "pts_remove_unused_art_sets": false,
1103                    "pts_remove_unused_variants": false,
1104                    "pts_remove_empty_masks": false,
1105                    "pts_remove_empty_file": false
1106                },
1107                "field_descriptions": {
1108                    "pack_remove_itm_files": "Remove files identical to vanilla (Identical To Master).",
1109                    "pack_apply_compression": "Apply the most modern compression format the active game supports (overriding the pack's configured one), so the next save compresses the files.",
1110                    "pack_remove_duplicated_files": "Remove case-insensitively duplicated files (same name ignoring casing) when their contents are identical, keeping the all-lowercase one or, failing that, the last one.",
1111                    "db_import_datacores_into_twad_key_deletes": "Import datacored tables into TWAD key deletes.",
1112                    "db_optimize_datacored_tables": "Optimize datacored tables.",
1113                    "table_remove_duplicated_entries": "Remove duplicate rows in tables.",
1114                    "table_remove_itm_entries": "Remove rows identical to vanilla.",
1115                    "table_remove_itnr_entries": "Remove rows identical to vanilla that are not referenced.",
1116                    "table_remove_empty_file": "Remove tables with no rows.",
1117                    "text_remove_unused_xml_map_folders": "Remove unused XML files in map folders.",
1118                    "text_remove_unused_xml_prefab_folder": "Remove unused XML files in prefab folders.",
1119                    "text_remove_agf_files": "Remove AGF files.",
1120                    "text_remove_model_statistics_files": "Remove model statistics files.",
1121                    "pts_remove_unused_art_sets": "Remove unused art sets in portrait settings.",
1122                    "pts_remove_unused_variants": "Remove unused variants in portrait settings.",
1123                    "pts_remove_empty_masks": "Remove empty masks in portrait settings.",
1124                    "pts_remove_empty_file": "Remove empty portrait settings files."
1125                }
1126            }).to_string(),
1127
1128            "rpfm://reference/initialization" => "\
1129RPFM MCP Server Initialization Guide
1130=====================================
1131
1132Before you can work with PackFiles, you must initialize the server session:
1133
1134Step 1: Set the game
1135    Call: set_game_selected(game_name: \"warhammer_3\", rebuild_dependencies: true)
1136    This loads the correct schemas and vanilla game data for the selected title.
1137    Valid game keys: pharaoh_dynasties, pharaoh, warhammer_3, troy, three_kingdoms,
1138    warhammer_2, warhammer, thrones_of_britannia, attila, rome_2, shogun_2,
1139    napoleon, empire, arena.
1140
1141Step 2: Verify schema is loaded
1142    Call: is_schema_loaded()
1143    If it returns false, call update_schemas() to download the latest schemas.
1144
1145Step 3: Open a PackFile
1146    Call: open_packfiles(paths: [\"/path/to/my_mod.pack\"])
1147    The response returns pack info including the pack_key you'll use for all
1148    subsequent operations.
1149
1150Step 4: Verify dependencies (optional but recommended)
1151    Call: is_there_a_dependency_database(value: true)
1152    If false, call generate_dependencies_cache() to build the dependency database.
1153
1154After initialization, use list_open_packs() to see all open pack keys at any time.
1155".to_string(),
1156
1157            "rpfm://reference/path_conventions" => "\
1158Total War PackFile Path Conventions
1159====================================
1160
1161Files inside PackFiles follow specific path conventions:
1162
1163DB Tables:
1164    db/<table_name>/<file_name>
1165    Example: db/land_units_tables/my_mod
1166    Example: db/unit_stats_land_tables/custom_units
1167
1168Localisation (Loc) files:
1169    text/db/<file_name>.loc
1170    text/<file_name>.loc
1171    Example: text/db/my_mod.loc
1172
1173Scripts:
1174    script/<path>.lua
1175    script/campaign/mod/<script_name>.lua
1176    Example: script/campaign/mod/my_mod_script.lua
1177
1178UI Images:
1179    ui/<path>.png
1180    Path may vary depending on the purpose of the image.
1181
1182Models and Animations:
1183    variantmeshes/<path>
1184    animations/<path>
1185    Example: variantmeshes/wh_variantmodels/hu1/my_unit/my_unit.wsmodel
1186
1187Audio:
1188    audio/<path>.bnk
1189
1190Maps:
1191    terrain/tiles/battle/<map_name>/
1192".to_string(),
1193
1194            _ => {
1195                return Err(McpError {
1196                    code: ErrorCode::INVALID_PARAMS,
1197                    message: format!("Unknown resource URI: {uri}").into(),
1198                    data: None,
1199                });
1200            }
1201        };
1202
1203        Ok(ReadResourceResult::new(vec![ResourceContents::text(content, uri.clone())]).into())
1204    }
1205
1206    //-----------------------------------------------------------------------//
1207    // Completions
1208    //-----------------------------------------------------------------------//
1209
1210    async fn complete(
1211        &self,
1212        request: CompleteRequestParams,
1213        _context: RequestContext<RoleServer>,
1214    ) -> Result<CompleteResult, McpError> {
1215        let argument_name = &request.argument.name;
1216        let partial = &request.argument.value;
1217
1218        let candidates: Vec<String> = match argument_name.as_str() {
1219            "game_name" | "game_key" | "game" => {
1220                let games = vec![
1221                    "pharaoh_dynasties", "pharaoh", "warhammer_3", "troy",
1222                    "three_kingdoms", "warhammer_2", "warhammer",
1223                    "thrones_of_britannia", "attila", "rome_2", "shogun_2",
1224                    "napoleon", "empire", "arena",
1225                ];
1226                games.into_iter()
1227                    .filter(|g| g.starts_with(partial))
1228                    .map(String::from)
1229                    .collect()
1230            },
1231            "pack_file_type" => {
1232                let types = vec!["\"Boot\"", "\"Release\"", "\"Patch\"", "\"Mod\"", "\"Movie\""];
1233                types.into_iter()
1234                    .filter(|t| t.starts_with(partial))
1235                    .map(String::from)
1236                    .collect()
1237            },
1238            "format" => {
1239                // Could be CompressionFormat or SupportedFormats depending on tool
1240                let formats = vec![
1241                    "\"None\"", "\"Lzma1\"", "\"Lz4\"", "\"Zstd\"",
1242                    "\"CaVp8\"", "\"Ivf\"",
1243                ];
1244                formats.into_iter()
1245                    .filter(|f| f.starts_with(partial))
1246                    .map(String::from)
1247                    .collect()
1248            },
1249            "source" => {
1250                let sources = vec![
1251                    "\"PackFile\"", "\"GameFiles\"", "\"ParentFiles\"",
1252                    "\"AssKitFiles\"", "\"ExternalFile\"",
1253                ];
1254                sources.into_iter()
1255                    .filter(|s| s.starts_with(partial))
1256                    .map(String::from)
1257                    .collect()
1258            },
1259            _ => vec![],
1260        };
1261
1262        let total = candidates.len() as u32;
1263        let values: Vec<String> = candidates.into_iter().take(100).collect();
1264        let has_more = total > 100;
1265
1266        Ok(CompleteResult::new(CompletionInfo::with_pagination(
1267            values,
1268            Some(total),
1269            has_more,
1270        ).map_err(|e| McpError {
1271            code: ErrorCode::INTERNAL_ERROR,
1272            message: format!("Failed to build completion info: {e}").into(),
1273            data: None,
1274        })?))
1275    }
1276
1277}
1278
1279#[tool_router]
1280impl McpServer {
1281
1282    pub fn new(session: Arc<Session>) -> Self {
1283        Self {
1284            session,
1285            tool_router: McpServer::tool_router(),
1286            prompt_router: McpServer::prompt_router(),
1287        }
1288    }
1289
1290    //-----------------------------------------------------------------------//
1291    // Existing tools
1292    //-----------------------------------------------------------------------//
1293
1294    #[tool(name = "call_command", description = "Call any IPC command directly. Use this for commands not yet wrapped as named tools.")]
1295    pub async fn call_command(&self, params: Parameters<CallCommandArgs>) -> Result<CallToolResult, McpError> {
1296        let command: Command = parse_json!(&params.0.command);
1297        send_and_respond!(self, "call_command", command)
1298    }
1299
1300    //-----------------------------------------------------------------------//
1301    // Pack Lifecycle
1302    //-----------------------------------------------------------------------//
1303
1304    #[tool(description = "Create a new empty PackFile.")]
1305    pub async fn new_pack(&self) -> Result<CallToolResult, McpError> {
1306        send_and_respond!(self, "new_pack", Command::NewPack)
1307    }
1308
1309    #[tool(description = "Open one or more PackFiles. Returns the info about the open pack.")]
1310    pub async fn open_packfiles(&self, params: Parameters<OpenPackfilesArgs>) -> Result<CallToolResult, McpError> {
1311        send_and_respond!(self, "open_packfiles", Command::OpenPackFiles(params.0.paths))
1312    }
1313
1314    #[tool(description = "Save the pack identified by `pack_key`.")]
1315    pub async fn save_packfile(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1316        send_and_respond!(self, "save_packfile", Command::SavePack(params.0.pack_key))
1317    }
1318
1319    #[tool(description = "Close the pack identified by `pack_key` without saving. Any unsaved changes will be lost.")]
1320    pub async fn close_pack(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1321        send_and_respond!(self, "close_pack", Command::ClosePack(params.0.pack_key))
1322    }
1323
1324    #[tool(description = "Save the pack identified by `pack_key` to a new path.")]
1325    pub async fn save_pack_as(&self, params: Parameters<PackKeyPathArg>) -> Result<CallToolResult, McpError> {
1326        send_and_respond!(self, "save_pack_as", Command::SavePackAs(params.0.pack_key, params.0.path))
1327    }
1328
1329    #[tool(description = "Clean the pack identified by `pack_key` from corrupted files and save to a path. Use if normal save fails.")]
1330    pub async fn clean_and_save_pack_as(&self, params: Parameters<PackKeyPathArg>) -> Result<CallToolResult, McpError> {
1331        send_and_respond!(self, "clean_and_save_pack_as", Command::CleanAndSavePackAs(params.0.pack_key, params.0.path))
1332    }
1333
1334    #[tool(description = "Trigger a backup autosave for the pack identified by `pack_key`.")]
1335    pub async fn trigger_backup_autosave(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1336        send_and_respond!(self, "trigger_backup_autosave", Command::TriggerBackupAutosave(params.0.pack_key))
1337    }
1338
1339    #[tool(description = "Open all CA (vanilla) PackFiles for the selected game as one merged PackFile.")]
1340    pub async fn load_all_ca_pack_files(&self) -> Result<CallToolResult, McpError> {
1341        send_and_respond!(self, "load_all_ca_pack_files", Command::LoadAllCAPackFiles)
1342    }
1343
1344    //-----------------------------------------------------------------------//
1345    // Pack Metadata
1346    //-----------------------------------------------------------------------//
1347
1348    #[tool(description = "Set the type of the pack identified by `pack_key`. Valid PFHFileType values: \"Boot\", \"Release\", \"Patch\", \"Mod\", \"Movie\". Example: pack_file_type = \"\\\"Mod\\\"\"")]
1349    pub async fn set_pack_file_type(&self, params: Parameters<SetPackFileTypeArgs>) -> Result<CallToolResult, McpError> {
1350        let pfh_type = parse_json!(&params.0.pack_file_type);
1351        send_and_respond!(self, "set_pack_file_type", Command::SetPackFileType(params.0.pack_key, pfh_type))
1352    }
1353
1354    #[tool(description = "Change the compression format of the pack identified by `pack_key`. Valid formats: \"None\", \"Lzma1\" (legacy), \"Lz4\" (WH3 6.2+), \"Zstd\" (WH3 6.2+). Example: format = \"\\\"None\\\"\"")]
1355    pub async fn change_compression_format(&self, params: Parameters<ChangeCompressionFormatArgs>) -> Result<CallToolResult, McpError> {
1356        let format = parse_json!(&params.0.format);
1357        send_and_respond!(self, "change_compression_format", Command::ChangeCompressionFormat(params.0.pack_key, format))
1358    }
1359
1360    #[tool(description = "Change whether the pack index includes timestamps for the pack identified by `pack_key`.")]
1361    pub async fn change_index_includes_timestamp(&self, params: Parameters<PackKeyBoolArg>) -> Result<CallToolResult, McpError> {
1362        send_and_respond!(self, "change_index_includes_timestamp", Command::ChangeIndexIncludesTimestamp(params.0.pack_key, params.0.value))
1363    }
1364
1365    #[tool(description = "Get the file path of the pack identified by `pack_key`.")]
1366    pub async fn get_pack_file_path(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1367        send_and_respond!(self, "get_pack_file_path", Command::GetPackFilePath(params.0.pack_key))
1368    }
1369
1370    #[tool(description = "Get the file name of the pack identified by `pack_key`.")]
1371    pub async fn get_pack_file_name(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1372        send_and_respond!(self, "get_pack_file_name", Command::GetPackFileName(params.0.pack_key))
1373    }
1374
1375    #[tool(description = "Get the settings of the pack identified by `pack_key`.")]
1376    pub async fn get_pack_settings(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1377        send_and_respond!(self, "get_pack_settings", Command::GetPackSettings(params.0.pack_key))
1378    }
1379
1380    #[tool(description = "Set the settings of the pack identified by `pack_key`. The `settings` is a PackSettings JSON object containing pack-level configuration.")]
1381    pub async fn set_pack_settings(&self, params: Parameters<SetPackSettingsArgs>) -> Result<CallToolResult, McpError> {
1382        let settings = parse_json!(&params.0.settings);
1383        send_and_respond!(self, "set_pack_settings", Command::SetPackSettings(params.0.pack_key, settings))
1384    }
1385
1386    #[tool(description = "Get the list of PackFiles marked as dependencies of the pack identified by `pack_key`.")]
1387    pub async fn get_dependency_pack_files_list(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1388        send_and_respond!(self, "get_dependency_pack_files_list", Command::GetDependencyPackFilesList(params.0.pack_key))
1389    }
1390
1391    #[tool(description = "Set the list of PackFiles marked as dependencies for the pack identified by `pack_key`. The `list` is a JSON array of [enabled, pack_name] pairs, e.g. [[true, \"other_mod.pack\"], [false, \"disabled_mod.pack\"]].")]
1392    pub async fn set_dependency_pack_files_list(&self, params: Parameters<SetDependencyPackFilesListArgs>) -> Result<CallToolResult, McpError> {
1393        let list = parse_json!(&params.0.list);
1394        send_and_respond!(self, "set_dependency_pack_files_list", Command::SetDependencyPackFilesList(params.0.pack_key, list))
1395    }
1396
1397    //-----------------------------------------------------------------------//
1398    // File Operations
1399    //-----------------------------------------------------------------------//
1400
1401    #[tool(description = "Decode a file from the pack identified by `pack_key`. The `path` is the internal file path (e.g. \"db/land_units_tables/my_mod\"). The `source` is the data source: \"PackFile\" (user mod), \"GameFiles\" (vanilla), \"ParentFiles\" (dependency mods), \"AssKitFiles\", or \"ExternalFile\". Returns the decoded file content as JSON (RFileDecoded).")]
1402    pub async fn decode_packed_file(&self, params: Parameters<DecodePackedFileArgs>) -> Result<CallToolResult, McpError> {
1403        send_and_respond!(self, "decode_packed_file", Command::DecodePackedFile(params.0.pack_key, params.0.path, params.0.source))
1404    }
1405
1406    #[tool(description = "Create a new file inside the pack identified by `pack_key`. The `path` is the destination path (e.g. \"db/land_units_tables/my_mod\"). NewFile types: {\"DB\": [\"file_name\", \"table_name\", version]}, {\"Loc\": \"name\"}, {\"Text\": [\"name\", \"Plain\"]}, {\"AnimPack\": \"name\"}, {\"VMD\": \"name\"}, {\"WSModel\": \"name\"}, {\"PortraitSettings\": [\"name\", version, []]}.")]
1407    pub async fn new_packed_file(&self, params: Parameters<NewPackedFileArgs>) -> Result<CallToolResult, McpError> {
1408        let new_file = parse_json!(&params.0.new_file);
1409        send_and_respond!(self, "new_packed_file", Command::NewPackedFile(params.0.pack_key, params.0.path, new_file))
1410    }
1411
1412    #[tool(description = "Add files from disk to the pack identified by `pack_key`. The `source_paths` are filesystem paths. The `destination_paths` is a JSON array of ContainerPath: [{\"File\": \"db/table/file\"}, {\"Folder\": \"ui/images\"}]. Optionally set `ignore_paths` to skip certain files.")]
1413    pub async fn add_packed_files(&self, params: Parameters<AddPackedFilesArgs>) -> Result<CallToolResult, McpError> {
1414        let dest: Vec<ContainerPath> = parse_json!(&params.0.destination_paths);
1415        send_and_respond!(self, "add_packed_files", Command::AddPackedFiles(params.0.pack_key, params.0.source_paths, dest, params.0.ignore_paths))
1416    }
1417
1418    #[tool(description = "Add files from another PackFile to the pack identified by `pack_key`. The `source_pack_path` is the pack path. The `container_paths` is a JSON array of ContainerPath: [{\"File\": \"path\"}].")]
1419    pub async fn add_packed_files_from_pack_file(&self, params: Parameters<AddPackedFilesFromPackFileArgs>) -> Result<CallToolResult, McpError> {
1420        let paths: Vec<ContainerPath> = parse_json!(&params.0.container_paths);
1421        send_and_respond!(self, "add_packed_files_from_pack_file", Command::AddPackedFilesFromPackFile(params.0.pack_key, params.0.source_pack_path, paths))
1422    }
1423
1424    #[tool(description = "Copy files from the pack identified by `source_pack_key` into an AnimPack owned by `pack_key` (the two may differ). The `container_paths` is a JSON array of ContainerPath, e.g. [{\"File\": \"animations/anim.anim\"}]. The `animpack_path` is the AnimPack's internal path.")]
1425    pub async fn add_packed_files_from_pack_file_to_animpack(&self, params: Parameters<AddPackedFilesFromPackFileToAnimpackArgs>) -> Result<CallToolResult, McpError> {
1426        let paths: Vec<ContainerPath> = parse_json!(&params.0.container_paths);
1427        send_and_respond!(self, "add_packed_files_from_pack_file_to_animpack", Command::AddPackedFilesFromPackFileToAnimpack(params.0.source_pack_key, params.0.pack_key, params.0.animpack_path, paths))
1428    }
1429
1430    #[tool(description = "Copy files from an AnimPack owned by `anim_pack_key` into the destination pack `pack_key` (the two may differ). The `source` is the DataSource (\"PackFile\", \"GameFiles\", etc.); `anim_pack_key` is only used when it is \"PackFile\". The `animpack_path` is the AnimPack's internal path. The `container_paths` is a JSON array of ContainerPath, e.g. [{\"File\": \"animations/anim.anim\"}].")]
1431    pub async fn add_packed_files_from_animpack(&self, params: Parameters<AddPackedFilesFromAnimpackArgs>) -> Result<CallToolResult, McpError> {
1432        let paths: Vec<ContainerPath> = parse_json!(&params.0.container_paths);
1433        send_and_respond!(self, "add_packed_files_from_animpack", Command::AddPackedFilesFromAnimpack(params.0.anim_pack_key, params.0.pack_key, params.0.source, params.0.animpack_path, paths))
1434    }
1435
1436    #[tool(description = "Delete files from the pack identified by `pack_key`. The `paths` is a JSON array of ContainerPath: [{\"File\": \"path/to/file\"}, {\"Folder\": \"path/to/folder\"}].")]
1437    pub async fn delete_packed_files(&self, params: Parameters<ContainerPathsArg>) -> Result<CallToolResult, McpError> {
1438        let paths: Vec<ContainerPath> = parse_json!(&params.0.paths);
1439        send_and_respond!(self, "delete_packed_files", Command::DeletePackedFiles(params.0.pack_key, paths))
1440    }
1441
1442    #[tool(description = "Delete files from an AnimPack in the pack identified by `pack_key`. The `animpack_path` is the AnimPack's internal path. The `container_paths` is a JSON array of ContainerPath, e.g. [{\"File\": \"animations/anim.anim\"}].")]
1443    pub async fn delete_from_animpack(&self, params: Parameters<DeleteFromAnimpackArgs>) -> Result<CallToolResult, McpError> {
1444        let paths: Vec<ContainerPath> = parse_json!(&params.0.container_paths);
1445        send_and_respond!(self, "delete_from_animpack", Command::DeleteFromAnimpack(params.0.pack_key, params.0.animpack_path, paths))
1446    }
1447
1448    #[tool(description = "Extract files from the pack identified by `pack_key` to disk. The `source_paths` is a JSON object mapping DataSource to ContainerPath arrays, e.g. {\"PackFile\": [{\"File\": \"db/table/file\"}]}. Set `export_as_tsv: true` to export tables as TSV files.")]
1449    pub async fn extract_packed_files(&self, params: Parameters<ExtractPackedFilesArgs>) -> Result<CallToolResult, McpError> {
1450        let source: BTreeMap<DataSource, Vec<ContainerPath>> = parse_json!(&params.0.source_paths);
1451        send_and_respond!(self, "extract_packed_files", Command::ExtractPackedFiles(params.0.pack_key, source, params.0.destination_path, params.0.export_as_tsv))
1452    }
1453
1454    #[tool(description = "Rename files in the pack identified by `pack_key`. The `renames` is a JSON array of [old, new] ContainerPath pairs, e.g. [[{\"File\": \"old/path\"}, {\"File\": \"new/path\"}]].")]
1455    pub async fn rename_packed_files(&self, params: Parameters<RenamePackedFilesArgs>) -> Result<CallToolResult, McpError> {
1456        let renames: Vec<(ContainerPath, ContainerPath)> = parse_json!(&params.0.renames);
1457        send_and_respond!(self, "rename_packed_files", Command::RenamePackedFiles(params.0.pack_key, renames))
1458    }
1459
1460    #[tool(description = "Copy files to the internal clipboard. The `paths_by_pack` is a JSON object mapping pack key to ContainerPath arrays, e.g. {\"my_pack.pack\": [{\"File\": \"db/table/file\"}]}. Use `paste_packed_files` to paste afterwards.")]
1461    pub async fn copy_packed_files(&self, params: Parameters<CopyOrCutPackedFilesArgs>) -> Result<CallToolResult, McpError> {
1462        let paths_by_pack: BTreeMap<String, Vec<ContainerPath>> = parse_json!(&params.0.paths_by_pack);
1463        send_and_respond!(self, "copy_packed_files", Command::CopyPackedFiles(paths_by_pack))
1464    }
1465
1466    #[tool(description = "Cut files to the internal clipboard. Same as copy, but files will be removed from the source pack on paste. The `paths_by_pack` is a JSON object mapping pack key to ContainerPath arrays. Use `paste_packed_files` to paste afterwards.")]
1467    pub async fn cut_packed_files(&self, params: Parameters<CopyOrCutPackedFilesArgs>) -> Result<CallToolResult, McpError> {
1468        let paths_by_pack: BTreeMap<String, Vec<ContainerPath>> = parse_json!(&params.0.paths_by_pack);
1469        send_and_respond!(self, "cut_packed_files", Command::CutPackedFiles(paths_by_pack))
1470    }
1471
1472    #[tool(description = "Paste files from the internal clipboard into the pack identified by `pack_key`. The `destination_path` is the folder path to paste into (empty string for root). Returns the added paths, any cut-deleted paths, and the source pack key.")]
1473    pub async fn paste_packed_files(&self, params: Parameters<PastePackedFilesArgs>) -> Result<CallToolResult, McpError> {
1474        send_and_respond!(self, "paste_packed_files", Command::PastePackedFiles(params.0.pack_key, params.0.destination_path))
1475    }
1476
1477    #[tool(description = "Duplicate files in-place within the same pack. Files are cloned with a numeric suffix to avoid name collisions. The `paths` is a JSON array of ContainerPath, e.g. [{\"File\": \"db/table/file\"}].")]
1478    pub async fn duplicate_packed_files(&self, params: Parameters<DuplicatePackedFilesArgs>) -> Result<CallToolResult, McpError> {
1479        let paths: Vec<ContainerPath> = parse_json!(&params.0.paths);
1480        send_and_respond!(self, "duplicate_packed_files", Command::DuplicatePackedFiles(params.0.pack_key, paths))
1481    }
1482
1483    #[tool(description = "Save an edited decoded file back to the pack identified by `pack_key`. The `path` is the internal path (e.g. \"db/land_units_tables/my_mod\"). The `data` is the modified RFileDecoded JSON (same structure returned by `decode_packed_file`).")]
1484    pub async fn save_packed_file_from_view(&self, params: Parameters<SavePackedFileFromViewArgs>) -> Result<CallToolResult, McpError> {
1485        let data: RFileDecoded = parse_json!(&params.0.data);
1486        send_and_respond!(self, "save_packed_file_from_view", Command::SavePackedFileFromView(params.0.pack_key, params.0.path, data))
1487    }
1488
1489    #[tool(description = "Save a file from an external program back to the pack identified by `pack_key`.")]
1490    pub async fn save_packed_file_from_external_view(&self, params: Parameters<SavePackedFileFromExternalViewArgs>) -> Result<CallToolResult, McpError> {
1491        send_and_respond!(self, "save_packed_file_from_external_view", Command::SavePackedFileFromExternalView(params.0.pack_key, params.0.internal_path, params.0.external_path))
1492    }
1493
1494    #[tool(description = "Save files to the pack identified by `pack_key` and optionally optimize afterward. The `files` is a JSON array of RFile objects (as returned by decode/get operations). Set `optimize` to true to remove unchanged data after saving.")]
1495    pub async fn save_packed_files_to_pack_file_and_clean(&self, params: Parameters<SavePackedFilesToPackFileAndCleanArgs>) -> Result<CallToolResult, McpError> {
1496        let files: Vec<RFile> = parse_json!(&params.0.files);
1497        send_and_respond!(self, "save_packed_files_to_pack_file_and_clean", Command::SavePackedFilesToPackFileAndClean(params.0.pack_key, files, params.0.optimize))
1498    }
1499
1500    #[tool(description = "Get the raw binary data of a file in the pack identified by `pack_key`.")]
1501    pub async fn get_packed_file_raw_data(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1502        send_and_respond!(self, "get_packed_file_raw_data", Command::GetPackedFileRawData(params.0.pack_key, params.0.value))
1503    }
1504
1505    #[tool(description = "Open a file in the system's default program from the pack identified by `pack_key`. The `source` is the DataSource (\"PackFile\", \"GameFiles\", etc.). The `container_path` is a ContainerPath JSON, e.g. {\"File\": \"db/table/file\"}.")]
1506    pub async fn open_packed_file_in_external_program(&self, params: Parameters<OpenPackedFileInExternalProgramArgs>) -> Result<CallToolResult, McpError> {
1507        let cp: ContainerPath = parse_json!(&params.0.container_path);
1508        send_and_respond!(self, "open_packed_file_in_external_program", Command::OpenPackedFileInExternalProgram(params.0.pack_key, params.0.source, cp))
1509    }
1510
1511    #[tool(description = "Open the folder containing the pack identified by `pack_key` in the file manager.")]
1512    pub async fn open_containing_folder(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1513        send_and_respond!(self, "open_containing_folder", Command::OpenContainingFolder(params.0.pack_key))
1514    }
1515
1516    #[tool(description = "Clean the decode cache for the provided paths in the pack identified by `pack_key`. The `paths` is a JSON array of ContainerPath, e.g. [{\"File\": \"db/land_units_tables/my_mod\"}, {\"Folder\": \"db\"}].")]
1517    pub async fn clean_cache(&self, params: Parameters<ContainerPathsArg>) -> Result<CallToolResult, McpError> {
1518        let paths: Vec<ContainerPath> = parse_json!(&params.0.paths);
1519        send_and_respond!(self, "clean_cache", Command::CleanCache(params.0.pack_key, paths))
1520    }
1521
1522    #[tool(description = "Check if a folder exists in the pack identified by `pack_key`.")]
1523    pub async fn folder_exists(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1524        send_and_respond!(self, "folder_exists", Command::FolderExists(params.0.pack_key, params.0.value))
1525    }
1526
1527    #[tool(description = "Check if a file exists in the pack identified by `pack_key`.")]
1528    pub async fn packed_file_exists(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1529        send_and_respond!(self, "packed_file_exists", Command::PackedFileExists(params.0.pack_key, params.0.value))
1530    }
1531
1532    #[tool(description = "Get the info of one or more files in the pack identified by `pack_key`.")]
1533    pub async fn get_packed_files_info(&self, params: Parameters<PackKeyStringsArg>) -> Result<CallToolResult, McpError> {
1534        send_and_respond!(self, "get_packed_files_info", Command::GetPackedFilesInfo(params.0.pack_key, params.0.values))
1535    }
1536
1537    #[tool(description = "Get the info of a single file in the pack identified by `pack_key`.")]
1538    pub async fn get_rfile_info(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1539        send_and_respond!(self, "get_rfile_info", Command::GetRFileInfo(params.0.pack_key, params.0.value))
1540    }
1541
1542    //-----------------------------------------------------------------------//
1543    // Game Selection
1544    //-----------------------------------------------------------------------//
1545
1546    #[tool(description = "Get the currently selected game key.")]
1547    pub async fn get_game_selected(&self) -> Result<CallToolResult, McpError> {
1548        send_and_respond!(self, "get_game_selected", Command::GetGameSelected)
1549    }
1550
1551    #[tool(description = "Set the current game. Valid game keys: pharaoh_dynasties, pharaoh, warhammer_3, troy, three_kingdoms, warhammer_2, warhammer, thrones_of_britannia, attila, rome_2, shogun_2, napoleon, empire, arena. Set rebuild_dependencies to true on first call to load schemas and vanilla data.")]
1552    pub async fn set_game_selected(&self, params: Parameters<SetGameSelectedArgs>) -> Result<CallToolResult, McpError> {
1553        send_and_respond!(self, "set_game_selected", Command::SetGameSelected(params.0.game_name, params.0.rebuild_dependencies))
1554    }
1555
1556    //-----------------------------------------------------------------------//
1557    // Dependencies
1558    //-----------------------------------------------------------------------//
1559
1560    #[tool(description = "Generate the dependencies cache for the selected game. This can take a long time (more than 30 seconds), depending on your CPU and disk read speed. If the client is not careful, it can take enough time that the client may trigger a timeout.")]
1561    pub async fn generate_dependencies_cache(&self) -> Result<CallToolResult, McpError> {
1562        send_and_respond!(self, "generate_dependencies_cache", Command::GenerateDependenciesCache)
1563    }
1564
1565    #[tool(description = "Rebuild dependencies. Pass true for full rebuild, false for mod-specific only.")]
1566    pub async fn rebuild_dependencies(&self, params: Parameters<BoolArg>) -> Result<CallToolResult, McpError> {
1567        send_and_respond!(self, "rebuild_dependencies", Command::RebuildDependencies(params.0.value))
1568    }
1569
1570    #[tool(description = "Check if there is a dependency database loaded. Pass true to ensure AssKit data is included.")]
1571    pub async fn is_there_a_dependency_database(&self, params: Parameters<BoolArg>) -> Result<CallToolResult, McpError> {
1572        send_and_respond!(self, "is_there_a_dependency_database", Command::IsThereADependencyDatabase(params.0.value))
1573    }
1574
1575    #[tool(description = "Get the table names of all DB files in dependency PackFiles.")]
1576    pub async fn get_table_list_from_dependency_pack_file(&self) -> Result<CallToolResult, McpError> {
1577        send_and_respond!(self, "get_table_list_from_dependency_pack_file", Command::GetTableListFromDependencyPackFile)
1578    }
1579
1580    #[tool(description = "Get custom table names (start_pos_, twad_ prefixes) from the schema.")]
1581    pub async fn get_custom_table_list(&self) -> Result<CallToolResult, McpError> {
1582        send_and_respond!(self, "get_custom_table_list", Command::GetCustomTableList)
1583    }
1584
1585    #[tool(description = "Get the version of a table from the dependency database.")]
1586    pub async fn get_table_version_from_dependency_pack_file(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1587        send_and_respond!(self, "get_table_version_from_dependency_pack_file", Command::GetTableVersionFromDependencyPackFile(params.0.value))
1588    }
1589
1590    #[tool(description = "Get the definition of a table from the dependency database. NOTE: the returned `fields` list is the raw on-disk field layout, not what row data looks like (e.g. colour columns are split into separate r/g/b fields here). Pass the definition to `fields_processed` to get the field list/count that rows must actually match.")]
1591    pub async fn get_table_definition_from_dependency_pack_file(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1592        send_and_respond!(self, "get_table_definition_from_dependency_pack_file", Command::GetTableDefinitionFromDependencyPackFile(params.0.value))
1593    }
1594
1595    #[tool(description = "Get table data from dependencies by table name. NOTE: each returned file's decoded `data` rows are shaped per the PROCESSED fields (colour groups merged, bitwise/enum expanded), but the `definition.fields` bundled in the same file is the RAW on-disk layout and will have a different length/order — do not zip row cells against `definition.fields`. Call `fields_processed` on that definition to get the field list that actually lines up with `data`.")]
1596    pub async fn get_tables_from_dependencies(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1597        send_and_respond!(self, "get_tables_from_dependencies", Command::GetTablesFromDependencies(params.0.value))
1598    }
1599
1600    #[tool(description = "Import files from dependencies into the pack identified by `pack_key`. The `paths` is a JSON object mapping DataSource to ContainerPath arrays, e.g. {\"GameFiles\": [{\"File\": \"db/table/file\"}]}.")]
1601    pub async fn import_dependencies_to_open_pack_file(&self, params: Parameters<ImportDependenciesArgs>) -> Result<CallToolResult, McpError> {
1602        let paths: BTreeMap<DataSource, Vec<ContainerPath>> = parse_json!(&params.0.paths);
1603        send_and_respond!(self, "import_dependencies_to_open_pack_file", Command::ImportDependenciesToOpenPackFile(params.0.pack_key, paths))
1604    }
1605
1606    #[tool(description = "Get files from all known sources (PackFile, GameFiles, ParentFiles). The `paths` is a JSON array of ContainerPath, e.g. [{\"File\": \"db/land_units_tables/some_file\"}]. Set `lowercase` to true to normalize path casing.")]
1607    pub async fn get_rfiles_from_all_sources(&self, params: Parameters<GetRFilesFromAllSourcesArgs>) -> Result<CallToolResult, McpError> {
1608        let paths: Vec<ContainerPath> = parse_json!(&params.0.paths);
1609        send_and_respond!(self, "get_rfiles_from_all_sources", Command::GetRFilesFromAllSources(paths, params.0.lowercase))
1610    }
1611
1612    #[tool(description = "Get all file names under a path prefix across all data sources (PackFile, GameFiles, ParentFiles). The `path` is a ContainerPath JSON, e.g. {\"Folder\": \"db/land_units_tables\"} to list all files under that folder.")]
1613    pub async fn get_packed_files_names_starting_with_path_from_all_sources(&self, params: Parameters<ContainerPathArg>) -> Result<CallToolResult, McpError> {
1614        let path: ContainerPath = parse_json!(&params.0.path);
1615        send_and_respond!(self, "get_packed_files_names_starting_with_path_from_all_sources", Command::GetPackedFilesNamesStartingWitPathFromAllSources(path))
1616    }
1617
1618    #[tool(description = "Get local art set IDs from campaign_character_arts_tables in the pack identified by `pack_key`.")]
1619    pub async fn local_art_set_ids(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1620        send_and_respond!(self, "local_art_set_ids", Command::LocalArtSetIds(params.0.pack_key))
1621    }
1622
1623    #[tool(description = "Get art set IDs from dependencies' campaign_character_arts_tables.")]
1624    pub async fn dependencies_art_set_ids(&self) -> Result<CallToolResult, McpError> {
1625        send_and_respond!(self, "dependencies_art_set_ids", Command::DependenciesArtSetIds)
1626    }
1627
1628    //-----------------------------------------------------------------------//
1629    // Search
1630    //-----------------------------------------------------------------------//
1631
1632    #[tool(description = "Run a global search across the pack identified by `pack_key`. The `search` is a GlobalSearch JSON with fields: pattern (string), replace_text (string), case_sensitive (bool), use_regex (bool), search_on ({db: bool, loc: bool, text: bool, ...}), sources ([{\"Pack\": \"key\"}]), game_key (string). See the `rpfm://examples/global_search` resource for a full example.")]
1633    pub async fn global_search(&self, params: Parameters<GlobalSearchArgs>) -> Result<CallToolResult, McpError> {
1634        let search = parse_json!(&params.0.search);
1635        send_and_respond!(self, "global_search", Command::GlobalSearch(params.0.pack_key, search))
1636    }
1637
1638    #[tool(description = "Replace specific matches in a global search for the pack identified by `pack_key`. The `search` is the same GlobalSearch JSON used in `global_search` (see `rpfm://examples/global_search` resource). The `matches` is a JSON array of MatchHolder objects from the search results — include only the matches you want to replace.")]
1639    pub async fn global_search_replace_matches(&self, params: Parameters<GlobalSearchReplaceMatchesArgs>) -> Result<CallToolResult, McpError> {
1640        let search = parse_json!(&params.0.search);
1641        let matches = parse_json!(&params.0.matches);
1642        send_and_respond!(self, "global_search_replace_matches", Command::GlobalSearchReplaceMatches(params.0.pack_key, search, matches))
1643    }
1644
1645    #[tool(description = "Replace all matches in a global search for the pack identified by `pack_key`. The `search` is a GlobalSearch JSON with the `replace_text` field set to the replacement string. See `rpfm://examples/global_search` resource for the full structure.")]
1646    pub async fn global_search_replace_all(&self, params: Parameters<GlobalSearchArgs>) -> Result<CallToolResult, McpError> {
1647        let search = parse_json!(&params.0.search);
1648        send_and_respond!(self, "global_search_replace_all", Command::GlobalSearchReplaceAll(params.0.pack_key, search))
1649    }
1650
1651    #[tool(description = "Find all references to a value in the pack identified by `pack_key`. The `reference_map` is a JSON object mapping table names to column name arrays, e.g. {\"land_units_tables\": [\"key\", \"unit\"]}. The `value` is the string to search for across those columns.")]
1652    pub async fn search_references(&self, params: Parameters<SearchReferencesArgs>) -> Result<CallToolResult, McpError> {
1653        let map: HashMap<String, Vec<String>> = parse_json!(&params.0.reference_map);
1654        send_and_respond!(self, "search_references", Command::SearchReferences(params.0.pack_key, map, params.0.value))
1655    }
1656
1657    #[tool(description = "Get valid reference values for columns in a table definition for the pack identified by `pack_key`. The `definition` is a Definition JSON (as returned by `get_table_definition_from_dependency_pack_file`). Set `force` to true to regenerate cached reference data.")]
1658    pub async fn get_reference_data_from_definition(&self, params: Parameters<GetReferenceDataFromDefinitionArgs>) -> Result<CallToolResult, McpError> {
1659        let def = parse_json!(&params.0.definition);
1660        send_and_respond!(self, "get_reference_data_from_definition", Command::GetReferenceDataFromDefinition(params.0.pack_key, params.0.table_name, def, params.0.force))
1661    }
1662
1663    #[tool(description = "Go to the definition of a reference in the pack identified by `pack_key`. Provide table name, column name, and values to search.")]
1664    pub async fn go_to_definition(&self, params: Parameters<GoToDefinitionArgs>) -> Result<CallToolResult, McpError> {
1665        send_and_respond!(self, "go_to_definition", Command::GoToDefinition(params.0.pack_key, params.0.table_name, params.0.column_name, params.0.values))
1666    }
1667
1668    #[tool(description = "Go to a loc key's location in the pack identified by `pack_key`.")]
1669    pub async fn go_to_loc(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1670        send_and_respond!(self, "go_to_loc", Command::GoToLoc(params.0.pack_key, params.0.value))
1671    }
1672
1673    #[tool(description = "Get the source data of a loc key in the pack identified by `pack_key`.")]
1674    pub async fn get_source_data_from_loc_key(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1675        send_and_respond!(self, "get_source_data_from_loc_key", Command::GetSourceDataFromLocKey(params.0.pack_key, params.0.value))
1676    }
1677
1678    //-----------------------------------------------------------------------//
1679    // Schema
1680    //-----------------------------------------------------------------------//
1681
1682    #[tool(description = "Save the provided schema to disk. The `schema` is the full Schema JSON object (as returned by `get_schema`). Use this after modifying definitions or applying patches.")]
1683    pub async fn save_schema(&self, params: Parameters<SaveSchemaArgs>) -> Result<CallToolResult, McpError> {
1684        let schema = parse_json!(&params.0.schema);
1685        send_and_respond!(self, "save_schema", Command::SaveSchema(schema))
1686    }
1687
1688    #[tool(description = "Update the currently loaded schema with data from the game's Assembly Kit.")]
1689    pub async fn update_current_schema_from_asskit(&self) -> Result<CallToolResult, McpError> {
1690        send_and_respond!(self, "update_current_schema_from_asskit", Command::UpdateCurrentSchemaFromAssKit)
1691    }
1692
1693    #[tool(description = "Update schemas from the remote repository.")]
1694    pub async fn update_schemas(&self) -> Result<CallToolResult, McpError> {
1695        send_and_respond!(self, "update_schemas", Command::UpdateSchemas)
1696    }
1697
1698    #[tool(description = "Check if a schema is currently loaded.")]
1699    pub async fn is_schema_loaded(&self) -> Result<CallToolResult, McpError> {
1700        send_and_respond!(self, "is_schema_loaded", Command::IsSchemaLoaded)
1701    }
1702
1703    #[tool(description = "Get the current schema.")]
1704    pub async fn get_schema(&self) -> Result<CallToolResult, McpError> {
1705        send_and_respond!(self, "get_schema", Command::Schema)
1706    }
1707
1708    #[tool(description = "Get all definitions for a table name. NOTE: the returned `fields` list is the raw on-disk field layout, not what row data looks like (e.g. colour columns are split into separate r/g/b fields here). Pass the definition to `fields_processed` to get the field list/count that rows must actually match.")]
1709    pub async fn definitions_by_table_name(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1710        send_and_respond!(self, "definitions_by_table_name", Command::DefinitionsByTableName(params.0.value))
1711    }
1712
1713    #[tool(description = "Get a specific definition by table name and version. NOTE: the returned `fields` list is the raw on-disk field layout, not what row data looks like (e.g. colour columns are split into separate r/g/b fields here). Do not use `fields.len()` to size a row for saving — pass this definition to `fields_processed` first to get the field list/count and types that rows must actually match.")]
1714    pub async fn definition_by_table_name_and_version(&self, params: Parameters<StringI32Args>) -> Result<CallToolResult, McpError> {
1715        send_and_respond!(self, "definition_by_table_name_and_version", Command::DefinitionByTableNameAndVersion(params.0.name, params.0.version))
1716    }
1717
1718    #[tool(description = "Delete a definition by table name and version.")]
1719    pub async fn delete_definition(&self, params: Parameters<StringI32Args>) -> Result<CallToolResult, McpError> {
1720        send_and_respond!(self, "delete_definition", Command::DeleteDefinition(params.0.name, params.0.version))
1721    }
1722
1723    #[tool(description = "Get columns from other tables that reference the given table's definition. The `definition` is a Definition JSON (as returned by `get_table_definition_from_dependency_pack_file` or `definitions_by_table_name`).")]
1724    pub async fn referencing_columns_for_definition(&self, params: Parameters<ReferencingColumnsForDefinitionArgs>) -> Result<CallToolResult, McpError> {
1725        let def = parse_json!(&params.0.definition);
1726        send_and_respond!(self, "referencing_columns_for_definition", Command::ReferencingColumnsForDefinition(params.0.table_name, def))
1727    }
1728
1729    #[tool(description = "Get the processed fields from a definition, with bitwise expansion, enum conversions, and colour-group merging applied. Call this before building or validating row data: table rows must have exactly as many entries as `fields_processed` returns, NOT as many as the raw `fields` list on the Definition (e.g. `definition_by_table_name_and_version`/`definitions_by_table_name` return raw fields, where a colour split into r/g/b counts as 3 fields instead of the 1 merged field rows actually use). Saving a row built against the raw field count/types will fail. The `definition` is a Definition JSON (as returned by `get_table_definition_from_dependency_pack_file`).")]
1730    pub async fn fields_processed(&self, params: Parameters<DefinitionArg>) -> Result<CallToolResult, McpError> {
1731        let def = parse_json!(&params.0.definition);
1732        send_and_respond!(self, "fields_processed", Command::FieldsProcessed(def))
1733    }
1734
1735    #[tool(description = "Save local schema patches to customize column metadata without modifying the upstream schema. The `patches` is a JSON object mapping table names to DefinitionPatch objects, e.g. {\"land_units_tables\": {\"field_patches\": {...}}}.")]
1736    pub async fn save_local_schema_patch(&self, params: Parameters<SchemaPatchArgs>) -> Result<CallToolResult, McpError> {
1737        let patches = parse_json!(&params.0.patches);
1738        send_and_respond!(self, "save_local_schema_patch", Command::SaveLocalSchemaPatch(patches))
1739    }
1740
1741    #[tool(description = "Remove local schema patches for a table.")]
1742    pub async fn remove_local_schema_patches_for_table(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1743        send_and_respond!(self, "remove_local_schema_patches_for_table", Command::RemoveLocalSchemaPatchesForTable(params.0.value))
1744    }
1745
1746    #[tool(description = "Remove local schema patches for a specific field in a table.")]
1747    pub async fn remove_local_schema_patches_for_table_and_field(&self, params: Parameters<SettingsSetStringArgs>) -> Result<CallToolResult, McpError> {
1748        send_and_respond!(self, "remove_local_schema_patches_for_table_and_field", Command::RemoveLocalSchemaPatchesForTableAndField(params.0.key, params.0.value))
1749    }
1750
1751    #[tool(description = "Import a schema patch from an external source. The `patches` is a JSON object mapping table names to DefinitionPatch objects (same format as `save_local_schema_patch`).")]
1752    pub async fn import_schema_patch(&self, params: Parameters<SchemaPatchArgs>) -> Result<CallToolResult, McpError> {
1753        let patches = parse_json!(&params.0.patches);
1754        send_and_respond!(self, "import_schema_patch", Command::ImportSchemaPatch(patches))
1755    }
1756
1757    //-----------------------------------------------------------------------//
1758    // Table Operations
1759    //-----------------------------------------------------------------------//
1760
1761    #[tool(description = "Merge multiple compatible tables into one in the pack identified by `pack_key`. The `paths` is a JSON array of ContainerPath for the tables to merge, e.g. [{\"File\": \"db/land_units_tables/table1\"}, {\"File\": \"db/land_units_tables/table2\"}]. The `merged_path` is the destination path. Set `delete_source` to true to remove the original files. DB Tables can also be enabled for Delta Merging (if two or more tables edit the same row, it merges their changes into a single row).")]
1762    pub async fn merge_files(&self, params: Parameters<MergeFilesArgs>) -> Result<CallToolResult, McpError> {
1763        let paths: Vec<ContainerPath> = parse_json!(&params.0.paths);
1764        let mut options = MergeOptions::default();
1765        options.set_delta_merge(params.0.delta_merge);
1766        send_and_respond!(self, "merge_files", Command::MergeFiles(params.0.pack_key, paths, params.0.merged_path, params.0.delete_source, options))
1767    }
1768
1769    #[tool(description = "Update a table to the latest schema version in the pack identified by `pack_key`. The `value` is a ContainerPath JSON, e.g. {\"File\": \"db/land_units_tables/my_mod\"}.")]
1770    pub async fn update_table(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1771        let path: ContainerPath = parse_json!(&params.0.value);
1772        send_and_respond!(self, "update_table", Command::UpdateTable(params.0.pack_key, path))
1773    }
1774
1775    #[tool(description = "Trigger a cascade edition on all referenced data in the pack identified by `pack_key`. When a key value changes, this propagates the change to all referencing tables. The `definition` is a Definition JSON for the source table. The `changes` is a JSON array of [field, old_value, new_value] tuples, e.g. [[field_json, \"old_key\", \"new_key\"]].")]
1776    pub async fn cascade_edition(&self, params: Parameters<CascadeEditionArgs>) -> Result<CallToolResult, McpError> {
1777        let def = parse_json!(&params.0.definition);
1778        let changes = parse_json!(&params.0.changes);
1779        send_and_respond!(self, "cascade_edition", Command::CascadeEdition(params.0.pack_key, params.0.table_name, def, changes))
1780    }
1781
1782    #[tool(description = "Get table paths by table name from the pack identified by `pack_key`.")]
1783    pub async fn get_tables_by_table_name(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1784        send_and_respond!(self, "get_tables_by_table_name", Command::GetTablesByTableName(params.0.pack_key, params.0.value))
1785    }
1786
1787    #[tool(description = "Add keys to the key_deletes table in the pack identified by `pack_key`.")]
1788    pub async fn add_keys_to_key_deletes(&self, params: Parameters<AddKeysToKeyDeletesArgs>) -> Result<CallToolResult, McpError> {
1789        send_and_respond!(self, "add_keys_to_key_deletes", Command::AddKeysToKeyDeletes(params.0.pack_key, params.0.table_file_name, params.0.key_table_name, params.0.keys))
1790    }
1791
1792    #[tool(description = "Export a table from the pack identified by `pack_key` to a TSV file.")]
1793    pub async fn export_tsv(&self, params: Parameters<TsvExportArgs>) -> Result<CallToolResult, McpError> {
1794        send_and_respond!(self, "export_tsv", Command::ExportTSV(params.0.pack_key, params.0.table_path, params.0.tsv_path, DataSource::PackFile))
1795    }
1796
1797    #[tool(description = "Import a TSV file to a table in the pack identified by `pack_key`.")]
1798    pub async fn import_tsv(&self, params: Parameters<TsvImportArgs>) -> Result<CallToolResult, McpError> {
1799        send_and_respond!(self, "import_tsv", Command::ImportTSV(params.0.pack_key, params.0.table_path, params.0.tsv_path))
1800    }
1801
1802    //-----------------------------------------------------------------------//
1803    // Diagnostics
1804    //-----------------------------------------------------------------------//
1805
1806    #[tool(description = "Run a full diagnostics check over all open packs.")]
1807    pub async fn diagnostics_check(&self, params: Parameters<DiagnosticsCheckArgs>) -> Result<CallToolResult, McpError> {
1808        send_and_respond!(self, "diagnostics_check", Command::DiagnosticsCheck(params.0.ignored, params.0.check_ak_only_refs))
1809    }
1810
1811    #[tool(description = "Update diagnostics incrementally for changed files across all open packs. The `diagnostics` is the Diagnostics JSON from a previous `diagnostics_check` call. The `paths` is a JSON array of ContainerPath for the files that changed, e.g. [{\"File\": \"db/land_units_tables/my_mod\"}].")]
1812    pub async fn diagnostics_update(&self, params: Parameters<DiagnosticsUpdateArgs>) -> Result<CallToolResult, McpError> {
1813        let diag = parse_json!(&params.0.diagnostics);
1814        let paths: Vec<ContainerPath> = parse_json!(&params.0.paths);
1815        send_and_respond!(self, "diagnostics_update", Command::DiagnosticsUpdate(diag, paths, params.0.check_ak_only_refs))
1816    }
1817
1818    #[tool(description = "Add a line to the ignored diagnostics list for the pack identified by `pack_key`.")]
1819    pub async fn add_line_to_pack_ignored_diagnostics(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1820        send_and_respond!(self, "add_line_to_pack_ignored_diagnostics", Command::AddLineToPackIgnoredDiagnostics(params.0.pack_key, params.0.value))
1821    }
1822
1823    #[tool(description = "Export missing table definitions for the pack identified by `pack_key` to a file (for debugging).")]
1824    pub async fn get_missing_definitions(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
1825        send_and_respond!(self, "get_missing_definitions", Command::GetMissingDefinitions(params.0.pack_key))
1826    }
1827
1828    //-----------------------------------------------------------------------//
1829    // Notes
1830    //-----------------------------------------------------------------------//
1831
1832    #[tool(description = "Get all notes under a path in the pack identified by `pack_key`.")]
1833    pub async fn notes_for_path(&self, params: Parameters<PackKeyStringArg>) -> Result<CallToolResult, McpError> {
1834        send_and_respond!(self, "notes_for_path", Command::NotesForPath(params.0.pack_key, params.0.value))
1835    }
1836
1837    #[tool(description = "Add a note to the pack identified by `pack_key`. The `note` is a Note JSON object with fields: path (string — the file or folder path to attach the note to), id (u64), text (string — the note content).")]
1838    pub async fn add_note(&self, params: Parameters<AddNoteArgs>) -> Result<CallToolResult, McpError> {
1839        let note = parse_json!(&params.0.note);
1840        send_and_respond!(self, "add_note", Command::AddNote(params.0.pack_key, note))
1841    }
1842
1843    #[tool(description = "Delete a note by path and ID in the pack identified by `pack_key`.")]
1844    pub async fn delete_note(&self, params: Parameters<DeleteNoteArgs>) -> Result<CallToolResult, McpError> {
1845        send_and_respond!(self, "delete_note", Command::DeleteNote(params.0.pack_key, params.0.path, params.0.id))
1846    }
1847
1848    //-----------------------------------------------------------------------//
1849    // Optimization
1850    //-----------------------------------------------------------------------//
1851
1852    #[tool(description = "Optimize the pack identified by `pack_key` by removing unchanged/duplicate data. The `options` is an OptimizerOptions JSON with boolean fields: pack_remove_itm_files, table_remove_duplicated_entries, table_remove_itm_entries, table_remove_itnr_entries, table_remove_empty_file, db_optimize_datacored_tables, etc. See the `rpfm://examples/optimizer_options` resource for all fields.")]
1853    pub async fn optimize_pack_file(&self, params: Parameters<OptimizePackFileArgs>) -> Result<CallToolResult, McpError> {
1854        let options = parse_json!(&params.0.options);
1855        send_and_respond!(self, "optimize_pack_file", Command::OptimizePackFile(params.0.pack_key, options))
1856    }
1857
1858    #[tool(description = "Get the default optimizer options.")]
1859    pub async fn get_optimizer_options(&self) -> Result<CallToolResult, McpError> {
1860        send_and_respond!(self, "get_optimizer_options", Command::OptimizerOptions)
1861    }
1862
1863    //-----------------------------------------------------------------------//
1864    // Updates
1865    //-----------------------------------------------------------------------//
1866
1867    #[tool(description = "Check if there is an RPFM update available.")]
1868    pub async fn check_updates(&self) -> Result<CallToolResult, McpError> {
1869        send_and_respond!(self, "check_updates", Command::CheckUpdates)
1870    }
1871
1872    #[tool(description = "Check if there is a schema update available.")]
1873    pub async fn check_schema_updates(&self) -> Result<CallToolResult, McpError> {
1874        send_and_respond!(self, "check_schema_updates", Command::CheckSchemaUpdates)
1875    }
1876
1877    #[tool(description = "Check for Lua autogen updates.")]
1878    pub async fn check_lua_autogen_updates(&self) -> Result<CallToolResult, McpError> {
1879        send_and_respond!(self, "check_lua_autogen_updates", Command::CheckLuaAutogenUpdates)
1880    }
1881
1882    #[tool(description = "Check for Empire/Napoleon Assembly Kit updates.")]
1883    pub async fn check_empire_and_napoleon_ak_updates(&self) -> Result<CallToolResult, McpError> {
1884        send_and_respond!(self, "check_empire_and_napoleon_ak_updates", Command::CheckEmpireAndNapoleonAKUpdates)
1885    }
1886
1887    #[tool(description = "Check for translation updates.")]
1888    pub async fn check_translations_updates(&self) -> Result<CallToolResult, McpError> {
1889        send_and_respond!(self, "check_translations_updates", Command::CheckTranslationsUpdates)
1890    }
1891
1892    #[tool(description = "Update the Lua autogen repository.")]
1893    pub async fn update_lua_autogen(&self) -> Result<CallToolResult, McpError> {
1894        send_and_respond!(self, "update_lua_autogen", Command::UpdateLuaAutogen)
1895    }
1896
1897    #[tool(description = "Update the program to the latest version.")]
1898    pub async fn update_main_program(&self) -> Result<CallToolResult, McpError> {
1899        send_and_respond!(self, "update_main_program", Command::UpdateMainProgram)
1900    }
1901
1902    #[tool(description = "Update the Empire/Napoleon Assembly Kit files.")]
1903    pub async fn update_empire_and_napoleon_ak(&self) -> Result<CallToolResult, McpError> {
1904        send_and_respond!(self, "update_empire_and_napoleon_ak", Command::UpdateEmpireAndNapoleonAK)
1905    }
1906
1907    #[tool(description = "Update the translations repository.")]
1908    pub async fn update_translations(&self) -> Result<CallToolResult, McpError> {
1909        send_and_respond!(self, "update_translations", Command::UpdateTranslations)
1910    }
1911
1912    //-----------------------------------------------------------------------//
1913    // Settings Getters
1914    //-----------------------------------------------------------------------//
1915
1916    #[tool(description = "Get a boolean setting value by key.")]
1917    pub async fn settings_get_bool(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1918        send_and_respond!(self, "settings_get_bool", Command::SettingsGetBool(params.0.value))
1919    }
1920
1921    #[tool(description = "Get an i32 setting value by key.")]
1922    pub async fn settings_get_i32(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1923        send_and_respond!(self, "settings_get_i32", Command::SettingsGetI32(params.0.value))
1924    }
1925
1926    #[tool(description = "Get an f32 setting value by key.")]
1927    pub async fn settings_get_f32(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1928        send_and_respond!(self, "settings_get_f32", Command::SettingsGetF32(params.0.value))
1929    }
1930
1931    #[tool(description = "Get a string setting value by key.")]
1932    pub async fn settings_get_string(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1933        send_and_respond!(self, "settings_get_string", Command::SettingsGetString(params.0.value))
1934    }
1935
1936    #[tool(description = "Get a PathBuf setting value by key.")]
1937    pub async fn settings_get_path_buf(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1938        send_and_respond!(self, "settings_get_path_buf", Command::SettingsGetPathBuf(params.0.value))
1939    }
1940
1941    #[tool(description = "Get a Vec<String> setting value by key.")]
1942    pub async fn settings_get_vec_string(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1943        send_and_respond!(self, "settings_get_vec_string", Command::SettingsGetVecString(params.0.value))
1944    }
1945
1946    #[tool(description = "Get a raw bytes setting value by key.")]
1947    pub async fn settings_get_vec_raw(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
1948        send_and_respond!(self, "settings_get_vec_raw", Command::SettingsGetVecRaw(params.0.value))
1949    }
1950
1951    #[tool(description = "Get all settings at once (bool, i32, f32, string, raw_data, and vec_string maps).")]
1952    pub async fn settings_get_all(&self) -> Result<CallToolResult, McpError> {
1953        send_and_respond!(self, "settings_get_all", Command::SettingsGetAll)
1954    }
1955
1956    //-----------------------------------------------------------------------//
1957    // Settings Setters
1958    //-----------------------------------------------------------------------//
1959
1960    #[tool(description = "Set a boolean setting value.")]
1961    pub async fn settings_set_bool(&self, params: Parameters<SettingsSetBoolArgs>) -> Result<CallToolResult, McpError> {
1962        send_and_respond!(self, "settings_set_bool", Command::SettingsSetBool(params.0.key, params.0.value))
1963    }
1964
1965    #[tool(description = "Set an i32 setting value.")]
1966    pub async fn settings_set_i32(&self, params: Parameters<SettingsSetI32Args>) -> Result<CallToolResult, McpError> {
1967        send_and_respond!(self, "settings_set_i32", Command::SettingsSetI32(params.0.key, params.0.value))
1968    }
1969
1970    #[tool(description = "Set an f32 setting value.")]
1971    pub async fn settings_set_f32(&self, params: Parameters<SettingsSetF32Args>) -> Result<CallToolResult, McpError> {
1972        send_and_respond!(self, "settings_set_f32", Command::SettingsSetF32(params.0.key, params.0.value))
1973    }
1974
1975    #[tool(description = "Set a string setting value.")]
1976    pub async fn settings_set_string(&self, params: Parameters<SettingsSetStringArgs>) -> Result<CallToolResult, McpError> {
1977        send_and_respond!(self, "settings_set_string", Command::SettingsSetString(params.0.key, params.0.value))
1978    }
1979
1980    #[tool(description = "Set a PathBuf setting value.")]
1981    pub async fn settings_set_path_buf(&self, params: Parameters<SettingsSetPathBufArgs>) -> Result<CallToolResult, McpError> {
1982        send_and_respond!(self, "settings_set_path_buf", Command::SettingsSetPathBuf(params.0.key, params.0.value))
1983    }
1984
1985    #[tool(description = "Set a Vec<String> setting value.")]
1986    pub async fn settings_set_vec_string(&self, params: Parameters<SettingsSetVecStringArgs>) -> Result<CallToolResult, McpError> {
1987        send_and_respond!(self, "settings_set_vec_string", Command::SettingsSetVecString(params.0.key, params.0.value))
1988    }
1989
1990    #[tool(description = "Set a raw bytes setting value.")]
1991    pub async fn settings_set_vec_raw(&self, params: Parameters<SettingsSetVecRawArgs>) -> Result<CallToolResult, McpError> {
1992        send_and_respond!(self, "settings_set_vec_raw", Command::SettingsSetVecRaw(params.0.key, params.0.value))
1993    }
1994
1995    #[tool(description = "Backup the current settings to memory.")]
1996    pub async fn backup_settings(&self) -> Result<CallToolResult, McpError> {
1997        send_and_respond!(self, "backup_settings", Command::BackupSettings)
1998    }
1999
2000    #[tool(description = "Clear all settings and reset to defaults.")]
2001    pub async fn clear_settings(&self) -> Result<CallToolResult, McpError> {
2002        send_and_respond!(self, "clear_settings", Command::ClearSettings)
2003    }
2004
2005    #[tool(description = "Restore settings from the backup.")]
2006    pub async fn restore_backup_settings(&self) -> Result<CallToolResult, McpError> {
2007        send_and_respond!(self, "restore_backup_settings", Command::RestoreBackupSettings)
2008    }
2009
2010    //-----------------------------------------------------------------------//
2011    // Path Queries
2012    //-----------------------------------------------------------------------//
2013
2014    #[tool(description = "Get the config path.")]
2015    pub async fn config_path(&self) -> Result<CallToolResult, McpError> {
2016        send_and_respond!(self, "config_path", Command::ConfigPath)
2017    }
2018
2019    #[tool(description = "Get the Assembly Kit path for the current game.")]
2020    pub async fn assembly_kit_path(&self) -> Result<CallToolResult, McpError> {
2021        send_and_respond!(self, "assembly_kit_path", Command::AssemblyKitPath)
2022    }
2023
2024    #[tool(description = "Get the backup autosave path.")]
2025    pub async fn backup_autosave_path(&self) -> Result<CallToolResult, McpError> {
2026        send_and_respond!(self, "backup_autosave_path", Command::BackupAutosavePath)
2027    }
2028
2029    #[tool(description = "Get the old Assembly Kit data path.")]
2030    pub async fn old_ak_data_path(&self) -> Result<CallToolResult, McpError> {
2031        send_and_respond!(self, "old_ak_data_path", Command::OldAkDataPath)
2032    }
2033
2034    #[tool(description = "Get the schemas path.")]
2035    pub async fn schemas_path(&self) -> Result<CallToolResult, McpError> {
2036        send_and_respond!(self, "schemas_path", Command::SchemasPath)
2037    }
2038
2039    #[tool(description = "Get the table profiles path.")]
2040    pub async fn table_profiles_path(&self) -> Result<CallToolResult, McpError> {
2041        send_and_respond!(self, "table_profiles_path", Command::TableProfilesPath)
2042    }
2043
2044    #[tool(description = "Get the translations local path.")]
2045    pub async fn translations_local_path(&self) -> Result<CallToolResult, McpError> {
2046        send_and_respond!(self, "translations_local_path", Command::TranslationsLocalPath)
2047    }
2048
2049    #[tool(description = "Get the dependencies cache path.")]
2050    pub async fn dependencies_cache_path(&self) -> Result<CallToolResult, McpError> {
2051        send_and_respond!(self, "dependencies_cache_path", Command::DependenciesCachePath)
2052    }
2053
2054    #[tool(description = "Clear a config path.")]
2055    pub async fn settings_clear_path(&self, params: Parameters<PathArg>) -> Result<CallToolResult, McpError> {
2056        send_and_respond!(self, "settings_clear_path", Command::SettingsClearPath(params.0.path))
2057    }
2058
2059    //-----------------------------------------------------------------------//
2060    // Specialized
2061    //-----------------------------------------------------------------------//
2062
2063    #[tool(description = "Get the info about the pack identified by `pack_key` and the list of files it contains.")]
2064    pub async fn open_pack_info(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
2065        send_and_respond!(self, "open_pack_info", Command::GetPackFileDataForTreeView(params.0.pack_key))
2066    }
2067
2068    #[tool(description = "Initialize a MyMod folder for mod development.")]
2069    pub async fn initialize_my_mod_folder(&self, params: Parameters<InitializeMyModFolderArgs>) -> Result<CallToolResult, McpError> {
2070        send_and_respond!(self, "initialize_my_mod_folder", Command::InitializeMyModFolder(params.0.name, params.0.game, params.0.sublime, params.0.vscode, params.0.gitignore))
2071    }
2072
2073    #[tool(description = "Live export the pack identified by `pack_key` to the game folder for testing.")]
2074    pub async fn live_export(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
2075        send_and_respond!(self, "live_export", Command::LiveExport(params.0.pack_key))
2076    }
2077
2078    #[tool(description = "Patch the SiegeAI of a Siege Map in the pack identified by `pack_key` for Warhammer games.")]
2079    pub async fn patch_siege_ai(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
2080        send_and_respond!(self, "patch_siege_ai", Command::PatchSiegeAI(params.0.pack_key))
2081    }
2082
2083    #[tool(description = "Pack map tiles into the pack identified by `pack_key`. The `tile_maps` is a list of tile map file paths on disk. The `tiles` is a JSON array of [path, name] pairs, e.g. [[\"/path/to/tile\", \"tile_name\"]].")]
2084    pub async fn pack_map(&self, params: Parameters<PackMapArgs>) -> Result<CallToolResult, McpError> {
2085        let tiles: Vec<(PathBuf, String)> = parse_json!(&params.0.tiles);
2086        send_and_respond!(self, "pack_map", Command::PackMap(params.0.pack_key, params.0.tile_maps, tiles))
2087    }
2088
2089    #[tool(description = "Generate all missing loc entries for the pack identified by `pack_key`.")]
2090    pub async fn generate_missing_loc_data(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
2091        send_and_respond!(self, "generate_missing_loc_data", Command::GenerateMissingLocData(params.0.pack_key))
2092    }
2093
2094    #[tool(description = "Get pack translation data for a language from the pack identified by `pack_key`.")]
2095    pub async fn get_pack_translation(&self, params: Parameters<GetPackTranslationArgs>) -> Result<CallToolResult, McpError> {
2096        send_and_respond!(self, "get_pack_translation", Command::GetPackTranslation(params.0.pack_key, params.0.language))
2097    }
2098
2099    #[tool(description = "Get campaign IDs for starpos building in the pack identified by `pack_key`.")]
2100    pub async fn build_starpos_get_campaign_ids(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
2101        send_and_respond!(self, "build_starpos_get_campaign_ids", Command::BuildStarposGetCampaingIds(params.0.pack_key))
2102    }
2103
2104    #[tool(description = "Check if victory conditions file exists for starpos building in the pack identified by `pack_key`.")]
2105    pub async fn build_starpos_check_victory_conditions(&self, params: Parameters<PackKeyArg>) -> Result<CallToolResult, McpError> {
2106        send_and_respond!(self, "build_starpos_check_victory_conditions", Command::BuildStarposCheckVictoryConditions(params.0.pack_key))
2107    }
2108
2109    #[tool(description = "Build starpos (pre-processing step) for the pack identified by `pack_key`.")]
2110    pub async fn build_starpos(&self, params: Parameters<BuildStarposArgs>) -> Result<CallToolResult, McpError> {
2111        send_and_respond!(self, "build_starpos", Command::BuildStarpos(params.0.pack_key, params.0.campaign_id, params.0.process_hlp_spd))
2112    }
2113
2114    #[tool(description = "Build starpos (post-processing step) for the pack identified by `pack_key`.")]
2115    pub async fn build_starpos_post(&self, params: Parameters<BuildStarposArgs>) -> Result<CallToolResult, McpError> {
2116        send_and_respond!(self, "build_starpos_post", Command::BuildStarposPost(params.0.pack_key, params.0.campaign_id, params.0.process_hlp_spd))
2117    }
2118
2119    #[tool(description = "Clean up starpos temporary files for the pack identified by `pack_key`.")]
2120    pub async fn build_starpos_cleanup(&self, params: Parameters<BuildStarposArgs>) -> Result<CallToolResult, McpError> {
2121        send_and_respond!(self, "build_starpos_cleanup", Command::BuildStarposCleanup(params.0.pack_key, params.0.campaign_id, params.0.process_hlp_spd))
2122    }
2123
2124    #[tool(description = "Update animation IDs with an offset in the pack identified by `pack_key`.")]
2125    pub async fn update_anim_ids(&self, params: Parameters<UpdateAnimIdsArgs>) -> Result<CallToolResult, McpError> {
2126        send_and_respond!(self, "update_anim_ids", Command::UpdateAnimIds(params.0.pack_key, params.0.starting_id, params.0.offset))
2127    }
2128
2129    #[tool(description = "Get animation paths by skeleton name.")]
2130    pub async fn get_anim_paths_by_skeleton_name(&self, params: Parameters<StringArg>) -> Result<CallToolResult, McpError> {
2131        send_and_respond!(self, "get_anim_paths_by_skeleton_name", Command::GetAnimPathsBySkeletonName(params.0.value))
2132    }
2133
2134    #[tool(description = "Export a RigidModel to glTF format. The `rigid_model` is a RigidModel JSON object (as returned by decoding a .rigid_model_v2 file with `decode_packed_file`). The `output_path` is the destination file path on disk.")]
2135    pub async fn export_rigid_to_gltf(&self, params: Parameters<ExportRigidToGltfArgs>) -> Result<CallToolResult, McpError> {
2136        let rigid = parse_json!(&params.0.rigid_model);
2137        send_and_respond!(self, "export_rigid_to_gltf", Command::ExportRigidToGltf(rigid, params.0.output_path))
2138    }
2139
2140    #[tool(description = "Change the format of a ca_vp8 video file in the pack identified by `pack_key`. Valid formats: \"CaVp8\" (CA custom VP8) or \"Ivf\" (standard VP8 IVF).")]
2141    pub async fn set_video_format(&self, params: Parameters<SetVideoFormatArgs>) -> Result<CallToolResult, McpError> {
2142        let format = parse_json!(&params.0.format);
2143        send_and_respond!(self, "set_video_format", Command::SetVideoFormat(params.0.pack_key, params.0.path, format))
2144    }
2145
2146    //-----------------------------------------------------------------------//
2147    // Multi-Pack Management
2148    //-----------------------------------------------------------------------//
2149
2150    #[tool(description = "List all currently open packs with their keys and metadata. Use this to get valid pack_key values for other tools.")]
2151    pub async fn list_open_packs(&self) -> Result<CallToolResult, McpError> {
2152        send_and_respond!(self, "list_open_packs", Command::ListOpenPacks)
2153    }
2154
2155    //-----------------------------------------------------------------------//
2156    // Additional tools
2157    //-----------------------------------------------------------------------//
2158
2159    #[tool(description = "Close all currently open packs without saving. Any unsaved changes will be lost.")]
2160    pub async fn close_all_packs(&self) -> Result<CallToolResult, McpError> {
2161        send_and_respond!(self, "close_all_packs", Command::CloseAllPacks)
2162    }
2163
2164}
2165
2166//-------------------------------------------------------------------------------//
2167//                              MCP Prompts
2168//-------------------------------------------------------------------------------//
2169
2170#[prompt_router]
2171impl McpServer {
2172
2173    #[prompt(name = "open_and_inspect_pack", description = "Walk through opening a PackFile and inspecting its contents.")]
2174    pub async fn open_and_inspect_pack(&self) -> Vec<PromptMessage> {
2175        vec![PromptMessage::new_text(
2176            Role::User,
2177            "\
2178You are an assistant helping the user inspect a Total War PackFile using the RPFM MCP server.
2179
2180Follow these steps in order:
2181
21821. **Open the pack** – Call `open_packfiles` with the filesystem path(s) the user provides.
2183   The response contains one or more pack keys; remember them for subsequent calls.
2184
21852. **Select the game** – Call `set_game_selected` with the correct game key (e.g. `\"warhammer_3\"`)
2186   and `rebuild_dependencies: true` so that schemas and dependency data are loaded.
2187
21883. **List pack contents** – Call `open_pack_info` with the pack key to get the full file tree.
2189   Present the tree to the user in a readable format.
2190
21914. **Decode specific files** – When the user asks about a file, call `decode_packed_file` with the
2192   pack key, the internal path (e.g. `\"db/land_units_tables/my_table\"`), and
2193   `source: \"PackFile\"`. The decoded JSON will contain the table rows, schema, etc.
2194
21955. **Inspect metadata** – Use `get_pack_settings`, `get_pack_file_name`, or
2196   `get_dependency_pack_files_list` to answer questions about the pack itself.
2197
2198Important notes:
2199- Always call `list_open_packs` if you are unsure which pack key to use.
2200- If a file fails to decode, check `is_schema_loaded`; if false, call `update_schemas` first.
2201- When done, optionally call `close_pack` to free resources.
2202",
2203        )]
2204    }
2205
2206    #[prompt(name = "edit_db_table", description = "Guide for reading, modifying, and saving a DB table inside a pack.")]
2207    pub async fn edit_db_table(&self) -> Vec<PromptMessage> {
2208        vec![PromptMessage::new_text(
2209            Role::User,
2210            "\
2211You are an assistant helping the user edit a DB table inside a Total War PackFile.
2212
2213Workflow:
2214
22151. **Open the pack** – `open_packfiles` → note the `pack_key`.
22162. **Set the game** – `set_game_selected` with `rebuild_dependencies: true`.
22173. **Decode the table** – `decode_packed_file` with the DB path
2218   (e.g. `\"db/unit_stats_land_tables/my_table\"`) and `source: \"PackFile\"`.
2219   The response is an `RFileDecoded` JSON containing the table data and definition.
22204. **Modify rows** – Edit the decoded JSON: add, remove, or change rows/cells.
2221   Each row is typically a list of `DecodedData` values matching the table's
2222   fields processed list (retrievable via the `FieldsProcessed` message).
22235. **Save back** – Call `save_packed_file_from_view` with the pack key, the same path,
2224   and the modified `RFileDecoded` JSON as the `data` parameter.
22256. **Save the pack** – Call `save_packfile` (or `save_pack_as` for a new path).
2226
2227Tips:
2228- Use `get_table_definition_from_dependency_pack_file` to see the table's definition, but
2229  always run it through `fields_processed` before using its field list/count — the
2230  definition's raw `fields` do NOT match row shape (e.g. a colour column is split into
2231  separate r/g/b fields there); rows must match `fields_processed` exactly or saving
2232  will fail with a field-count or type error.
2233- Use `get_reference_data_from_definition` to discover valid values for referenced columns.
2234- After saving, you can run `diagnostics_check` to validate the pack.
2235",
2236        )]
2237    }
2238
2239    #[prompt(name = "create_new_mod", description = "Step-by-step guide for creating a new mod PackFile from scratch.")]
2240    pub async fn create_new_mod(&self) -> Vec<PromptMessage> {
2241        vec![PromptMessage::new_text(
2242            Role::User,
2243            "\
2244You are an assistant helping the user create a new Total War mod from scratch.
2245
2246Workflow:
2247
22481. **Set the game** – `set_game_selected` with the target game key and
2249   `rebuild_dependencies: true`.
2250
22512. **Create the pack** – `new_pack` returns a new empty pack and its pack key.
2252
22533. **Set pack type** – `set_pack_file_type` to `\"Mod\"` (the standard type for mods).
2254
22554. **Add DB tables** – For each table you need:
2256   a. Call `new_packed_file` with the pack key, the path (e.g. `\"db/land_units_tables/my_mod\"`),
2257      and the `new_file` JSON set to `\"DB\"` with the table name.
2258   b. Decode, edit, and save as described in the `edit_db_table` workflow.
2259
22605. **Add Loc files** – For localisation:
2261   a. `new_packed_file` with path `\"text/db/my_mod.loc\"` and `new_file` set to `\"Loc\"`.
2262   b. Decode, add key/value rows, and save.
2263
22646. **Add other files** – Use `add_packed_files` to import assets from disk (images, models, etc.).
2265
22667. **Save the pack** – `save_pack_as` to write the final `.pack` file to disk.
2267
2268Optional steps:
2269- `initialize_my_mod_folder` to set up a mod development folder with IDE support.
2270- `optimize_pack_file` to strip unchanged rows that match vanilla data.
2271- `diagnostics_check` to validate everything before release.
2272",
2273        )]
2274    }
2275
2276    #[prompt(name = "search_and_replace", description = "Find and replace values across all files in a pack.")]
2277    pub async fn search_and_replace(&self) -> Vec<PromptMessage> {
2278        vec![PromptMessage::new_text(
2279            Role::User,
2280            "\
2281You are an assistant helping the user search for and replace data across a PackFile.
2282
2283Workflow:
2284
22851. **Open the pack** and **set the game** (see `open_and_inspect_pack` prompt).
2286
22872. **Run a global search** – Call `global_search` with the pack key and a `GlobalSearch`
2288   JSON object. The search object specifies the pattern, whether to use regex, which file
2289   types to include (DB, Loc, Text), and the replacement string.
2290
22913. **Review matches** – The response contains all matches grouped by file.
2292   Present them to the user for review.
2293
22944. **Replace selectively** – Call `global_search_replace_matches` with the same search
2295   object and a `Vec<MatchHolder>` containing only the matches the user approved.
2296
22975. **Or replace all** – If the user confirms a blanket replace, call
2298   `global_search_replace_all` with the search object.
2299
23006. **Save** – `save_packfile` to persist changes.
2301
2302Related tools:
2303- `search_references` – Find all rows that reference a specific value across tables.
2304- `go_to_definition` – Jump to where a referenced key is defined.
2305- `go_to_loc` – Find the loc entry for a given key.
2306",
2307        )]
2308    }
2309
2310    #[prompt(name = "manage_dependencies", description = "Set up and work with game dependencies and vanilla data.")]
2311    pub async fn manage_dependencies(&self) -> Vec<PromptMessage> {
2312        vec![PromptMessage::new_text(
2313            Role::User,
2314            "\
2315You are an assistant helping the user work with dependency data (vanilla game files).
2316
2317Workflow:
2318
23191. **Set the game** – `set_game_selected` with `rebuild_dependencies: true`.
2320
23212. **Check dependency database** – `is_there_a_dependency_database` with `true` to verify
2322   that game data (including Assembly Kit data) is loaded.
2323   If it returns false, call `generate_dependencies_cache` first.
2324
23253. **Browse vanilla tables** – `get_table_list_from_dependency_pack_file` returns all
2326   DB table names from the vanilla game files.
2327
23284. **Read vanilla data** – `get_tables_from_dependencies` with a table name to get
2329   all rows from vanilla for that table.
2330
23315. **Get definitions** – `get_table_definition_from_dependency_pack_file` to get the
2332   schema definition for any table.
2333
23346. **Import from vanilla** – `import_dependencies_to_open_pack_file` to copy specific
2335   files from vanilla into your mod pack.
2336
23377. **Open CA packs** – `load_all_ca_pack_files` opens all vanilla packs as one merged
2338   read-only pack for full browsing.
2339
23408. **Cross-source lookups** – `get_rfiles_from_all_sources` retrieves files by path
2341   from PackFile, GameFiles, and ParentFiles simultaneously.
2342
2343Tips:
2344- Use `get_packed_files_names_starting_with_path_from_all_sources` to discover files
2345  under a given path prefix across all sources.
2346- `set_dependency_pack_files_list` lets you mark other mods as dependencies of your pack.
2347- The `definition` bundled in each file from `get_tables_from_dependencies` (and from
2348  `get_table_definition_from_dependency_pack_file`) lists RAW on-disk fields, which can
2349  have a different length/order than the actual decoded rows (e.g. colour columns are
2350  split into separate r/g/b fields there). Run it through `fields_processed` before
2351  matching it up against row cells or reusing it to build new rows.
2352",
2353        )]
2354    }
2355
2356    #[prompt(name = "run_diagnostics", description = "Validate a pack and fix common issues.")]
2357    pub async fn run_diagnostics(&self) -> Vec<PromptMessage> {
2358        vec![PromptMessage::new_text(
2359            Role::User,
2360            "\
2361You are an assistant helping the user validate a Total War mod PackFile.
2362
2363Workflow:
2364
23651. **Open the pack** and **set the game** with `rebuild_dependencies: true`.
2366
23672. **Generate dependencies** – If dependencies have not been generated yet,
2368   call `generate_dependencies` to build the dependency data needed for diagnostics.
2369
23703. **Run full diagnostics** – `diagnostics_check` with an empty `ignored` list
2371   and `check_ak_only_refs: false` (or `true` to include Assembly Kit references).
2372   The response contains all warnings and errors grouped by category.
2373
23744. **Review results** – Present the diagnostic results to the user, grouped by severity.
2375   Common issues include:
2376   - Invalid references (a column references a key that does not exist)
2377   - Duplicate keys
2378   - Empty loc entries
2379   - Outdated table versions
2380
23815. **Fix issues** – For each issue:
2382   - Decode the affected file with `decode_packed_file`.
2383   - Apply the fix (correct a reference, remove a duplicate row, etc.).
2384   - Save with `save_packed_file_from_view`.
2385
23866. **Ignore false positives** – Use `add_line_to_pack_ignored_diagnostics` to suppress
2387   specific diagnostic lines that are intentional.
2388
23897. **Re-check** – After fixes, call `diagnostics_check` again to confirm all issues
2390   are resolved.
2391
23928. **Optimize** – Optionally run `optimize_pack_file` to remove rows that are identical
2393   to vanilla, reducing pack size.
2394",
2395        )]
2396    }
2397
2398    #[prompt(name = "schema_operations", description = "Work with table schemas: inspect, update, and patch definitions.")]
2399    pub async fn schema_operations(&self) -> Vec<PromptMessage> {
2400        vec![PromptMessage::new_text(
2401            Role::User,
2402            "\
2403You are an assistant helping the user manage RPFM table schemas.
2404
2405Workflow:
2406
24071. **Check schema status** – `is_schema_loaded` to verify a schema is loaded.
2408   If not, call `update_schemas` to download the latest from the repository.
2409
24102. **Get the full schema** – `get_schema` returns the entire schema object.
2411
24123. **Inspect a table definition** – `definitions_by_table_name` with a table name
2413   returns all known versions. Use `definition_by_table_name_and_version` for a
2414   specific version.
2415
24164. **See processed fields** – `fields_processed` takes a Definition JSON and returns
2417   fields with bitwise expansion, enum conversions, and colour-group merging applied.
2418   This is required, not just cosmetic: `definitions_by_table_name` and
2419   `definition_by_table_name_and_version` return the raw on-disk field list (e.g. a
2420   colour column split into separate r/g/b fields), which has a different length/order
2421   than actual row data. Always call `fields_processed` before using a definition's
2422   field list/count to build or validate rows for saving.
2423
24245. **Find referencing columns** – `referencing_columns_for_definition` shows which
2425   other tables reference a given table's columns.
2426
24276. **Patch a definition** – To customise column metadata (descriptions, references,
2428   default values) without modifying the upstream schema:
2429   a. Build a `HashMap<String, DefinitionPatch>` with your changes.
2430   b. Call `save_local_schema_patch` to persist it locally.
2431   c. Use `remove_local_schema_patches_for_table` or
2432      `remove_local_schema_patches_for_table_and_field` to undo patches.
2433
24347. **Import patches** – `import_schema_patch` applies a patch from another source.
2435
24368. **Update from Assembly Kit** – `update_current_schema_from_asskit` merges
2437   definition data from the game's Assembly Kit into the loaded schema.
2438
24399. **Save the schema** – `save_schema` writes the current in-memory schema to disk.
2440",
2441        )]
2442    }
2443
2444    #[prompt(name = "file_operations", description = "Add, remove, rename, extract, and move files within packs.")]
2445    pub async fn file_operations(&self) -> Vec<PromptMessage> {
2446        vec![PromptMessage::new_text(
2447            Role::User,
2448            "\
2449You are an assistant helping the user manage files inside a Total War PackFile.
2450
2451Common operations:
2452
2453**Add files from disk:**
2454- `add_packed_files` – Import files from the filesystem into the pack. Provide source
2455  filesystem paths and destination `ContainerPath` entries as JSON.
2456
2457**Add files from another pack:**
2458- `add_packed_files_from_pack_file` – Copy files between two open packs.
2459
2460**Create new files:**
2461- `new_packed_file` – Create a blank DB table, Loc file, or other file type inside the pack.
2462
2463**Delete files:**
2464- `delete_packed_files` – Remove files by their `ContainerPath` list.
2465
2466**Rename / move files:**
2467- `rename_packed_files` – Pass a list of `(old_path, new_path)` tuples.
2468
2469**Copy / Cut / Paste / Duplicate:**
2470- `copy_packed_files` – Copy files to the internal clipboard for later pasting.
2471- `cut_packed_files` – Cut files to the internal clipboard (removed from source on paste).
2472- `paste_packed_files` – Paste clipboard contents into a pack at the given folder path.
2473- `duplicate_packed_files` – Clone files in-place with a numeric suffix.
2474
2475**Extract to disk:**
2476- `extract_packed_files` – Export files from the pack to a folder on disk.
2477  Set `export_as_tsv: true` to export tables as TSV files.
2478
2479**AnimPack operations:**
2480- `add_packed_files_from_pack_file_to_animpack` – Add files to an AnimPack.
2481- `add_packed_files_from_animpack` – Extract files from an AnimPack.
2482- `delete_from_animpack` – Remove files from an AnimPack.
2483
2484**File info:**
2485- `get_packed_files_info` / `get_rfile_info` – Get metadata about files.
2486- `folder_exists` / `packed_file_exists` – Check if a path exists.
2487- `get_packed_file_raw_data` – Get the raw binary content of a file.
2488
2489**Merge tables:**
2490- `merge_files` – Combine multiple compatible tables into one.
2491
2492**External editing:**
2493- `open_packed_file_in_external_program` – Open a file in the system's default editor.
2494- `save_packed_file_from_external_view` – Re-import after external editing.
2495
2496Always call `save_packfile` or `save_pack_as` when done to persist changes.
2497",
2498        )]
2499    }
2500
2501    #[prompt(name = "troubleshooting", description = "Diagnose and fix common issues with RPFM and PackFiles.")]
2502    pub async fn troubleshooting(&self) -> Vec<PromptMessage> {
2503        vec![PromptMessage::new_text(
2504            Role::User,
2505            "\
2506You are an assistant helping the user troubleshoot common RPFM and PackFile issues.
2507
2508## Common Issues and Solutions
2509
2510### 1. Schema not loaded
2511**Symptom**: Files fail to decode, or `decode_packed_file` returns raw data.
2512**Solution**:
2513- Call `is_schema_loaded()` – if false, call `update_schemas()`.
2514- Make sure `set_game_selected` was called with `rebuild_dependencies: true`.
2515
2516### 2. Dependencies not available
2517**Symptom**: References show as invalid, diagnostics report missing keys.
2518**Solution**:
2519- Call `is_there_a_dependency_database(true)` – if false, call `generate_dependencies_cache()`.
2520- Ensure the game path is configured correctly in settings.
2521
2522### 3. Pack won't save
2523**Symptom**: `save_packfile` returns an error.
2524**Solution**:
2525- Check if the file is read-only or locked by another process.
2526- Try `save_pack_as` to a different path.
2527- As a last resort, use `clean_and_save_pack_as` to recover from corruption.
2528
2529### 4. Table version mismatch
2530**Symptom**: Table data looks wrong or has missing columns after a game update.
2531**Solution**:
2532- Call `update_schemas()` to get the latest table definitions.
2533- Use `update_table` to migrate the table to the current version.
2534- Check `get_table_definition_from_dependency_pack_file` for the expected schema.
2535
2536### 5. Wrong game selected
2537**Symptom**: Tables decode with wrong columns or fail to decode, dependencies are for a different game.
2538**Solution**:
2539- Call `get_game_selected()` to verify the current game.
2540- Call `set_game_selected` with the correct game key and `rebuild_dependencies: true`.
2541
2542### 6. Diagnostics show many reference errors
2543**Symptom**: `diagnostics_check` reports hundreds of invalid references.
2544**Solution**:
2545- Ensure dependencies are loaded (`is_there_a_dependency_database(true)`).
2546- Check if the pack depends on other mods via `get_dependency_pack_files_list`.
2547- Some references are Assembly Kit only; re-run with `check_ak_only_refs: true`.
2548- Use `add_line_to_pack_ignored_diagnostics` for intentional deviations.
2549
2550### Diagnostic Tools
2551- `diagnostics_check` – Full pack validation.
2552- `get_game_selected` – Verify game context.
2553- `is_schema_loaded` – Check schema status.
2554- `is_there_a_dependency_database` – Check dependency database status.
2555- `list_open_packs` – Verify which packs are open.
2556- `config_path` / `schemas_path` – Verify RPFM paths.
2557",
2558        )]
2559    }
2560
2561    #[prompt(name = "tsv_workflow", description = "Import and export tables as TSV files for batch editing in spreadsheets.")]
2562    pub async fn tsv_workflow(&self) -> Vec<PromptMessage> {
2563        vec![PromptMessage::new_text(
2564            Role::User,
2565            "\
2566You are an assistant helping the user work with TSV (Tab-Separated Values) files for batch editing \
2567Total War mod data in spreadsheets.
2568
2569## Export Workflow (Pack → TSV → Spreadsheet)
2570
25711. **Open the pack** and **set the game** with `rebuild_dependencies: true`.
2572
25732. **Export a single table as TSV**:
2574   Call `export_tsv` with:
2575   - `pack_key`: the pack key
2576   - `tsv_path`: destination path on disk (e.g. `/home/user/my_table.tsv`)
2577   - `table_path`: the internal path (e.g. `db/land_units_tables/my_mod`)
2578
25793. **Export all tables as TSV**:
2580   Call `extract_packed_files` with `export_as_tsv: true`.
2581   This exports all tables in the pack as TSV files to the destination folder.
2582
25834. **Edit in a spreadsheet**: Open the TSV file in LibreOffice Calc, Excel, or Google Sheets.
2584   - Keep the header rows intact (they contain schema metadata).
2585   - Tab-separated values — do not change the delimiter.
2586
2587## Import Workflow (Spreadsheet → TSV → Pack)
2588
25891. **Save the spreadsheet as TSV** (tab-delimited, UTF-8 encoding).
2590
25912. **Import the TSV back**:
2592   Call `import_tsv` with:
2593   - `pack_key`: the target pack key
2594   - `tsv_path`: path to the TSV file on disk
2595   - `table_path`: the internal path where the table should go
2596
25973. **Verify**: Call `decode_packed_file` to confirm the data imported correctly.
2598
25994. **Save the pack**: Call `save_packfile` to persist changes.
2600
2601## Tips
2602- TSV files include metadata headers that RPFM uses for schema matching.
2603  Do not delete or modify these header rows.
2604- Use `get_table_definition_from_dependency_pack_file` to understand column types
2605  before editing.
2606- After import, run `diagnostics_check` to validate references.
2607",
2608        )]
2609    }
2610
2611    #[prompt(name = "translation_workflow", description = "Work with localisation and translation data in PackFiles.")]
2612    pub async fn translation_workflow(&self) -> Vec<PromptMessage> {
2613        vec![PromptMessage::new_text(
2614            Role::User,
2615            "\
2616You are an assistant helping the user work with localisation (translation) data in Total War mods.
2617
2618## Understanding Loc Files
2619
2620Loc files contain key-value pairs for in-game text. Each entry has:
2621- A **key** (unique identifier referenced by DB tables)
2622- A **value** (the displayed text in the game)
2623
2624## Viewing Existing Translations
2625
26261. **Open the pack** and **set the game**.
2627
26282. **Decode a loc file**:
2629   Call `decode_packed_file` with the loc file path (e.g. `text/db/my_mod.loc`)
2630   and `source: \"PackFile\"`.
2631
26323. **Get translation overview**:
2633   Call `get_pack_translation` with the pack key and a language code
2634   (e.g. `\"en\"`, `\"fr\"`, `\"de\"`, `\"es\"`, `\"it\"`, `\"zh\"`, `\"ru\"`, etc.).
2635
2636## Creating New Translations
2637
26381. **Create a new loc file**:
2639   Call `new_packed_file` with path `\"text/db/my_mod.loc\"` and
2640   `new_file = {\"Loc\": \"my_mod\"}`.
2641
26422. **Decode it**: `decode_packed_file` to get the empty structure.
2643
26443. **Add entries**: Modify the decoded JSON to add key-value rows.
2645   Each row is typically `[\"key_string\", \"Displayed text in game\"]`.
2646
26474. **Save back**: `save_packed_file_from_view` with the modified data.
2648
2649## Generating Missing Loc Data
2650
2651Call `generate_missing_loc_data` with the pack key to auto-generate
2652loc entries for DB fields that reference loc keys but don't have entries yet.
2653
2654## Finding Loc Keys
2655
2656- Use `go_to_loc` with a loc key to find its source loc file.
2657- Use `get_source_data_from_loc_key` to find where a loc key is referenced.
2658- Use `global_search` with `search_on.loc: true` to search across all loc files.
2659
2660## Tips
2661- Loc keys follow naming conventions like `<table>_<loc_column_name>_<keys_concatenated>`.
2662- Use `search_references` to find all DB columns that reference a specific loc key.
2663- After adding translations, run `diagnostics_check` to verify all references.
2664",
2665        )]
2666    }
2667}