rmcp-agent 0.1.3

A library that extends langchain-rust with support for Model Context Protocol (MCP) tool integration and streaming tool execution capabilities.
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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
use std::collections::HashMap;
use std::pin::Pin;
use std::sync::Arc;

use async_trait::async_trait;
use chrono::Utc;
use futures_util::Stream;
use langchain_rust::agent::AgentError;
use langchain_rust::chain::{Chain, ChainError};
use langchain_rust::language_models::GenerateResult;
use langchain_rust::memory::SimpleMemory;
use langchain_rust::prompt::PromptArgs;
use langchain_rust::schemas::{AgentAction, AgentEvent, BaseMemory, LogTools, Message, StreamData};
use langchain_rust::tools::Tool;
use serde_json::{Value, json};
use tokio::sync::Mutex;
use tokio_stream::wrappers::UnboundedReceiverStream;
use uuid::Uuid;

use crate::agent::extension::{AgentEventChunk, AgentExt, DeltaEvent};

pub struct OpenAIMcpAgentExecutor<A>
where
    A: AgentExt,
{
    agent: Arc<A>,
    max_iterations: Option<i32>,
    break_if_error: bool,

    pub model: String,
    pub memory: Option<Arc<Mutex<dyn BaseMemory>>>,
}

impl<A: AgentExt> OpenAIMcpAgentExecutor<A> {
    pub fn new(agent: Arc<A>, model: impl ToString) -> Self {
        Self {
            agent,
            max_iterations: Some(10),
            break_if_error: false,
            memory: None,
            model: model.to_string(),
        }
    }

    pub fn with_max_iterations(mut self, max_iterations: i32) -> Self {
        self.max_iterations = Some(max_iterations);
        self
    }

    pub fn with_memory(mut self, memory: Arc<Mutex<dyn BaseMemory>>) -> Self {
        self.memory = Some(memory);
        self
    }

    pub fn with_break_if_error(mut self, break_if_error: bool) -> Self {
        self.break_if_error = break_if_error;
        self
    }

    fn get_name_to_tools(&self) -> HashMap<String, Arc<dyn Tool>> {
        let mut name_to_tool = HashMap::new();
        for tool in self.agent.get_tools().iter() {
            tracing::debug!("Loading Tool: {}", tool.name());
            name_to_tool.insert(tool.name().trim().replace(" ", "_"), tool.clone());
        }
        name_to_tool
    }
}

#[async_trait]
impl<A> Chain for OpenAIMcpAgentExecutor<A>
where
    A: AgentExt + 'static,
{
    async fn call(&self, input_variables: PromptArgs) -> Result<GenerateResult, ChainError> {
        let mut input_variables = input_variables.clone();
        let name_to_tools = self.get_name_to_tools();
        let mut steps: Vec<(AgentAction, String)> = Vec::new();
        tracing::debug!("steps: {steps:?}");
        if let Some(memory) = &self.memory {
            let memory = memory.lock().await;
            input_variables.insert("chat_history".to_string(), json!(memory.messages()));
        } else {
            input_variables.insert(
                "chat_history".to_string(),
                json!(SimpleMemory::new().messages()),
            );
        }

        loop {
            let agent_event = self
                .agent
                .plan(&steps, input_variables.clone())
                .await
                .map_err(|e| ChainError::AgentError(format!("Error in agent planning: {e}")))?;

            match agent_event {
                AgentEvent::Action(actions) => {
                    for action in actions {
                        tracing::debug!("Action: {:?}", action.tool_input);
                        let tool = name_to_tools
                            .get(&action.tool.trim().replace(" ", "_"))
                            .ok_or_else(|| {
                                AgentError::ToolError(format!("Tool {} not found", action.tool))
                            })
                            .map_err(|e| ChainError::AgentError(e.to_string()))?;

                        let observation = match tool.call(&action.tool_input).await {
                            Ok(result) => result,
                            Err(err) => {
                                let error_msg = err.to_string();
                                tracing::info!("The tool return the following error: {error_msg}");
                                if self.break_if_error {
                                    return Err(ChainError::AgentError(
                                        AgentError::ToolError(error_msg).to_string(),
                                    ));
                                } else {
                                    format!("The tool return the following error: {error_msg}")
                                }
                            }
                        };

                        steps.push((action, observation));
                    }
                }
                AgentEvent::Finish(finish) => {
                    if let Some(memory) = &self.memory {
                        let mut memory = memory.lock().await;

                        memory.add_user_message(match &input_variables["input"] {
                            // Avoid adding extra quotes to the user input in the history.
                            Value::String(s) => s,
                            x => x, // This is the JSON encoded value.
                        });

                        let mut tools_ai_message_seen: HashMap<String, ()> = HashMap::default();
                        for (action, observation) in steps {
                            let LogTools { tool_id, tools } = serde_json::from_str(&action.log)?;
                            let tools_value = serde_json::from_str(&tools)?;
                            if tools_ai_message_seen.insert(tools, ()).is_none() {
                                memory.add_message(
                                    Message::new_ai_message("").with_tool_calls(tools_value),
                                );
                            }
                            memory.add_message(Message::new_tool_message(observation, tool_id));
                        }

                        memory.add_ai_message(&finish.output);
                    }

                    return Ok(GenerateResult {
                        generation: finish.output,
                        ..Default::default()
                    });
                }
            }

            if let Some(max_iterations) = self.max_iterations {
                if steps.len() >= max_iterations as usize {
                    return Ok(GenerateResult {
                        generation: "Max iterations reached".to_string(),
                        ..Default::default()
                    });
                }
            }
        }
    }

    async fn stream(
        &self,
        input_variables: PromptArgs,
    ) -> Result<Pin<Box<dyn Stream<Item = Result<StreamData, ChainError>> + Send>>, ChainError>
    {
        let mut input_variables = input_variables.clone();
        let name_to_tools = self.get_name_to_tools();
        let mut steps: Vec<(AgentAction, String)> = Vec::new();

        let (tx, rx) = tokio::sync::mpsc::unbounded_channel();

        if let Some(memory) = &self.memory {
            let memory = memory.lock().await;
            input_variables.insert("chat_history".to_string(), json!(memory.messages()));
        } else {
            input_variables.insert(
                "chat_history".to_string(),
                json!(SimpleMemory::new().messages()),
            );
        }

        let conversation_id = input_variables
            .get("conversation_id")
            .unwrap_or(&Value::String(Uuid::now_v7().to_string()))
            .to_string();

        let chat_completion_id = format!("chatcmpl-{}", Uuid::now_v7());
        let model = self.model.clone();
        let created = Utc::now().timestamp();

        // Send initial chunk
        let _ = tx.send(Ok(StreamData::new(
            json!({
                "id": chat_completion_id,
                "conversation_id": conversation_id,
                "object": "chat.completion.chunk",
                "created": created,
                "model": model,
                "choices": [{
                    "index": 0,
                    "delta": {
                        "role": "assistant",
                        "content": null
                    },
                    "logprobs": null,
                    "finish_reason": null
                }]
            }),
            None,
            "",
        )));

        let agent = self.agent.clone();
        let memory = self.memory.clone();
        let max_iterations = self.max_iterations;
        let break_if_error = self.break_if_error;

        tokio::spawn(async move {
            use futures_util::StreamExt;

            let mut accumulated_content = String::new();
            let mut current_iteration_steps: Vec<(AgentAction, String)> = Vec::new();

            loop {
                accumulated_content.clear();
                current_iteration_steps.clear();

                let mut plan_stream = match agent.plan_stream(&steps, input_variables.clone()).await
                {
                    Ok(stream) => stream,
                    Err(e) => {
                        let _ = tx.send(Ok(StreamData::new(
                            json!({
                                "id": chat_completion_id,
                                "conversation_id": conversation_id,
                                "object": "chat.completion.chunk",
                                "created": created,
                                "model": model,
                                "choices": [{
                                    "index": 0,
                                    "delta": {
                                        "content": format!("Error: {e}")
                                    },
                                    "logprobs": null,
                                    "finish_reason": "stop"
                                }]
                            }),
                            None,
                            "",
                        )));
                        return;
                    }
                };

                while let Some(chunk_result) = plan_stream.next().await {
                    match chunk_result {
                        Ok(chunk) => match chunk {
                            AgentEventChunk::Delta(event) => match event {
                                DeltaEvent::Content(content) => {
                                    if !content.is_empty() {
                                        accumulated_content.push_str(&content);

                                        let _ = tx.send(Ok(StreamData::new(
                                            json!({
                                                "id": chat_completion_id,
                                                "conversation_id": conversation_id,
                                                "object": "chat.completion.chunk",
                                                "created": created,
                                                "model": model,
                                                "choices": [{
                                                    "index": 0,
                                                    "delta": {
                                                        "content": content
                                                    },
                                                    "logprobs": null,
                                                    "finish_reason": null
                                                }]
                                            }),
                                            None,
                                            content,
                                        )));
                                    }
                                }
                                DeltaEvent::Action(action) => {
                                    // Generate a tool call ID for this partial action
                                    let log: Value = serde_json::from_str(action.log.as_str())
                                        .unwrap_or_default();

                                    let tool_call_id = match log.get("tool_id") {
                                        Some(id) => id
                                            .as_str()
                                            .unwrap_or_else(|| {
                                                tracing::warn!("tool_id is not a string: {}", id);
                                                ""
                                            })
                                            .to_string(),
                                        None => {
                                            let tmp_id = Uuid::now_v7().to_string();
                                            tracing::error!(
                                                "missing `tool_id` in action.log, tmp id: {tmp_id}"
                                            );
                                            println!(
                                                "missing `tool_id` in action.log, tmp id: {tmp_id}"
                                            );
                                            tmp_id
                                        }
                                    };

                                    // Create the tool call JSON structure for the partial action
                                    let tool_call_json = json!({
                                        "id": tool_call_id,
                                        "conversation_id": conversation_id,
                                        "type": "function",
                                        "function": {
                                            "name": action.tool,
                                            "arguments": action.tool_input,
                                        }
                                    });

                                    // Send the partial tool call information
                                    let _ = tx.send(Ok(StreamData::new(
                                        json!({
                                            "id": chat_completion_id,
                                            "conversation_id": conversation_id,
                                            "object": "chat.completion.chunk",
                                            "created": created,
                                            "model": model,
                                            "choices": [{
                                                "index": 0,
                                                "delta": {
                                                    "tool_calls": [tool_call_json]
                                                },
                                                "logprobs": null,
                                                "finish_reason": null
                                            }]
                                        }),
                                        None,
                                        "",
                                    )));
                                }
                            },
                            AgentEventChunk::Final(event) => {
                                tracing::debug!("got event: {event:?}");
                                match event {
                                    AgentEvent::Action(actions) => {
                                        for action in actions {
                                            let tool = match name_to_tools
                                                .get(&action.tool.trim().replace(" ", "_"))
                                            {
                                                Some(tool) => tool,
                                                None => {
                                                    let error_msg =
                                                        format!("Tool {} not found", action.tool);
                                                    let _ = tx.send(Ok(StreamData::new(
                                                        json!({
                                                            "id": chat_completion_id,
                                                            "conversation_id": conversation_id,
                                                            "object": "chat.completion.chunk",
                                                            "created": created,
                                                            "model": model,
                                                            "choices": [{
                                                                "index": 0,
                                                                "delta": {
                                                                    "content": error_msg
                                                                },
                                                                "logprobs": null,
                                                                "finish_reason": "stop"
                                                            }]
                                                        }),
                                                        None,
                                                        error_msg,
                                                    )));
                                                    return;
                                                }
                                            };

                                            let log: Value = serde_json::from_str(&action.log)
                                                .unwrap_or_default();

                                            let tool_call_id = log
                                                .get("tool_id")
                                                .and_then(|v| v.as_str())
                                                .map(|s| s.to_string())
                                                .unwrap_or_else(|| Uuid::now_v7().to_string());

                                            let tool_call_json = json!({
                                                "id": tool_call_id,
                                                "conversation_id": conversation_id,
                                                "type": "function",
                                                "function": {
                                                    "name": action.tool,
                                                    "arguments": action.tool_input,
                                                }
                                            });

                                            let _ = tx.send(Ok(StreamData::new(
                                                json!({
                                                    "id": chat_completion_id,
                                                    "conversation_id": conversation_id,
                                                    "object": "chat.completion.chunk",
                                                    "created": created,
                                                    "model": model,
                                                    "choices": [{
                                                        "index": 0,
                                                        "delta": {
                                                            "tool_calls": [tool_call_json]
                                                        },
                                                        "logprobs": null,
                                                        "finish_reason": ""
                                                    }]
                                                }),
                                                None,
                                                "",
                                            )));

                                            let observation =
                                                match tool.call(&action.tool_input).await {
                                                    Ok(result) => result,
                                                    Err(err) => {
                                                        let error_msg =
                                                            format!("Tool error: {err}");

                                                        if break_if_error {
                                                            let _ = tx.send(Ok(StreamData::new(
                                                            json!({
                                                                "id": chat_completion_id,
                                                                "conversation_id": conversation_id,
                                                                "object": "chat.completion.chunk",
                                                                "created": created,
                                                                "model": model,
                                                                "choices": [{
                                                                    "index": 0,
                                                                    "delta": {
                                                                        "content": error_msg
                                                                    },
                                                                    "logprobs": null,
                                                                    "finish_reason": "stop"
                                                                }]
                                                            }),
                                                            None,
                                                            error_msg,
                                                        )));
                                                            return;
                                                        } else {
                                                            error_msg
                                                        }
                                                    }
                                                };

                                            let parsed =
                                                match serde_json::from_str::<Value>(&observation) {
                                                    Ok(json_result) => json_result,
                                                    Err(_) => Value::String(observation.clone()),
                                                };

                                            let delta = json!({
                                                "content": null,
                                                "parsed": parsed,
                                                "tool_name": tool.name(),
                                                "tool_call_id": tool_call_id
                                            });

                                            let _ = tx.send(Ok(StreamData::new(
                                                json!({
                                                    "id": chat_completion_id,
                                                    "conversation_id": conversation_id,
                                                    "object": "chat.completion.chunk",
                                                    "created": created,
                                                    "model": model,
                                                    "choices": [{
                                                        "index": 0,
                                                        "delta": delta,
                                                        "logprobs": null,
                                                        "finish_reason": null
                                                    }]
                                                }),
                                                None,
                                                parsed.to_string(),
                                            )));

                                            tracing::debug!("observation: {observation}");

                                            current_iteration_steps
                                                .push((action.clone(), observation.clone()));
                                            steps.push((action, observation));
                                        }

                                        if !accumulated_content.is_empty() {
                                            if let Some(memory) = &memory {
                                                let mut memory = memory.lock().await;
                                                memory.add_ai_message(&accumulated_content);
                                            }
                                        }

                                        if let Some(memory) = &memory {
                                            let mut memory = memory.lock().await;
                                            let mut tools_ai_message_seen: HashMap<String, ()> =
                                                HashMap::default();

                                            for (action, observation) in &current_iteration_steps {
                                                match serde_json::from_str::<LogTools>(&action.log)
                                                {
                                                    Ok(LogTools { tool_id, tools }) => {
                                                        if let Ok(tools_value) =
                                                            serde_json::from_str::<Value>(&tools)
                                                        {
                                                            if tools_ai_message_seen
                                                                .insert(tools, ())
                                                                .is_none()
                                                            {
                                                                memory.add_message(
                                                                    Message::new_ai_message("")
                                                                        .with_tool_calls(
                                                                            tools_value,
                                                                        ),
                                                                );
                                                            }
                                                            memory.add_message(
                                                                Message::new_tool_message(
                                                                    observation.clone(),
                                                                    tool_id,
                                                                ),
                                                            );
                                                        } else {
                                                            tracing::warn!(
                                                                "Failed to parse tools JSON: {}",
                                                                tools
                                                            );
                                                        }
                                                    }
                                                    Err(e) => {
                                                        tracing::warn!(
                                                            "Failed to parse action log: {}",
                                                            e
                                                        );
                                                    }
                                                }
                                            }
                                        }

                                        break;
                                    }
                                    AgentEvent::Finish(finish) => {
                                        if let Some(memory) = &memory {
                                            let mut memory = memory.lock().await;

                                            if steps.is_empty()
                                                && current_iteration_steps.is_empty()
                                            {
                                                memory.add_user_message(
                                                    match &input_variables["input"] {
                                                        Value::String(s) => s,
                                                        x => x,
                                                    },
                                                );
                                            }

                                            if !accumulated_content.is_empty() {
                                                memory.add_ai_message(&accumulated_content);
                                            }

                                            let mut tools_ai_message_seen: HashMap<String, ()> =
                                                HashMap::default();
                                            for (action, observation) in &steps {
                                                match serde_json::from_str::<LogTools>(&action.log)
                                                {
                                                    Ok(LogTools { tool_id, tools }) => {
                                                        if let Ok(tools_value) =
                                                            serde_json::from_str::<Value>(&tools)
                                                        {
                                                            if tools_ai_message_seen
                                                                .insert(tools, ())
                                                                .is_none()
                                                            {
                                                                memory.add_message(
                                                                    Message::new_ai_message("")
                                                                        .with_tool_calls(
                                                                            tools_value,
                                                                        ),
                                                                );
                                                            }
                                                            memory.add_message(
                                                                Message::new_tool_message(
                                                                    observation.clone(),
                                                                    tool_id,
                                                                ),
                                                            );
                                                        } else {
                                                            tracing::warn!(
                                                                "Failed to parse tools JSON: {tools}"
                                                            );
                                                        }
                                                    }
                                                    Err(e) => {
                                                        tracing::warn!(
                                                            "Failed to parse action log: {e}"
                                                        );
                                                    }
                                                }
                                            }
                                            memory.add_ai_message(&finish.output);
                                        }

                                        let _ = tx.send(Ok(StreamData::new(
                                            json!({
                                                "id": chat_completion_id,
                                                "conversation_id": conversation_id,
                                                "object": "chat.completion.chunk",
                                                "created": created,
                                                "model": model,
                                                "choices": [{
                                                    "index": 0,
                                                    "delta": {},
                                                    "logprobs": null,
                                                    "finish_reason": "stop"
                                                }]
                                            }),
                                            None,
                                            "stop",
                                        )));
                                        return;
                                    }
                                }
                            }
                        },
                        Err(e) => {
                            let _ = tx.send(Ok(StreamData::new(
                                json!({
                                    "id": chat_completion_id,
                                    "conversation_id": conversation_id,
                                    "object": "chat.completion.chunk",
                                    "created": created,
                                    "model": model,
                                    "choices": [{
                                        "index": 0,
                                        "delta": {
                                            "content": format!("Stream error: {e}")
                                        },
                                        "logprobs": null,
                                        "finish_reason": "stop"
                                    }]
                                }),
                                None,
                                "",
                            )));
                            return;
                        }
                    }
                }

                if let Some(memory) = &memory {
                    let memory = memory.lock().await;
                    let messages = memory.messages();
                    input_variables.insert("chat_history".to_string(), json!(messages));
                }

                // Check max iterations before continuing
                if let Some(max_iterations) = max_iterations {
                    if steps.len() >= max_iterations as usize {
                        let _ = tx.send(Ok(StreamData::new(
                            json!({
                                "id": chat_completion_id,
                                "conversation_id": conversation_id,
                                "object": "chat.completion.chunk",
                                "created": created,
                                "model": model,
                                "choices": [{
                                    "index": 0,
                                    "delta": {
                                        "content": "Maximum iterations reached."
                                    },
                                    "logprobs": null,
                                    "finish_reason": "length"
                                }]
                            }),
                            None,
                            "Maximum iterations reached.",
                        )));
                        return;
                    }
                }
            }
        });

        Ok(Box::pin(UnboundedReceiverStream::new(rx)))
    }
}