composio-sdk 0.3.0

Minimal Rust SDK for Composio Tool Router REST API
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
# Comparação: custom_tools.py (Python) → Rust


## 📊 Status Atual


**Python (`custom_tools.py`)**: ✅ Completo
**Rust**: ⚠️ **Parcialmente implementado** - Faltam componentes principais

## 🔍 Análise do Arquivo Python


### Componentes Principais


1. **Protocols (Type Hints)**
   - `ExecuteRequestFn` - Função para executar requests proxy
   - `CustomToolProtocol` - Tool sem autenticação
   - `CustomToolWithProxyProtocol` - Tool com autenticação e proxy

2. **CustomTool Class**
   - Wrapper para funções customizadas
   - Parse automático de parâmetros via `inspect`
   - Geração de schema a partir de Pydantic models
   - Suporte para tools com/sem toolkit
   - Execução com autenticação automática

3. **CustomTools Class**
   - Registry de custom tools
   - Decorator `@register` para registrar tools
   - Método `execute()` para executar tools

## 📋 Mapeamento Python → Rust


| Python | Rust (Atual) | Rust (Necessário) | Status |
|--------|--------------|-------------------|--------|
| `ExecuteRequestFn` | - | `ExecuteRequestFn` trait | ❌ Falta |
| `CustomToolProtocol` | - | `CustomToolFn` trait | ❌ Falta |
| `CustomToolWithProxyProtocol` | - | `CustomToolWithProxyFn` trait | ❌ Falta |
| `CustomTool` | `CustomToolDefinition` | `CustomTool` struct completo | ⚠️ Parcial |
| `CustomTools` | - | `CustomToolsRegistry` | ❌ Falta |
| `register()` decorator | - | Macro ou builder pattern | ❌ Falta |

## 🎯 O Que Já Existe no Rust


### `CustomToolDefinition` (src/models/tools.rs)

```rust
pub struct CustomToolDefinition {
    pub slug: String,
    pub name: String,
    pub description: String,
    pub input_schema: serde_json::Value,
    pub output_schema: Option<serde_json::Value>,
    pub toolkit: Option<String>,
    pub requires_auth: bool,
}
```

**Limitações**:
- Apenas definição estática
- Não tem lógica de execução
- Não tem registry
- Não tem integração com client

### `CustomToolExecutionRequest` (src/models/tools.rs)

```rust
pub struct CustomToolExecutionRequest {
    pub slug: String,
    pub arguments: HashMap<String, serde_json::Value>,
    pub user_id: Option<String>,
    pub connected_account_id: Option<String>,
}
```

**Limitações**:
- Apenas estrutura de request
- Não tem lógica de execução

## 🚧 O Que Precisa Ser Implementado


### 1. Traits para Custom Tools


```rust
/// Função de execução de proxy request
pub trait ExecuteRequestFn: Send + Sync {
    fn execute(
        &self,
        endpoint: &str,
        method: &str,
        body: Option<serde_json::Value>,
        connected_account_id: Option<&str>,
        parameters: Option<Vec<ProxyParameter>>,
    ) -> Result<ToolProxyResponse, ComposioError>;
}

/// Custom tool sem autenticação
pub trait CustomToolFn: Send + Sync {
    fn execute(&self, request: serde_json::Value) -> Result<serde_json::Value, ComposioError>;
}

/// Custom tool com autenticação e proxy
pub trait CustomToolWithProxyFn: Send + Sync {
    fn execute(
        &self,
        request: serde_json::Value,
        execute_request: &dyn ExecuteRequestFn,
        auth_credentials: &HashMap<String, serde_json::Value>,
    ) -> Result<serde_json::Value, ComposioError>;
}
```

### 2. CustomTool Struct Completo


```rust
pub struct CustomTool {
    pub slug: String,
    pub name: String,
    pub description: String,
    pub toolkit: Option<String>,
    pub input_schema: serde_json::Value,
    pub output_schema: Option<serde_json::Value>,
    pub requires_auth: bool,
    
    // Função de execução (Box para trait object)
    executor: Box<dyn CustomToolExecutor>,
    
    // Client para operações
    client: Arc<ComposioClient>,
}

impl CustomTool {
    pub fn new_simple<F>(
        name: &str,
        description: &str,
        input_schema: serde_json::Value,
        executor: F,
        client: Arc<ComposioClient>,
    ) -> Self
    where
        F: Fn(serde_json::Value) -> Result<serde_json::Value, ComposioError> + Send + Sync + 'static
    {
        // Implementação
    }
    
    pub fn new_with_auth<F>(
        name: &str,
        description: &str,
        toolkit: &str,
        input_schema: serde_json::Value,
        executor: F,
        client: Arc<ComposioClient>,
    ) -> Self
    where
        F: Fn(serde_json::Value, &dyn ExecuteRequestFn, &HashMap<String, serde_json::Value>) 
           -> Result<serde_json::Value, ComposioError> + Send + Sync + 'static
    {
        // Implementação
    }
    
    pub async fn execute(
        &self,
        arguments: HashMap<String, serde_json::Value>,
        user_id: Option<&str>,
    ) -> Result<serde_json::Value, ComposioError> {
        // Implementação
    }
    
    fn get_auth_credentials(&self, user_id: &str) -> Result<HashMap<String, serde_json::Value>, ComposioError> {
        // Buscar connected account mais recente
    }
    
    pub fn to_tool_info(&self) -> Tool {
        // Converter para Tool (formato da API)
    }
}
```

### 3. CustomToolsRegistry


```rust
pub struct CustomToolsRegistry {
    tools: HashMap<String, Arc<CustomTool>>,
    client: Arc<ComposioClient>,
}

impl CustomToolsRegistry {
    pub fn new(client: Arc<ComposioClient>) -> Self {
        Self {
            tools: HashMap::new(),
            client,
        }
    }
    
    pub fn register_simple<F>(
        &mut self,
        name: &str,
        description: &str,
        input_schema: serde_json::Value,
        executor: F,
    ) -> Arc<CustomTool>
    where
        F: Fn(serde_json::Value) -> Result<serde_json::Value, ComposioError> + Send + Sync + 'static
    {
        let tool = Arc::new(CustomTool::new_simple(
            name,
            description,
            input_schema,
            executor,
            self.client.clone(),
        ));
        
        self.tools.insert(tool.slug.clone(), tool.clone());
        tool
    }
    
    pub fn register_with_auth<F>(
        &mut self,
        name: &str,
        description: &str,
        toolkit: &str,
        input_schema: serde_json::Value,
        executor: F,
    ) -> Arc<CustomTool>
    where
        F: Fn(serde_json::Value, &dyn ExecuteRequestFn, &HashMap<String, serde_json::Value>) 
           -> Result<serde_json::Value, ComposioError> + Send + Sync + 'static
    {
        let tool = Arc::new(CustomTool::new_with_auth(
            name,
            description,
            toolkit,
            input_schema,
            executor,
            self.client.clone(),
        ));
        
        self.tools.insert(tool.slug.clone(), tool.clone());
        tool
    }
    
    pub fn get(&self, slug: &str) -> Option<Arc<CustomTool>> {
        self.tools.get(slug).cloned()
    }
    
    pub async fn execute(
        &self,
        slug: &str,
        arguments: HashMap<String, serde_json::Value>,
        user_id: Option<&str>,
    ) -> Result<serde_json::Value, ComposioError> {
        let tool = self.get(slug)
            .ok_or_else(|| ComposioError::NotFound(format!("Custom tool {} not found", slug)))?;
        
        tool.execute(arguments, user_id).await
    }
    
    pub fn list(&self) -> Vec<Arc<CustomTool>> {
        self.tools.values().cloned().collect()
    }
}
```

## 🔄 Diferenças de Abordagem


### Python: Decorators + Inspection

```python
@composio.tools.register(toolkit="github")
def my_tool(request: MyRequest) -> MyResponse:
    """Tool description"""
    # Implementation
```

### Rust: Builder Pattern + Closures

```rust
registry.register_simple(
    "my_tool",
    "Tool description",
    input_schema,
    |request| {
        // Implementation
        Ok(response)
    }
);
```

**Por que essa diferença?**
- Python usa decorators e reflexão em runtime
- Rust não tem reflexão, então usamos closures e builders
- Rust requer tipos explícitos (não pode inferir schema automaticamente)

## 📝 Exemplo de Uso (Rust)


### Tool Simples (Sem Autenticação)

```rust
use composio::CustomToolsRegistry;
use serde_json::json;

let mut registry = CustomToolsRegistry::new(client.clone());

// Registrar tool
registry.register_simple(
    "calculate_sum",
    "Calculate the sum of two numbers",
    json!({
        "type": "object",
        "properties": {
            "a": {"type": "number"},
            "b": {"type": "number"}
        },
        "required": ["a", "b"]
    }),
    |request| {
        let a = request["a"].as_f64().unwrap();
        let b = request["b"].as_f64().unwrap();
        Ok(json!({"result": a + b}))
    }
);

// Executar tool
let result = registry.execute(
    "CALCULATE_SUM",
    HashMap::from([
        ("a".to_string(), json!(5)),
        ("b".to_string(), json!(3)),
    ]),
    None,
).await?;
```

### Tool com Autenticação

```rust
registry.register_with_auth(
    "create_custom_issue",
    "Create a custom GitHub issue",
    "github",
    json!({
        "type": "object",
        "properties": {
            "title": {"type": "string"},
            "body": {"type": "string"}
        },
        "required": ["title"]
    }),
    |request, execute_request, auth_credentials| {
        // Usar execute_request para fazer chamadas autenticadas
        let response = execute_request.execute(
            "/repos/owner/repo/issues",
            "POST",
            Some(request),
            None,
            None,
        )?;
        
        Ok(response.data)
    }
);
```

## 🎯 Plano de Implementação


### Fase 1: Estruturas Base ✅

- [x] `CustomToolDefinition` (já existe)
- [x] `CustomToolExecutionRequest` (já existe)

### Fase 2: Traits e Executors ❌

- [ ] `ExecuteRequestFn` trait
- [ ] `CustomToolExecutor` trait (unificado)
- [ ] Implementações de executor

### Fase 3: CustomTool Completo ❌

- [ ] Struct `CustomTool` com executor
- [ ] Método `execute()` com autenticação
- [ ] Método `get_auth_credentials()`
- [ ] Conversão para `Tool`

### Fase 4: Registry ❌

- [ ] Struct `CustomToolsRegistry`
- [ ] Métodos `register_simple()` e `register_with_auth()`
- [ ] Método `execute()`
- [ ] Método `list()`

### Fase 5: Integração ❌

- [ ] Integrar com `ComposioClient`
- [ ] Adicionar ao `Session`
- [ ] Testes unitários
- [ ] Exemplos de uso

## 💡 Desafios Específicos do Rust


1. **Sem Reflexão**: Não podemos inferir schemas automaticamente
   - Solução: Usuário fornece schema JSON explicitamente

2. **Trait Objects**: Precisamos de `Box<dyn Trait>` para armazenar closures
   - Solução: Usar trait objects com `Send + Sync`

3. **Lifetimes**: Closures podem capturar referências
   - Solução: Usar `'static` e `Arc` para compartilhar dados

4. **Async**: Executores podem ser async
   - Solução: Usar `async_trait` ou `Box<dyn Future>`

## 🚀 Próximos Passos


1. **Criar arquivo `src/models/custom_tools.rs`**
2. **Implementar traits base**
3. **Implementar `CustomTool` struct**
4. **Implementar `CustomToolsRegistry`**
5. **Adicionar testes**
6. **Criar exemplo de uso**
7. **Integrar com `ComposioClient`**

## 📚 Referências


- Arquivo Python: `temp/composio/core/models/custom_tools.py`
- Arquivo Rust (atual): `src/models/tools.rs` (parcial)
- Arquivo Rust (novo): `src/models/custom_tools.rs` (a criar)