Skip to main content

Crate tower_mcp_macros

Crate tower_mcp_macros 

Source
Expand description

Proc macros for tower-mcp.

Provides #[tool_fn], #[prompt_fn], #[resource_fn], and #[resource_template_fn] as optional syntactic sugar over the builder APIs. The macros generate builder code – you can always eject to the builder pattern for full control.

Enable via the macros feature on tower-mcp:

tower-mcp = { version = "0.27", features = ["macros"] }

§Tool Example

ⓘ
use tower_mcp::tool_fn;
use tower_mcp::CallToolResult;
use schemars::JsonSchema;
use serde::Deserialize;

#[derive(Debug, Deserialize, JsonSchema)]
struct AddInput { a: i64, b: i64 }

#[tool_fn(description = "Add two numbers")]
async fn add(input: AddInput) -> Result<CallToolResult, tower_mcp::Error> {
    Ok(CallToolResult::text(format!("{}", input.a + input.b)))
}

// Generates `add_tool() -> tower_mcp::tool::Tool`

§Prompt Example

ⓘ
use std::collections::HashMap;
use tower_mcp::prompt_fn;
use tower_mcp::protocol::GetPromptResult;

#[prompt_fn(description = "Greet someone", args(name = "Name to greet"))]
async fn greet(args: HashMap<String, String>) -> Result<GetPromptResult, tower_mcp::Error> {
    let name = args.get("name").cloned().unwrap_or_default();
    Ok(GetPromptResult::user_message(format!("Hello, {name}!")))
}

// Generates `greet_prompt() -> tower_mcp::prompt::Prompt`

§Resource Example

ⓘ
use tower_mcp::resource_fn;
use tower_mcp::protocol::ReadResourceResult;

#[resource_fn(uri = "app://config", description = "App configuration")]
async fn config() -> Result<ReadResourceResult, tower_mcp::Error> {
    Ok(ReadResourceResult::text("app://config", "debug=true"))
}

// Generates `config_resource() -> tower_mcp::resource::Resource`

§Resource Template Example

ⓘ
use std::collections::HashMap;
use tower_mcp::resource_template_fn;
use tower_mcp::protocol::ReadResourceResult;

#[resource_template_fn(
    uri_template = "file:///{+path}",
    name = "file",
    description = "Read a file by path"
)]
async fn read_file(
    uri: String,
    vars: HashMap<String, String>,
) -> Result<ReadResourceResult, tower_mcp::Error> {
    let path = vars.get("path").cloned().unwrap_or_default();
    Ok(ReadResourceResult::text(uri, format!("contents of {path}")))
}

// Generates `read_file_resource_template() -> tower_mcp::resource::ResourceTemplate`

Attribute Macros§

prompt_fn
Generates a prompt constructor function from an async handler.
resource_fn
Generates a static resource constructor function from an async handler.
resource_template_fn
Generates a resource template constructor function from an async handler.
tool_fn
Generates a tool constructor function from an async handler.