> ## Documentation Index
> Fetch the complete documentation index at: https://docs.nagare.smtdfc.net/llms.txt
> Use this file to discover all available pages before exploring further.

# SDK Rust

> Viết plugin Nagare bằng Rust với crate nagare_plugin.

## Cài đặt

Crate `nagare_plugin` nằm trong kho mã Nagare. Thêm vào `Cargo.toml`:

```toml Cargo.toml theme={null}
[package]
name = "hello-plugin"
version = "0.1.0"
edition = "2024"

[dependencies]
nagare_plugin = { git = "https://github.com/smtdfc/nagare" }
tokio = { version = "1", features = ["full"] }
serde = { version = "1", features = ["derive"] }
schemars = "0.8"
```

Tạo `metadata.json` như hướng dẫn trong [Tổng quan plugin](https://docs.nagare.smtdfc.net/plugins/overview.md#metadata-json).

## Ví dụ: plugin thêm công cụ

```rust src/main.rs theme={null}
use std::collections::HashMap;

use nagare_plugin::{PluginClient, PluginError, define_tool};
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};

const METADATA: &str = include_str!("../metadata.json");

#[derive(Deserialize, JsonSchema)]
struct GreetArgs {
    /// Tên người cần chào
    name: String,
}

#[derive(Serialize)]
struct GreetResult {
    message: String,
}

#[tokio::main]
async fn main() -> Result<(), PluginError> {
    let client = PluginClient::new();
    client.load_metadata(METADATA)?;

    let greet = define_tool(
        "greet_tool",
        "Tạo lời chào cho một người.",
        |args: GreetArgs| -> Result<GreetResult, PluginError> {
            Ok(GreetResult { message: format!("Xin chào, {}!", args.name) })
        },
        vec!["greeting".to_string()],
    );

    let c = client.clone();
    client
        .start(|| async move {
            if c.handshake().await.is_err() {
                return;
            }

            let mut categories = HashMap::new();
            categories.insert("greeting".to_string(), "Công cụ tạo lời chào".to_string());
            let _ = c.register_tool_categories(categories).await;

            let _ = c.register_plugin_tool(greet).await;
        })
        .await
}
```

Build gói:

```bash theme={null}
nagare plugin build
```

Lệnh build chạy `cargo build --release --target-dir build` và đóng gói tệp thực thi.

## Tham chiếu API

| Hàm | Mô tả |
| - | - |
| `PluginClient::new()` | Tạo client (trả về `Arc<PluginClient>`). Yêu cầu biến `NAGARE_PLUGIN_LOG_FILE` và `NAGARE_PLUGIN_CONFIG_DIR`, gateway đặt sẵn khi chạy plugin. |
| `load_metadata(raw)` | Nạp và kiểm tra `metadata.json`. |
| `start(on_start)` | Kết nối gateway, chạy `on_start` rồi chờ đến khi kết nối đóng. |
| `handshake()` | Bắt tay với gateway. Gọi đầu tiên trong `on_start`. |
| `define_tool(name, description, callback, categories)` | Định nghĩa công cụ. Kiểu tham số phải triển khai `Deserialize` và `JsonSchema`, kiểu kết quả triển khai `Serialize`. |
| `register_plugin_tool(tool)` | Đăng ký công cụ. Cần feature `plugin_tool`. |
| `register_tool_categories(map)` | Đăng ký danh mục công cụ (tên → mô tả). |
| `prepare_chat_channel(channel_id)` | Tạo hoặc mở lại kênh trò chuyện. Cần feature `chat`. |
| `send_chat_message(channel_id, text)` | Gửi tin nhắn tới agent. |
| `reset_chat_channel(channel_id)` | Bắt đầu phiên mới cho kênh. |
| `set_on_received_chat_message(cb)` | Callback `Fn(channel_id: String, chunk: String)` nhận phản hồi dạng JSON. |
| `config_dir()` | Thư mục cấu hình riêng của plugin. |

Mỗi lần gọi công cụ có thời gian chờ tối đa 60 giây.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.