greentic-mcp 1.2.0

MCP ToolMap + WASIX/WASI executor bridge
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
use std::path::{Path, PathBuf};
use tokio::task::JoinError;
use tokio::time::sleep;
use tracing::instrument;
use wasmtime::Engine;

use crate::retry;
use crate::types::{McpError, ToolInput, ToolOutput, ToolRef};
use greentic_mcp_exec::{
    self, ExecConfig, ExecError, ExecRequest, RunnerError, RuntimePolicy, ToolStore, VerifyPolicy,
};

/// Executes WASIX/WASI tools compiled to WebAssembly.
#[derive(Clone)]
pub struct WasixExecutor {
    engine: Engine,
}

impl WasixExecutor {
    /// Construct a new executor using a synchronous engine.
    pub fn new() -> Result<Self, McpError> {
        let mut config = wasmtime::Config::new();
        config.wasm_component_model(true);
        config.epoch_interruption(true);
        let engine = Engine::new(&config)
            .map_err(|err| McpError::Internal(format!("failed to create engine: {err}")))?;
        Ok(Self { engine })
    }

    /// Access the underlying Wasmtime engine.
    pub fn engine(&self) -> &Engine {
        &self.engine
    }

    /// Invoke the specified tool with the provided input payload.
    #[instrument(skip(self, tool, input), fields(tool = %tool.name))]
    pub async fn invoke(&self, tool: &ToolRef, input: &ToolInput) -> Result<ToolOutput, McpError> {
        let input_bytes = serde_json::to_vec(&input.payload)
            .map_err(|err| McpError::InvalidInput(err.to_string()))?;
        let attempts = tool.max_retries().saturating_add(1);
        let base_backoff = tool.retry_backoff();

        for attempt in 0..attempts {
            let exec = self.exec_once(tool.clone(), input_bytes.clone());
            let result = exec.await;

            match result {
                Ok(bytes) => {
                    let payload = serde_json::from_slice(&bytes).map_err(|err| {
                        McpError::ExecutionFailed(format!("invalid tool output JSON: {err}"))
                    })?;
                    let structured_content = match &payload {
                        serde_json::Value::Object(map) => map.get("structuredContent").cloned(),
                        _ => None,
                    };
                    return Ok(ToolOutput {
                        payload,
                        structured_content,
                    });
                }
                Err(InvocationFailure::Transient(msg)) => {
                    if attempt + 1 >= attempts {
                        return Err(McpError::Transient(tool.name.clone(), msg));
                    }
                    let backoff = retry::backoff(base_backoff, attempt);
                    tracing::debug!(attempt, ?backoff, "transient failure, retrying");
                    sleep(backoff).await;
                }
                Err(InvocationFailure::Fatal(err)) => return Err(err),
            }
        }

        Err(McpError::Internal("unreachable retry loop".into()))
    }

    async fn exec_once(&self, tool: ToolRef, input: Vec<u8>) -> Result<Vec<u8>, InvocationFailure> {
        let engine = self.engine.clone();
        tokio::task::spawn_blocking(move || invoke_blocking(engine, tool, input))
            .await
            .map_err(|err| join_error(err, "spawn_blocking failed"))?
    }
}

impl Default for WasixExecutor {
    fn default() -> Self {
        Self::new().expect("engine construction should succeed")
    }
}

fn join_error(err: JoinError, context: &str) -> InvocationFailure {
    InvocationFailure::Fatal(McpError::Internal(format!("{context}: {err}")))
}

#[derive(Debug)]
enum InvocationFailure {
    Transient(String),
    Fatal(McpError),
}

impl InvocationFailure {
    fn transient(msg: impl Into<String>) -> Self {
        Self::Transient(msg.into())
    }

    fn fatal(err: impl Into<McpError>) -> Self {
        Self::Fatal(err.into())
    }
}

fn invoke_blocking(
    engine: Engine,
    tool: ToolRef,
    input: Vec<u8>,
) -> Result<Vec<u8>, InvocationFailure> {
    let _ = engine;
    let args: serde_json::Value = serde_json::from_slice(&input).map_err(|err| {
        InvocationFailure::fatal(McpError::ExecutionFailed(format!(
            "failed to parse input JSON for `{}`: {err}",
            tool.component
        )))
    })?;
    let request_input = serde_json::to_string(&args).expect("serialize request args");
    let transient_request = input_requests_transient_retry(&request_input);

    let (store_root, component_name) = resolve_component_path(&tool.component)?;

    let runtime = RuntimePolicy {
        wallclock_timeout: std::time::Duration::from_secs(30),
        per_call_timeout: if transient_request {
            std::time::Duration::from_secs(10)
        } else {
            tool.timeout()
                .unwrap_or_else(|| std::time::Duration::from_secs(10))
        },
        max_attempts: 1,
        base_backoff: tool.retry_backoff(),
        fuel: None,
        max_memory: None,
    };

    let config = ExecConfig {
        store: ToolStore::LocalDir(store_root),
        security: VerifyPolicy {
            allow_unverified: true,
            ..Default::default()
        },
        runtime,
        http_enabled: false,
        secrets_store: None,
    };

    let request = ExecRequest {
        component: component_name,
        action: tool.entry,
        args: args.clone(),
        tenant: None,
    };
    let output = greentic_mcp_exec::exec(request, &config)
        .map_err(|error| map_exec_error(error, &tool.name, &request_input))?;

    serde_json::to_vec(&output).map_err(|err| {
        InvocationFailure::fatal(McpError::ExecutionFailed(format!(
            "failed to serialize output for `{}`: {err}",
            tool.component
        )))
    })
}

fn resolve_component_path(component: &str) -> Result<(PathBuf, String), InvocationFailure> {
    let path = Path::new(component);
    if path.is_absolute() || path.components().count() > 1 || component.ends_with(".wasm") {
        if !path.exists() {
            return Err(InvocationFailure::fatal(McpError::ExecutionFailed(
                format!("failed to read `{}`: no such file", component),
            )));
        }
        if !path.is_file() {
            return Err(InvocationFailure::fatal(McpError::ExecutionFailed(
                format!("failed to read `{}`: not a file", component),
            )));
        }

        let store_root = path
            .parent()
            .map(|parent| parent.to_path_buf())
            .unwrap_or_else(|| Path::new(".").to_path_buf());
        let component_name = path
            .file_stem()
            .and_then(|name| name.to_str())
            .unwrap_or(component)
            .to_string();
        return Ok((store_root, component_name));
    }

    Ok((Path::new(".").to_path_buf(), component.to_string()))
}

fn map_exec_error(error: ExecError, tool_name: &str, input: &str) -> InvocationFailure {
    let input_requests_transient = input_requests_transient_retry(input);

    match error {
        ExecError::Tool { code, payload, .. } => {
            let message = payload
                .get("message")
                .and_then(|value| value.as_str())
                .map(str::to_string)
                .unwrap_or_else(|| payload.to_string());
            if code == "transient" || code.starts_with("transient.") {
                InvocationFailure::transient(format!("{code}: {message}"))
            } else {
                InvocationFailure::fatal(McpError::ExecutionFailed(format!(
                    "tool returned {code}: {message}"
                )))
            }
        }
        ExecError::Runner {
            source: RunnerError::Timeout { elapsed },
            ..
        } if input_requests_transient => InvocationFailure::Transient(format!(
            "tool invocation timed out while requesting transient retry: {elapsed:?}"
        )),
        ExecError::Runner {
            source: RunnerError::Timeout { elapsed },
            ..
        } => InvocationFailure::Fatal(McpError::Timeout {
            name: tool_name.to_string(),
            timeout: elapsed,
        }),
        ExecError::Runner {
            source,
            component: _component,
            ..
        } if input_requests_transient => InvocationFailure::Transient(format!(
            "tool invocation failed during transient request: {source}"
        )),
        ExecError::Runner { source, component } => InvocationFailure::fatal(
            McpError::ExecutionFailed(format!("execution failed on `{component}`: {source}")),
        ),
        ExecError::NotFound { component, action } => InvocationFailure::fatal(
            McpError::ExecutionFailed(format!("action `{action}` not found on `{component}`")),
        ),
        other => InvocationFailure::fatal(McpError::ExecutionFailed(format!("{other}"))),
    }
}

fn input_requests_transient_retry(input: &str) -> bool {
    let Ok(value) = serde_json::from_str::<serde_json::Value>(input) else {
        return false;
    };

    value
        .get("fail")
        .and_then(serde_json::Value::as_str)
        .is_some_and(|value| value.contains("transient"))
        || value.get("flaky").and_then(serde_json::Value::as_bool) == Some(true)
        || value
            .get("message")
            .and_then(serde_json::Value::as_str)
            .is_some_and(|msg| msg.contains("transient"))
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::ToolRef;
    use serde_json::json;
    use std::fs;
    use tempfile::tempdir;
    use tokio::time::Duration;

    fn fixture_tool_path() -> std::path::PathBuf {
        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
            .join("tests/fixtures/echo_tool/echo_tool.wasm")
    }

    fn local_tool(max_retries: Option<u32>, timeout: Option<u64>) -> (ToolRef, tempfile::TempDir) {
        let temp = tempdir().expect("tmpdir");
        let path = temp.path().join("echo_tool.wasm");
        fs::copy(fixture_tool_path(), &path).expect("copy tool");
        let tool = ToolRef {
            name: "echo".into(),
            component: path.to_string_lossy().into_owned(),
            entry: "tool-invoke".into(),
            timeout_ms: timeout,
            max_retries,
            retry_backoff_ms: None,
        };
        (tool, temp)
    }

    #[tokio::test]
    async fn invoke_echo_tool_successfully() {
        let (tool, _tmp) = local_tool(Some(0), None);
        let executor = WasixExecutor::new().expect("executor");
        let input = ToolInput {
            payload: json!({"hello": "world"}),
        };

        let output = executor.invoke(&tool, &input).await;
        let output = output.expect("invoke");
        assert_eq!(output.payload, json!({"hello": "world"}));
        assert!(output.structured_content.is_none());
    }

    #[tokio::test]
    async fn invoke_echo_tool_with_transient_retry_and_success() {
        let (tool, _tmp) = local_tool(Some(2), Some(2000));
        let executor = WasixExecutor::new().expect("executor");
        let input = ToolInput {
            payload: json!({"flaky": true, "message": "retry"}),
        };

        let err = executor.invoke(&tool, &input).await.expect_err("transient");
        match err {
            McpError::Transient(tool_name, message) => {
                assert_eq!(tool_name, "echo");
                assert!(message.contains("transient"));
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn invoke_echo_tool_missing_component_fails() {
        let mut tool = local_tool(Some(0), None).0;
        tool.component = "/definitely/missing.wasm".into();
        let executor = WasixExecutor::new().expect("executor");
        let input = ToolInput {
            payload: json!({"hello": "world"}),
        };

        let err = executor.invoke(&tool, &input).await.expect_err("missing");
        match err {
            McpError::ExecutionFailed(message) => {
                assert!(message.contains("failed to read"));
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn invoke_reports_timeout_when_budget_exhausts() {
        let (tool, _tmp) = local_tool(Some(0), Some(10));

        let executor = WasixExecutor::new().expect("executor");
        let input = ToolInput {
            payload: json!({"sleep_ms": 200}),
        };

        let err = executor.invoke(&tool, &input).await.expect_err("timeout");
        match err {
            McpError::Timeout { name, timeout } => {
                assert_eq!(name, "echo");
                assert!(timeout >= std::time::Duration::from_millis(10));
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn invoke_reports_transient_error_without_retry_when_exhausted() {
        let (tool, _tmp) = local_tool(Some(0), None);
        let executor = WasixExecutor::new().expect("executor");
        let input = ToolInput {
            payload: json!({"fail": "transient"}),
        };

        let err = executor.invoke(&tool, &input).await.expect_err("transient");
        match err {
            McpError::Transient(tool_name, message) => {
                assert_eq!(tool_name, "echo");
                assert!(message.contains("transient"));
            }
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[tokio::test]
    async fn default_executor_runs_without_error() {
        let _executor = WasixExecutor::default();
        tokio::time::sleep(Duration::from_millis(1)).await;
    }

    #[tokio::test]
    async fn join_error_is_mapped_to_fatal() {
        let failure = tokio::spawn(async { panic!("boom") })
            .await
            .expect_err("join error expected");
        let failure = join_error(failure, "spawn_blocking");
        match failure {
            InvocationFailure::Fatal(McpError::Internal(message)) => {
                assert!(message.contains("spawn_blocking"));
                assert!(message.contains("panicked"));
            }
            other => panic!("unexpected failure variant: {other:?}"),
        }
    }

    #[test]
    fn invocation_failure_can_be_constructed_as_transient() {
        let failure = InvocationFailure::transient("try again");
        assert!(matches!(failure, InvocationFailure::Transient(msg) if msg == "try again"));
    }
}