rs-utcp 0.3.2

Rust implementation of the Universal Tool Calling Protocol (UTCP).
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
// Streamable HTTP Transport (for chunked/streaming HTTP responses)
use anyhow::{anyhow, Result};
use async_trait::async_trait;
use futures::StreamExt;
use reqwest::{header, Client};
use serde_json::{de::Deserializer, Value};
use std::collections::HashMap;
use tokio::sync::mpsc;

use crate::auth::AuthConfig;
use crate::providers::base::Provider;
use crate::providers::http_stream::StreamableHttpProvider;
use crate::tools::Tool;
use crate::transports::{
    stream::{boxed_channel_stream, StreamResult},
    ClientTransport,
};

/// Transport for HTTP endpoints that stream newline-delimited JSON or chunked bodies.
pub struct StreamableHttpTransport {
    client: Client,
}

impl StreamableHttpTransport {
    /// Create a streaming HTTP transport with a default client.
    pub fn new() -> Self {
        Self {
            client: Client::new(),
        }
    }

    /// Attach authentication headers or query params to the request builder.
    fn apply_auth(
        &self,
        builder: reqwest::RequestBuilder,
        auth: &AuthConfig,
    ) -> Result<reqwest::RequestBuilder> {
        match auth {
            AuthConfig::ApiKey(api_key) => {
                let location = api_key.location.to_ascii_lowercase();
                match location.as_str() {
                    "header" => Ok(builder.header(&api_key.var_name, &api_key.api_key)),
                    "query" => {
                        Ok(builder.query(&[(api_key.var_name.clone(), api_key.api_key.clone())]))
                    }
                    "cookie" => {
                        let cookie_value = format!("{}={}", api_key.var_name, api_key.api_key);
                        Ok(builder.header(header::COOKIE, cookie_value))
                    }
                    other => Err(anyhow!("Unsupported API key location: {}", other)),
                }
            }
            AuthConfig::Basic(basic) => {
                Ok(builder.basic_auth(&basic.username, Some(&basic.password)))
            }
            AuthConfig::OAuth2(_) => Err(anyhow!(
                "OAuth2 auth is not yet supported by the HTTP stream transport"
            )),
        }
    }
}

#[async_trait]
impl ClientTransport for StreamableHttpTransport {
    async fn register_tool_provider(&self, _prov: &dyn Provider) -> Result<Vec<Tool>> {
        // Streamable HTTP often shares the same discovery endpoint as HTTP providers.
        Ok(vec![])
    }

    async fn deregister_tool_provider(&self, _prov: &dyn Provider) -> Result<()> {
        Ok(())
    }

    async fn call_tool(
        &self,
        tool_name: &str,
        args: HashMap<String, Value>,
        prov: &dyn Provider,
    ) -> Result<Value> {
        // Fallback: perform a standard request and aggregate the full response.
        let http_prov = prov
            .as_any()
            .downcast_ref::<StreamableHttpProvider>()
            .ok_or_else(|| anyhow!("Provider is not a StreamableHttpProvider"))?;

        let call_name = tool_name
            .strip_prefix(&format!("{}.", http_prov.base.name))
            .unwrap_or(tool_name);
        let url = format!("{}/{}", http_prov.url.trim_end_matches('/'), call_name);
        let method_upper = http_prov.http_method.to_uppercase();
        let mut request_builder = match method_upper.as_str() {
            "GET" => self.client.get(&url).query(&args),
            "POST" => self.client.post(&url).json(&args),
            "PUT" => self.client.put(&url).json(&args),
            "DELETE" => self.client.delete(&url).json(&args),
            "PATCH" => self.client.patch(&url).json(&args),
            other => return Err(anyhow!("Unsupported HTTP method: {}", other)),
        };

        if let Some(headers) = &http_prov.headers {
            for (k, v) in headers {
                request_builder = request_builder.header(k, v);
            }
        }

        if let Some(auth) = &http_prov.base.auth {
            request_builder = self.apply_auth(request_builder, auth)?;
        }

        let response = request_builder.send().await?;

        if !response.status().is_success() {
            return Err(anyhow!(
                "HTTP request failed with status: {}",
                response.status()
            ));
        }

        let value: Value = response.json().await?;
        Ok(value)
    }

    async fn call_tool_stream(
        &self,
        tool_name: &str,
        args: HashMap<String, Value>,
        prov: &dyn Provider,
    ) -> Result<Box<dyn StreamResult>> {
        let http_prov = prov
            .as_any()
            .downcast_ref::<StreamableHttpProvider>()
            .ok_or_else(|| anyhow!("Provider is not a StreamableHttpProvider"))?;

        let call_name = tool_name
            .strip_prefix(&format!("{}.", http_prov.base.name))
            .unwrap_or(tool_name);
        let url = format!("{}/{}", http_prov.url.trim_end_matches('/'), call_name);
        let method_upper = http_prov.http_method.to_uppercase();
        let mut req = match method_upper.as_str() {
            "GET" => self.client.get(url).query(&args),
            "POST" => self.client.post(url).json(&args),
            "PUT" => self.client.put(url).json(&args),
            "DELETE" => self.client.delete(url).json(&args),
            "PATCH" => self.client.patch(url).json(&args),
            other => return Err(anyhow!("Unsupported HTTP method: {}", other)),
        };

        if let Some(headers) = &http_prov.headers {
            for (k, v) in headers {
                req = req.header(k, v);
            }
        }

        if let Some(auth) = &http_prov.base.auth {
            req = self.apply_auth(req, auth)?;
        }

        let response = req.send().await?;

        if !response.status().is_success() {
            return Err(anyhow!(
                "HTTP request failed with status: {}",
                response.status()
            ));
        }

        // Stream response chunks and parse them as JSON values.
        let mut byte_stream = response.bytes_stream();
        let (tx, rx) = mpsc::channel(16);

        tokio::spawn(async move {
            let mut buffer: Vec<u8> = Vec::new();
            while let Some(chunk_result) = byte_stream.next().await {
                match chunk_result {
                    Ok(bytes) => {
                        buffer.extend_from_slice(&bytes);
                        let deserializer = Deserializer::from_slice(&buffer);
                        let mut stream = deserializer.into_iter::<Value>();
                        let mut offset = 0usize;

                        loop {
                            match stream.next() {
                                Some(Ok(value)) => {
                                    offset = stream.byte_offset();
                                    if tx.send(Ok(value)).await.is_err() {
                                        return;
                                    }
                                }
                                Some(Err(e)) => {
                                    if e.is_eof() {
                                        break;
                                    }
                                    let _ = tx
                                        .send(Err(anyhow!(
                                            "Failed to parse JSON from stream: {}",
                                            e
                                        )))
                                        .await;
                                    return;
                                }
                                None => break,
                            }
                        }

                        if offset > 0 && offset <= buffer.len() {
                            buffer.drain(0..offset);
                        }
                    }
                    Err(err) => {
                        let _ = tx
                            .send(Err(anyhow!("Error reading bytes from stream: {}", err)))
                            .await;
                        return;
                    }
                }
            }

            if !buffer.is_empty() {
                let _ = tx
                    .send(Err(anyhow!("Stream ended with incomplete JSON frame")))
                    .await;
            }
        });

        Ok(boxed_channel_stream(rx, None))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::auth::{ApiKeyAuth, AuthType, BasicAuth, OAuth2Auth};
    use crate::providers::base::{BaseProvider, ProviderType};
    use crate::providers::http_stream::StreamableHttpProvider;
    use axum::{body::Body, extract::Json, http::Response, routing::post, Router};
    use bytes::Bytes;
    use serde_json::json;
    use std::net::TcpListener;

    #[test]
    fn apply_auth_sets_expected_headers_and_query() {
        let transport = StreamableHttpTransport::new();

        let header_auth = AuthConfig::ApiKey(ApiKeyAuth {
            auth_type: AuthType::ApiKey,
            api_key: "secret".to_string(),
            var_name: "X-Stream-Key".to_string(),
            location: "header".to_string(),
        });
        let request = transport
            .apply_auth(
                reqwest::Client::new().get("http://example.com"),
                &header_auth,
            )
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(request.headers().get("X-Stream-Key").unwrap(), "secret");

        let query_auth = AuthConfig::ApiKey(ApiKeyAuth {
            auth_type: AuthType::ApiKey,
            api_key: "abc".to_string(),
            var_name: "token".to_string(),
            location: "query".to_string(),
        });
        let request = transport
            .apply_auth(
                reqwest::Client::new().get("http://example.com"),
                &query_auth,
            )
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(request.url().query(), Some("token=abc"));

        let basic_auth = AuthConfig::Basic(BasicAuth {
            auth_type: AuthType::Basic,
            username: "user".to_string(),
            password: "pass".to_string(),
        });
        let request = transport
            .apply_auth(
                reqwest::Client::new().get("http://example.com"),
                &basic_auth,
            )
            .unwrap()
            .build()
            .unwrap();
        assert_eq!(
            request.headers().get(header::AUTHORIZATION).unwrap(),
            "Basic dXNlcjpwYXNz"
        );
    }

    #[test]
    fn apply_auth_rejects_oauth2() {
        let transport = StreamableHttpTransport::new();
        let auth = AuthConfig::OAuth2(OAuth2Auth {
            auth_type: AuthType::OAuth2,
            token_url: "https://auth.example.com/token".to_string(),
            client_id: "client".to_string(),
            client_secret: "secret".to_string(),
            scope: None,
        });

        let err = transport
            .apply_auth(reqwest::Client::new().get("http://example.com"), &auth)
            .unwrap_err();
        assert!(err.to_string().contains("OAuth2 auth is not yet supported"));
    }

    #[tokio::test]
    async fn register_call_and_stream_http_stream_transport() {
        async fn aggregate(Json(payload): Json<Value>) -> Json<Value> {
            Json(json!({ "received": payload }))
        }

        async fn stream(Json(_payload): Json<Value>) -> Response<Body> {
            let chunks: Vec<Result<Bytes, std::convert::Infallible>> = vec![
                Ok(Bytes::from_static(br#"{"chunk":"#)),
                Ok(Bytes::from_static(br#"1}"#)),
                Ok(Bytes::from_static(b"\n{\"chunk\":2}")),
            ];
            Response::builder()
                .header("content-type", "application/json")
                .body(Body::wrap_stream(tokio_stream::iter(chunks)))
                .unwrap()
        }

        let app = Router::new()
            .route("/aggregate", post(aggregate))
            .route("/stream", post(stream));
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::Server::from_tcp(listener)
                .unwrap()
                .serve(app.into_make_service())
                .await
                .unwrap();
        });

        let base_url = format!("http://{}", addr);
        let provider = StreamableHttpProvider {
            base: BaseProvider {
                name: "http-stream".to_string(),
                provider_type: ProviderType::HttpStream,
                auth: None,
                allowed_communication_protocols: None,
            },
            url: base_url.clone(),
            http_method: "POST".to_string(),
            headers: None,
        };

        let transport = StreamableHttpTransport::new();
        let tools = transport
            .register_tool_provider(&provider)
            .await
            .expect("register");
        assert!(tools.is_empty());

        let mut args = HashMap::new();
        args.insert("payload".into(), Value::String("data".into()));

        let aggregate_value = transport
            .call_tool("aggregate", args.clone(), &provider)
            .await
            .expect("call tool");
        assert_eq!(aggregate_value, json!({ "received": json!(args) }));

        let mut stream = transport
            .call_tool_stream("stream", args, &provider)
            .await
            .expect("call tool stream");
        let mut items = Vec::new();
        while let Some(item) = stream.next().await.unwrap() {
            items.push(item);
            if items.len() == 2 {
                break;
            }
        }
        stream.close().await.unwrap();

        assert_eq!(items, vec![json!({"chunk": 1}), json!({"chunk": 2})]);
    }

    #[tokio::test]
    async fn http_stream_strips_provider_prefix() {
        async fn echo(Json(_payload): Json<Value>) -> Json<Value> {
            Json(json!({"ok": true}))
        }

        let app = Router::new().route("/echo", post(echo));
        let listener = TcpListener::bind("127.0.0.1:0").unwrap();
        let addr = listener.local_addr().unwrap();
        tokio::spawn(async move {
            axum::Server::from_tcp(listener)
                .unwrap()
                .serve(app.into_make_service())
                .await
                .unwrap();
        });

        let base_url = format!("http://{}", addr);
        let provider = StreamableHttpProvider {
            base: BaseProvider {
                name: "http-stream".to_string(),
                provider_type: ProviderType::HttpStream,
                auth: None,
                allowed_communication_protocols: None,
            },
            url: base_url.clone(),
            http_method: "POST".to_string(),
            headers: None,
        };

        let transport = StreamableHttpTransport::new();
        let value = transport
            .call_tool("http-stream.echo", HashMap::new(), &provider)
            .await
            .expect("call tool");
        assert_eq!(value, json!({"ok": true}));
    }
}