universal-tool-macros 0.1.11

DEPRECATED: Use agentic-tools-* crates and agentic-mcp instead. Procedural macros for Universal Tool Framework.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! REST API code generation for Universal Tool Framework
//!
//! This module generates `create_rest_router()` and `get_openapi_spec()` methods
//! that integrate tools with axum-based REST APIs.

use crate::codegen::shared::to_kebab_case;
use crate::codegen::shared::to_pascal_case;
use crate::model::HttpMethod;
use crate::model::ParamSource;
use crate::model::RouterDef;
use crate::model::ToolDef;
use proc_macro2::TokenStream;
use quote::quote;
use syn::spanned::Spanned;

/// Generates all REST-related methods for a router
/// Returns a tuple of (module_code, method_code) to allow proper separation
pub fn generate_rest_methods_split(router: &RouterDef) -> (TokenStream, TokenStream) {
    let struct_type = &router.struct_type;

    // Generate a unique module name based on the struct type
    let module_name = syn::Ident::new(
        &format!(
            "__utf_rest_generated_{}",
            struct_type
                .segments
                .last()
                .unwrap()
                .ident
                .to_string()
                .to_lowercase()
        ),
        struct_type.span(),
    );

    let create_router_method = generate_create_rest_router(router, &module_name);
    let openapi_method = generate_get_openapi_spec(router);
    let param_structs = generate_param_structs(router);

    let module_code = quote! {
        mod #module_name {
            use super::*;
            use ::serde::{Serialize, Deserialize};

            #param_structs
        }
    };

    // Wrap methods in an impl block
    let method_code = quote! {
        impl #struct_type {
            #create_router_method

            #openapi_method
        }
    };

    (module_code, method_code)
}

/// Generates all REST-related methods for a router (legacy version for compatibility)
#[allow(dead_code)] // Part of incomplete OpenAPI feature
pub fn generate_rest_methods(router: &RouterDef) -> TokenStream {
    let (module_code, method_code) = generate_rest_methods_split(router);
    quote! {
        #module_code
        #method_code
    }
}

/// Generates the create_rest_router() method
fn generate_create_rest_router(router: &RouterDef, module_name: &syn::Ident) -> TokenStream {
    let routes = router
        .tools
        .iter()
        .map(|tool| generate_tool_route(tool, module_name));

    // Compute prefix precedence: rest_config.prefix > base_path > "/api"
    let prefix: String = router
        .metadata
        .rest_config
        .as_ref()
        .and_then(|c| c.prefix.as_ref())
        .cloned()
        .or_else(|| router.metadata.base_path.clone())
        .unwrap_or_else(|| "/api".to_string());

    quote! {
        /// Creates an axum::Router with routes for all tools, nested under configured prefix.
        ///
        /// This is an associated function that takes the application state as an Arc.
        /// Usage: `let app = MyStruct::create_rest_router(Arc::new(my_instance));`
        ///
        /// Users integrate this router into their web server however they need
        pub fn create_rest_router(state: ::std::sync::Arc<Self>) -> ::universal_tool_core::rest::Router {
            use ::universal_tool_core::rest::{Router, response::IntoResponse};

            // Inner API with all routes; state is provided by the outer router
            let api = Router::new()
                #( #routes )*;

            // Apply prefix via nesting, then attach state at the outer level
            Router::new()
                .nest(#prefix, api)
                .with_state(state)
        }
    }
}

/// Generates parameter structs for each tool
fn generate_param_structs(router: &RouterDef) -> TokenStream {
    router
        .tools
        .iter()
        .map(|tool| {
            let struct_name = get_params_struct_name(tool);

            // Only generate struct if there are body parameters
            let body_params: Vec<_> = tool
                .params
                .iter()
                .filter(|p| matches!(p.source, ParamSource::Body))
                .collect();

            if body_params.is_empty() {
                quote! {}
            } else {
                let fields = body_params.iter().map(|param| {
                    let name = &param.name;
                    let ty = &param.ty;
                    let doc = param
                        .metadata
                        .description
                        .as_deref()
                        .unwrap_or("")
                        .to_string();

                    quote! {
                        #[doc = #doc]
                        pub #name: #ty
                    }
                });

                quote! {
                    #[derive(Debug, Clone, Serialize, Deserialize)]
                    pub struct #struct_name {
                        #( #fields ),*
                    }
                }
            }
        })
        .collect()
}

/// Generates a route for a single tool
fn generate_tool_route(tool: &ToolDef, module_name: &syn::Ident) -> TokenStream {
    let method = determine_http_method(tool);
    let path = generate_route_path(tool);
    let _handler_name = get_handler_name(tool);

    // Generate the handler function
    let handler = generate_handler(tool, module_name);

    // Generate the route registration
    let route_method = match method {
        HttpMethod::Get => quote! { ::universal_tool_core::rest::routing::get },
        HttpMethod::Post => quote! { ::universal_tool_core::rest::routing::post },
        HttpMethod::Put => quote! { ::universal_tool_core::rest::routing::put },
        HttpMethod::Delete => quote! { ::universal_tool_core::rest::routing::delete },
        HttpMethod::Patch => quote! { ::universal_tool_core::rest::routing::patch },
    };

    quote! {
        .route(#path, #route_method(#handler))
    }
}

/// Generates the handler closure for a tool
fn generate_handler(tool: &ToolDef, module_name: &syn::Ident) -> TokenStream {
    let has_body_params = tool
        .params
        .iter()
        .any(|p| matches!(p.source, ParamSource::Body));

    // Generate parameter extraction
    let param_extractors = generate_param_extractors(tool);

    // Generate the handler body with inline error handling
    let error_handling = quote! {
        let status = match e.code {
            ::universal_tool_core::error::ErrorCode::BadRequest => ::universal_tool_core::rest::StatusCode::BAD_REQUEST,
            ::universal_tool_core::error::ErrorCode::InvalidArgument => ::universal_tool_core::rest::StatusCode::BAD_REQUEST,
            ::universal_tool_core::error::ErrorCode::NotFound => ::universal_tool_core::rest::StatusCode::NOT_FOUND,
            ::universal_tool_core::error::ErrorCode::PermissionDenied => ::universal_tool_core::rest::StatusCode::FORBIDDEN,
            ::universal_tool_core::error::ErrorCode::Internal => ::universal_tool_core::rest::StatusCode::INTERNAL_SERVER_ERROR,
            ::universal_tool_core::error::ErrorCode::Timeout => ::universal_tool_core::rest::StatusCode::REQUEST_TIMEOUT,
            ::universal_tool_core::error::ErrorCode::Conflict => ::universal_tool_core::rest::StatusCode::CONFLICT,
            ::universal_tool_core::error::ErrorCode::NetworkError => ::universal_tool_core::rest::StatusCode::SERVICE_UNAVAILABLE,
            ::universal_tool_core::error::ErrorCode::ExternalServiceError => ::universal_tool_core::rest::StatusCode::BAD_GATEWAY,
            ::universal_tool_core::error::ErrorCode::ExecutionFailed => ::universal_tool_core::rest::StatusCode::INTERNAL_SERVER_ERROR,
            ::universal_tool_core::error::ErrorCode::SerializationError => ::universal_tool_core::rest::StatusCode::BAD_REQUEST,
            ::universal_tool_core::error::ErrorCode::IoError => ::universal_tool_core::rest::StatusCode::INTERNAL_SERVER_ERROR,
        };
        (status, ::universal_tool_core::rest::Json(::serde_json::json!({
            "error": e.to_string(),
            "code": format!("{:?}", e.code),
        }))).into_response()
    };

    // Build the arguments vector for the method call
    let method_args_vec: Vec<TokenStream> = tool
        .params
        .iter()
        .map(|param| {
            let name = &param.name;
            match param.source {
                ParamSource::Body => quote! { params.#name },
                _ => quote! { #name },
            }
        })
        .collect();

    // Use the shared function to generate the method call with proper async/sync handling
    let method_call = crate::codegen::shared::generate_normalized_method_call(
        tool,
        quote! { state },
        method_args_vec,
    );

    if has_body_params {
        let params_struct = get_params_struct_name(tool);
        quote! {
            |::universal_tool_core::rest::State(state): ::universal_tool_core::rest::State<::std::sync::Arc<Self>>#param_extractors,
             ::universal_tool_core::rest::Json(params): ::universal_tool_core::rest::Json<#module_name::#params_struct>| async move {
                match #method_call {
                    Ok(result) => (::universal_tool_core::rest::StatusCode::OK, ::universal_tool_core::rest::Json(result)).into_response(),
                    Err(e) => { #error_handling },
                }
            }
        }
    } else {
        quote! {
            |::universal_tool_core::rest::State(state): ::universal_tool_core::rest::State<::std::sync::Arc<Self>>#param_extractors| async move {
                match #method_call {
                    Ok(result) => (::universal_tool_core::rest::StatusCode::OK, ::universal_tool_core::rest::Json(result)).into_response(),
                    Err(e) => { #error_handling },
                }
            }
        }
    }
}

/// Generates parameter extractors for non-body parameters
fn generate_param_extractors(tool: &ToolDef) -> TokenStream {
    let extractors = tool.params.iter()
        .filter(|p| !matches!(p.source, ParamSource::Body))
        .map(|param| {
            let name = &param.name;
            let ty = &param.ty;

            match param.source {
                ParamSource::Path => quote! { , ::universal_tool_core::rest::Path(#name): ::universal_tool_core::rest::Path<#ty> },
                ParamSource::Query => quote! { , ::universal_tool_core::rest::Query(#name): ::universal_tool_core::rest::Query<#ty> },
                _ => quote! {},
            }
        });

    quote! { #( #extractors )* }
}

/// Generates the get_openapi_spec() method
fn generate_get_openapi_spec(_router: &RouterDef) -> TokenStream {
    // TODO(3): Implement full OpenAPI generation when openapi feature is enabled
    // This would use utoipa macros to generate a proper OpenAPI spec with schemas
    // For now, return a placeholder that lets users know the feature is not enabled
    quote! {
        /// Returns OpenAPI documentation for all tools
        ///
        /// Note: Full OpenAPI generation requires the 'openapi' feature to be enabled:
        /// ```toml
        /// universal-tool-core = { version = "0.1", features = ["rest", "openapi"] }
        /// ```
        pub fn get_openapi_spec(&self) -> String {
            "OpenAPI generation requires the 'openapi' feature to be enabled".to_string()
        }
    }
}

/// Determines the HTTP method for a tool
fn determine_http_method(tool: &ToolDef) -> HttpMethod {
    // Check if REST config specifies a method
    if let Some(rest_config) = &tool.metadata.rest_config {
        return rest_config.method;
    }

    // Use smart defaults based on method name
    let name = tool.method_name.to_string();
    if name.starts_with("get") || name.starts_with("list") || name.starts_with("find") {
        HttpMethod::Get
    } else if name.starts_with("create") || name.starts_with("add") || name.starts_with("new") {
        HttpMethod::Post
    } else if name.starts_with("update") || name.starts_with("modify") || name.starts_with("set") {
        HttpMethod::Put
    } else if name.starts_with("delete") || name.starts_with("remove") {
        HttpMethod::Delete
    } else if name.starts_with("patch") {
        HttpMethod::Patch
    } else {
        // Default to POST for other operations
        HttpMethod::Post
    }
}

/// Generates the route path for a tool
fn generate_route_path(tool: &ToolDef) -> String {
    // Check if REST config specifies a path
    if let Some(rest_config) = &tool.metadata.rest_config
        && let Some(path) = &rest_config.path
    {
        return path.clone();
    }

    // Generate path based on tool name
    let base_path = format!("/{}", to_kebab_case(&tool.tool_name));

    // Add path parameters
    let mut path = base_path;
    for param in &tool.params {
        if matches!(param.source, ParamSource::Path) {
            path.push_str(&format!("/:{}", param.name));
        }
    }

    path
}

/// Gets the name for the params struct for a tool
fn get_params_struct_name(tool: &ToolDef) -> syn::Ident {
    let name = format!("{}Params", to_pascal_case(&tool.tool_name));
    syn::Ident::new(&name, tool.method_name.span())
}

/// Gets the handler function name for a tool
fn get_handler_name(tool: &ToolDef) -> syn::Ident {
    let name = format!("handle_rest_{}", tool.method_name);
    syn::Ident::new(&name, tool.method_name.span())
}

/// Generate OpenAPI schemas for parameter structs
#[allow(dead_code)] // Will be used when OpenAPI feature is completed
fn generate_openapi_schemas(router: &RouterDef) -> TokenStream {
    let schemas = router
        .tools
        .iter()
        .filter(|tool| {
            tool.params
                .iter()
                .any(|p| matches!(p.source, ParamSource::Body))
        })
        .map(|_tool| {
            quote! {
                // ToSchema is already derived above
            }
        });

    quote! { #( #schemas )* }
}

/// Generate OpenAPI path documentation
#[allow(dead_code)] // Will be used when OpenAPI feature is completed
fn generate_openapi_paths(router: &RouterDef) -> TokenStream {
    let paths = router.tools.iter().map(|tool| {
        let fn_name = syn::Ident::new(
            &format!("__openapi_path_{}", tool.method_name),
            tool.method_name.span()
        );
        let path = generate_route_path(tool);
        let method = determine_http_method(tool);
        let method_str = format!("{method:?}").to_lowercase();
        let description = &tool.metadata.description;

        // Determine request body
        let has_body = tool.params.iter().any(|p| matches!(p.source, ParamSource::Body));
        let request_body = if has_body {
            let struct_name = get_params_struct_name(tool);
            quote! { request_body = #struct_name, }
        } else {
            quote! {}
        };

        // Extract the success type from Result<T, E>
        let return_type = &tool.return_type;

        quote! {
            // OpenAPI paths are always generated when REST is enabled
            #[::utoipa::path(
                #method_str,
                path = #path,
                #request_body
                responses(
                    (status = 200, description = #description, body = #return_type),
                    (status = 400, description = "Bad request", body = ::universal_tool_core::error::ToolError),
                    (status = 500, description = "Internal server error", body = ::universal_tool_core::error::ToolError)
                )
            )]
            async fn #fn_name() {}
        }
    });

    quote! { #( #paths )* }
}