agent-tools-interface 0.7.10

Agent Tools Interface — secure CLI for AI agent tool execution
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
use ati::core::http::{execute_tool, validate_headers, HttpError};
use ati::core::keyring::Keyring;
use ati::core::manifest::{AuthType, HttpMethod, Provider, Tool};
use serde_json::{json, Value};
use std::collections::HashMap;
use wiremock::matchers::{body_string_contains, header, method, path, query_param};
use wiremock::{Mock, MockServer, ResponseTemplate};

#[test]
fn test_denied_header_authorization() {
    let mut headers = HashMap::new();
    headers.insert("Authorization".to_string(), "Bearer evil".to_string());
    let err = validate_headers(&headers, None).unwrap_err();
    assert!(matches!(err, HttpError::DeniedHeader(_)));
}

#[test]
fn test_denied_header_case_insensitive() {
    let mut headers = HashMap::new();
    headers.insert("AUTHORIZATION".to_string(), "Bearer evil".to_string());
    let err = validate_headers(&headers, None).unwrap_err();
    assert!(matches!(err, HttpError::DeniedHeader(_)));
}

#[test]
fn test_denied_header_host() {
    let mut headers = HashMap::new();
    headers.insert("Host".to_string(), "evil.com".to_string());
    assert!(validate_headers(&headers, None).is_err());
}

#[test]
fn test_denied_header_cookie() {
    let mut headers = HashMap::new();
    headers.insert("Cookie".to_string(), "session=evil".to_string());
    assert!(validate_headers(&headers, None).is_err());
}

#[test]
fn test_denied_header_set_cookie() {
    let mut headers = HashMap::new();
    headers.insert("Set-Cookie".to_string(), "session=evil".to_string());
    assert!(validate_headers(&headers, None).is_err());
}

#[test]
fn test_denied_header_content_type() {
    let mut headers = HashMap::new();
    headers.insert("Content-Type".to_string(), "text/html".to_string());
    assert!(validate_headers(&headers, None).is_err());
}

#[test]
fn test_denied_header_transfer_encoding() {
    let mut headers = HashMap::new();
    headers.insert("Transfer-Encoding".to_string(), "chunked".to_string());
    assert!(validate_headers(&headers, None).is_err());
}

#[test]
fn test_denied_header_proxy_authorization() {
    let mut headers = HashMap::new();
    headers.insert("Proxy-Authorization".to_string(), "Basic evil".to_string());
    assert!(validate_headers(&headers, None).is_err());
}

#[test]
fn test_denied_header_x_forwarded_for() {
    let mut headers = HashMap::new();
    headers.insert("X-Forwarded-For".to_string(), "1.2.3.4".to_string());
    assert!(validate_headers(&headers, None).is_err());
}

#[test]
fn test_allowed_header_passes() {
    let mut headers = HashMap::new();
    headers.insert("X-Custom-Header".to_string(), "safe-value".to_string());
    assert!(validate_headers(&headers, None).is_ok());
}

#[test]
fn test_allowed_multiple_headers_pass() {
    let mut headers = HashMap::new();
    headers.insert("X-Custom-Header".to_string(), "safe-value".to_string());
    headers.insert("Accept-Language".to_string(), "en-US".to_string());
    assert!(validate_headers(&headers, None).is_ok());
}

#[test]
fn test_empty_headers_pass() {
    let headers = HashMap::new();
    assert!(validate_headers(&headers, None).is_ok());
}

#[test]
fn test_denied_provider_auth_header() {
    let mut headers = HashMap::new();
    headers.insert("X-Api-Key".to_string(), "evil-key".to_string());
    assert!(validate_headers(&headers, Some("X-Api-Key")).is_err());
}

#[test]
fn test_denied_provider_auth_header_case_insensitive() {
    let mut headers = HashMap::new();
    headers.insert("x-api-key".to_string(), "evil-key".to_string());
    assert!(validate_headers(&headers, Some("X-Api-Key")).is_err());
}

#[test]
fn test_provider_auth_header_not_in_headers() {
    let mut headers = HashMap::new();
    headers.insert("X-Custom-Header".to_string(), "safe-value".to_string());
    assert!(validate_headers(&headers, Some("X-Api-Key")).is_ok());
}

// ---------------------------------------------------------------------------
// Helper: create a Provider pointing at a wiremock server
// ---------------------------------------------------------------------------

fn mock_provider(base_url: &str) -> Provider {
    Provider {
        name: "test".into(),
        description: String::new(),
        base_url: base_url.into(),
        auth_type: AuthType::None,
        auth_key_name: None,
        auth_header_name: None,
        auth_value_prefix: None,
        auth_query_name: None,
        auth_secret_name: None,
        handler: String::new(),
        internal: false,
        category: None,
        mcp_transport: None,
        mcp_command: None,
        mcp_args: vec![],
        mcp_env: HashMap::new(),
        mcp_url: None,
        cli_command: None,
        cli_default_args: vec![],
        cli_env: HashMap::new(),
        cli_timeout_secs: None,
        cli_output_args: Vec::new(),
        cli_output_positional: HashMap::new(),
        upload_destinations: HashMap::new(),
        upload_default_destination: None,
        openapi_spec: None,
        openapi_include_tags: vec![],
        openapi_exclude_tags: vec![],
        openapi_include_operations: vec![],
        openapi_exclude_operations: vec![],
        openapi_max_operations: None,
        openapi_overrides: HashMap::new(),
        oauth2_token_url: None,
        oauth2_basic_auth: false,
        extra_headers: HashMap::new(),
        auth_generator: None,
        skills: vec![],
    }
}

fn mock_tool(endpoint: &str, method: HttpMethod, input_schema: Value) -> Tool {
    Tool {
        name: "test:op".into(),
        description: String::new(),
        endpoint: endpoint.into(),
        method,
        scope: None,
        input_schema: Some(input_schema),
        response: None,
        tags: vec![],
        hint: None,
        examples: vec![],
    }
}

// ---------------------------------------------------------------------------
// Test: array query param with multi format (repeated keys)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_array_query_param_multi() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/pets"))
        .and(query_param("status", "available"))
        .and(query_param("status", "pending"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
        .mount(&server)
        .await;

    let provider = mock_provider(&server.uri());
    let schema = json!({
        "type": "object",
        "properties": {
            "status": {
                "type": "array",
                "items": { "type": "string" },
                "x-ati-param-location": "query",
                "x-ati-collection-format": "multi"
            }
        }
    });
    let tool = mock_tool("/pets", HttpMethod::Get, schema);
    let keyring = Keyring::empty();

    let mut args = HashMap::new();
    args.insert("status".into(), json!(["available", "pending"]));

    let result = execute_tool(&provider, &tool, &args, &keyring)
        .await
        .unwrap();
    assert_eq!(result["ok"], true);
}

// ---------------------------------------------------------------------------
// Test: array query param with csv format (comma-separated)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_array_query_param_csv() {
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/items"))
        .and(query_param("ids", "1,2,3"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"ok": true})))
        .mount(&server)
        .await;

    let provider = mock_provider(&server.uri());
    let schema = json!({
        "type": "object",
        "properties": {
            "ids": {
                "type": "array",
                "items": { "type": "integer" },
                "x-ati-param-location": "query",
                "x-ati-collection-format": "csv"
            }
        }
    });
    let tool = mock_tool("/items", HttpMethod::Get, schema);
    let keyring = Keyring::empty();

    let mut args = HashMap::new();
    args.insert("ids".into(), json!([1, 2, 3]));

    let result = execute_tool(&provider, &tool, &args, &keyring)
        .await
        .unwrap();
    assert_eq!(result["ok"], true);
}

// ---------------------------------------------------------------------------
// Test: form-urlencoded body encoding
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_form_urlencoded_body() {
    let server = MockServer::start().await;

    Mock::given(method("POST"))
        .and(path("/token"))
        .and(header("content-type", "application/x-www-form-urlencoded"))
        .and(body_string_contains("grant_type=client_credentials"))
        .and(body_string_contains("client_id=myapp"))
        .respond_with(ResponseTemplate::new(200).set_body_json(json!({"access_token": "abc123"})))
        .mount(&server)
        .await;

    let provider = mock_provider(&server.uri());
    let schema = json!({
        "type": "object",
        "x-ati-body-encoding": "form",
        "properties": {
            "grant_type": {
                "type": "string",
                "x-ati-param-location": "body"
            },
            "client_id": {
                "type": "string",
                "x-ati-param-location": "body"
            }
        }
    });
    let tool = mock_tool("/token", HttpMethod::Post, schema);
    let keyring = Keyring::empty();

    let mut args = HashMap::new();
    args.insert("grant_type".into(), json!("client_credentials"));
    args.insert("client_id".into(), json!("myapp"));

    let result = execute_tool(&provider, &tool, &args, &keyring)
        .await
        .unwrap();
    assert_eq!(result["access_token"], "abc123");
}

// ---------------------------------------------------------------------------
// Issue #81 — upstream 404 "no records" classification and structured errors
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_upstream_404_no_records_returns_no_records_variant() {
    // PDL-style 404 body — should map to HttpError::NoRecordsFound, not ApiError.
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/person/enrich"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "status": 404,
            "error": {
                "type": "not_found",
                "message": "No records were found matching your request"
            }
        })))
        .mount(&server)
        .await;

    let provider = mock_provider(&server.uri());
    let tool = mock_tool("/person/enrich", HttpMethod::Get, json!({}));
    let keyring = Keyring::empty();

    let err = execute_tool(&provider, &tool, &HashMap::new(), &keyring)
        .await
        .unwrap_err();

    assert!(
        matches!(err, HttpError::NoRecordsFound { status: 404 }),
        "expected NoRecordsFound variant, got {err:?}"
    );
}

#[tokio::test]
async fn test_upstream_404_message_only_still_detected_as_no_records() {
    // Middesk-style — no error.type field, just a plain message.
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/businesses"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "message": "No companies were found matching your request"
        })))
        .mount(&server)
        .await;

    let provider = mock_provider(&server.uri());
    let tool = mock_tool("/businesses", HttpMethod::Get, json!({}));
    let keyring = Keyring::empty();

    let err = execute_tool(&provider, &tool, &HashMap::new(), &keyring)
        .await
        .unwrap_err();

    assert!(
        matches!(err, HttpError::NoRecordsFound { status: 404 }),
        "expected NoRecordsFound variant, got {err:?}"
    );
}

#[tokio::test]
async fn test_upstream_404_unrelated_body_stays_api_error() {
    // A 404 that is NOT a "no records" shape should stay as ApiError so the
    // proxy treats it like any other upstream failure.
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/endpoint"))
        .respond_with(ResponseTemplate::new(404).set_body_json(json!({
            "error": { "type": "invalid_route", "message": "This endpoint was removed" }
        })))
        .mount(&server)
        .await;

    let provider = mock_provider(&server.uri());
    let tool = mock_tool("/endpoint", HttpMethod::Get, json!({}));
    let keyring = Keyring::empty();

    let err = execute_tool(&provider, &tool, &HashMap::new(), &keyring)
        .await
        .unwrap_err();

    match err {
        HttpError::ApiError {
            status,
            error_type,
            error_message,
            ..
        } => {
            assert_eq!(status, 404);
            assert_eq!(error_type.as_deref(), Some("invalid_route"));
            assert_eq!(error_message.as_deref(), Some("This endpoint was removed"));
        }
        other => panic!("expected ApiError, got {other:?}"),
    }
}

#[tokio::test]
async fn test_upstream_402_insufficient_credits_carries_structured_fields() {
    // xAI-style 402 — flat body with error + message strings.
    let server = MockServer::start().await;

    Mock::given(method("GET"))
        .and(path("/v1/quote"))
        .respond_with(ResponseTemplate::new(402).set_body_json(json!({
            "error": "Insufficient credits",
            "message": "Your current balance is $0.01"
        })))
        .mount(&server)
        .await;

    let provider = mock_provider(&server.uri());
    let tool = mock_tool("/v1/quote", HttpMethod::Get, json!({}));
    let keyring = Keyring::empty();

    let err = execute_tool(&provider, &tool, &HashMap::new(), &keyring)
        .await
        .unwrap_err();

    match err {
        HttpError::ApiError {
            status,
            error_message,
            ..
        } => {
            assert_eq!(status, 402);
            // Flat shape: `error` is used as the message when no nested message exists.
            assert_eq!(error_message.as_deref(), Some("Insufficient credits"));
        }
        other => panic!("expected ApiError, got {other:?}"),
    }
}