pmcp-code-mode 0.7.2

Code Mode validation and execution framework for MCP servers
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
//! High-level code execution trait for MCP servers.
//!
//! This module provides the [`CodeExecutor`] trait, which is the primary public API
//! for implementing code execution in MCP servers. It replaces the internal
//! `HttpExecutor`, `SdkExecutor`, and `McpExecutor` traits for external server
//! developers (those traits remain available for advanced use behind the
//! `js-runtime` feature flag).

use crate::types::ExecutionError;

/// High-level trait for executing validated code.
///
/// Implementations handle the execution of code that has already passed
/// validation and token verification. This is the primary public API
/// for code execution -- it replaces the internal `HttpExecutor`,
/// `SdkExecutor`, and `McpExecutor` traits for external server developers.
///
/// # Execution Patterns
///
/// The four supported patterns (all implemented via this single trait):
/// - **Pattern A (SQL):** Direct SQL execution, no JS runtime
/// - **Pattern B (JS+HTTP):** JavaScript plan compiled and executed via HTTP calls
/// - **Pattern C (JS+SDK):** JavaScript plan executed via AWS SDK calls
/// - **Pattern D (JS+MCP):** JavaScript plan executed via MCP tool calls
///
/// # API Stability Note
///
/// **\[Addresses divergent review concern: CodeExecutor trait surface area\]**
/// This v0.1.0 API uses a simple `(code, variables)` signature per D-04.
/// A future v0.2.0 may add an `ExecutionContext` parameter carrying timeout,
/// cancellation token, and request metadata. The `(code, variables)` signature
/// will be preserved as a default-method wrapper for backward compatibility.
///
/// # Example
///
/// ```rust,ignore
/// use pmcp_code_mode::{CodeExecutor, ExecutionError};
/// use serde_json::Value;
///
/// struct MyExecutor { /* database pool, http client, etc. */ }
///
/// #[pmcp_code_mode::async_trait]
/// impl CodeExecutor for MyExecutor {
///     async fn execute(
///         &self,
///         code: &str,
///         variables: Option<&Value>,
///     ) -> Result<Value, ExecutionError> {
///         // Execute validated code against your backend
///         todo!()
///     }
/// }
/// ```
#[async_trait::async_trait]
pub trait CodeExecutor: Send + Sync {
    /// Execute validated code and return the result.
    ///
    /// `code` has already passed validation and token verification.
    /// `variables` are optional user-provided parameters (e.g., GraphQL variables).
    ///
    /// Implementations should NOT re-verify the token -- that is handled
    /// by the Code Mode framework before calling this method.
    async fn execute(
        &self,
        code: &str,
        variables: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value, ExecutionError>;
}

// ---------------------------------------------------------------------------
// Standard adapters: bridge low-level executor traits to CodeExecutor
// ---------------------------------------------------------------------------
//
// These adapters solve the &mut self vs &self mismatch: PlanExecutor::execute
// requires &mut self, but CodeExecutor::execute takes &self. Each adapter
// creates a fresh PlanCompiler + PlanExecutor per call (cheap — both are small
// structs, and the caller's HttpExecutor/SdkExecutor holds Arc'd state).

/// Compile JavaScript code and execute the plan, returning the result value.
///
/// Shared implementation for all three adapters. The `setup` closure configures
/// the `PlanExecutor` with the appropriate backend (HTTP, SDK, or MCP) before
/// execution begins.
#[cfg(feature = "js-runtime")]
async fn compile_and_execute<H: crate::executor::HttpExecutor + 'static>(
    config: &crate::executor::ExecutionConfig,
    http: H,
    code: &str,
    variables: Option<&serde_json::Value>,
    setup: impl FnOnce(&mut crate::executor::PlanExecutor<H>),
    adapter: &str,
) -> Result<serde_json::Value, ExecutionError> {
    let mut compiler = crate::executor::PlanCompiler::with_config(config);
    let plan = compiler
        .compile_code(code)
        .map_err(|e| ExecutionError::InvalidScript {
            message: e.caller_message(),
        })?;
    let mut executor = crate::executor::PlanExecutor::new(http, config.clone());
    if let Some(vars) = variables {
        executor.set_variable("args", vars.clone());
    }
    setup(&mut executor);
    let result = executor.execute(&plan).await?;
    tracing::debug!(
        adapter,
        api_calls = result.api_calls.len(),
        execution_time_ms = result.execution_time_ms,
        "plan executed"
    );
    Ok(result.value)
}

/// Adapter bridging [`HttpExecutor`] to [`CodeExecutor`] for JavaScript/OpenAPI
/// servers (Pattern B: JS+HTTP).
///
/// Compiles JavaScript code into an execution plan, then runs it against an
/// HTTP backend. The executor holds its own [`ExecutionConfig`] for limits
/// (`max_api_calls`, `timeout_seconds`, `max_loop_iterations`).
///
/// # Example
///
/// ```rust,ignore
/// use pmcp_code_mode::{JsCodeExecutor, ExecutionConfig};
///
/// let http = CostExplorerHttpExecutor::new(clients.clone());
/// let config = ExecutionConfig::default();
/// let executor = Arc::new(JsCodeExecutor::new(http, config));
/// // Pass executor to #[derive(CodeMode)] struct as code_executor field
/// ```
#[cfg(feature = "js-runtime")]
pub struct JsCodeExecutor<H> {
    http: H,
    config: crate::executor::ExecutionConfig,
}

#[cfg(feature = "js-runtime")]
impl<H: crate::executor::HttpExecutor + Clone> JsCodeExecutor<H> {
    /// Create a new JS code executor with the given HTTP backend and config.
    pub fn new(http: H, config: crate::executor::ExecutionConfig) -> Self {
        Self { http, config }
    }
}

#[cfg(feature = "js-runtime")]
#[async_trait::async_trait]
impl<H: crate::executor::HttpExecutor + Clone + 'static> CodeExecutor for JsCodeExecutor<H> {
    async fn execute(
        &self,
        code: &str,
        variables: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value, ExecutionError> {
        compile_and_execute(
            &self.config,
            self.http.clone(),
            code,
            variables,
            |_| {},
            "js",
        )
        .await
    }
}

/// Adapter bridging [`SdkExecutor`] to [`CodeExecutor`] for SDK-backed servers
/// (Pattern C: JS+SDK).
///
/// Uses a no-op HTTP executor stub since SDK plans route through
/// `PlanExecutor::set_sdk_executor` instead of HTTP calls.
///
/// # Example
///
/// ```rust,ignore
/// use pmcp_code_mode::{SdkCodeExecutor, ExecutionConfig};
///
/// let sdk = MyCostExplorerSdk::new(credentials);
/// let config = ExecutionConfig::default();
/// let executor = Arc::new(SdkCodeExecutor::new(sdk, config));
/// ```
#[cfg(feature = "js-runtime")]
pub struct SdkCodeExecutor<S> {
    sdk: S,
    config: crate::executor::ExecutionConfig,
}

#[cfg(feature = "js-runtime")]
impl<S: crate::executor::SdkExecutor + Clone + 'static> SdkCodeExecutor<S> {
    /// Create a new SDK code executor with the given SDK backend and config.
    pub fn new(sdk: S, config: crate::executor::ExecutionConfig) -> Self {
        Self { sdk, config }
    }
}

#[cfg(feature = "js-runtime")]
#[async_trait::async_trait]
impl<S: crate::executor::SdkExecutor + Clone + 'static> CodeExecutor for SdkCodeExecutor<S> {
    async fn execute(
        &self,
        code: &str,
        variables: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value, ExecutionError> {
        let sdk = self.sdk.clone();
        compile_and_execute(
            &self.config,
            NoopHttpExecutor,
            code,
            variables,
            move |ex| {
                ex.set_sdk_executor(sdk);
            },
            "sdk",
        )
        .await
    }
}

/// Adapter bridging [`McpExecutor`] to [`CodeExecutor`] for MCP composition
/// servers (Pattern D: JS+MCP).
///
/// Uses a no-op HTTP executor stub since MCP plans route through
/// `PlanExecutor::set_mcp_executor` instead of HTTP calls.
///
/// # Example
///
/// ```rust,ignore
/// use pmcp_code_mode::{McpCodeExecutor, ExecutionConfig};
///
/// let mcp = MyMcpRouter::new(foundation_servers);
/// let config = ExecutionConfig::default();
/// let executor = Arc::new(McpCodeExecutor::new(mcp, config));
/// ```
///
/// Note: `mcp-code-mode` feature implies `js-runtime` in Cargo.toml,
/// which provides `PlanCompiler`, `PlanExecutor`, and `NoopHttpExecutor`.
#[cfg(feature = "mcp-code-mode")]
pub struct McpCodeExecutor<M> {
    mcp: M,
    config: crate::executor::ExecutionConfig,
}

#[cfg(feature = "mcp-code-mode")]
impl<M: crate::executor::McpExecutor + Clone + 'static> McpCodeExecutor<M> {
    /// Create a new MCP composition code executor.
    pub fn new(mcp: M, config: crate::executor::ExecutionConfig) -> Self {
        Self { mcp, config }
    }
}

#[cfg(feature = "mcp-code-mode")]
#[async_trait::async_trait]
impl<M: crate::executor::McpExecutor + Clone + 'static> CodeExecutor for McpCodeExecutor<M> {
    async fn execute(
        &self,
        code: &str,
        variables: Option<&serde_json::Value>,
    ) -> Result<serde_json::Value, ExecutionError> {
        let mcp = self.mcp.clone();
        compile_and_execute(
            &self.config,
            NoopHttpExecutor,
            code,
            variables,
            move |ex| {
                ex.set_mcp_executor(mcp);
            },
            "mcp",
        )
        .await
    }
}

/// No-op HTTP executor for SDK and MCP adapters that don't use HTTP calls.
/// Gated on `js-runtime`; `mcp-code-mode` implies `js-runtime` in Cargo.toml.
#[cfg(feature = "js-runtime")]
#[derive(Clone)]
struct NoopHttpExecutor;

#[cfg(feature = "js-runtime")]
#[async_trait::async_trait]
impl crate::executor::HttpExecutor for NoopHttpExecutor {
    async fn execute_request(
        &self,
        method: &str,
        _path: crate::executor::ResolvedPath<'_>,
        _body: Option<serde_json::Value>,
    ) -> Result<serde_json::Value, ExecutionError> {
        // The path is deliberately NOT formatted into this message (T-128-21a).
        // After Phase 128 D-09 the incoming `path` is the RESOLVED path rather
        // than the template the script wrote, so echoing it here would hand a
        // refused or attacker-shaped path straight back to the MCP client — and
        // this would be the one surviving path-echo site in the crate while the
        // phase claimed the Pitfall 7 class closed.
        Err(ExecutionError::RuntimeError {
            message: format!(
                "HTTP calls not supported in this executor mode (attempted a {method} request). \
                 Use JsCodeExecutor for HTTP-based execution."
            ),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    struct EchoExecutor;

    #[async_trait::async_trait]
    impl CodeExecutor for EchoExecutor {
        async fn execute(
            &self,
            code: &str,
            variables: Option<&serde_json::Value>,
        ) -> Result<serde_json::Value, ExecutionError> {
            Ok(json!({
                "code": code,
                "variables": variables,
            }))
        }
    }

    /// Compile and run `code` against a dry-run backend, through the same function
    /// every adapter uses.
    #[cfg(feature = "js-runtime")]
    async fn compile_and_run(code: &str) -> Result<serde_json::Value, ExecutionError> {
        use crate::executor::{ExecutionConfig, MockHttpExecutor};
        compile_and_execute(
            &ExecutionConfig::default(),
            MockHttpExecutor::new_dry_run(),
            code,
            None,
            |_| {},
            "test",
        )
        .await
    }

    /// A script that cannot be compiled is the CALLER's mistake: it must be its own
    /// error variant, never `RuntimeError` (a server fault), so a tool handler can
    /// report it as a tool-level rejection. (pmcp-code-mode 0.7.2, F-31.)
    #[cfg(feature = "js-runtime")]
    #[tokio::test]
    async fn a_script_that_does_not_compile_is_invalid_script_not_a_runtime_fault() {
        // String concatenation where a template literal is required.
        let err = compile_and_run("const r = await api.get('/search/' + args.q); return r;")
            .await
            .expect_err("a concatenated path does not compile");
        assert!(
            matches!(err, ExecutionError::InvalidScript { .. }),
            "a compile error is the caller's, got: {err:?}"
        );
        assert!(
            err.to_string().contains("template literal"),
            "the model must read what to change: {err}"
        );
    }

    /// A syntax error's parser message quotes the token it choked on, which repeats
    /// the caller's code. The reported text is fixed instead.
    #[cfg(feature = "js-runtime")]
    #[tokio::test]
    async fn a_syntax_error_does_not_echo_the_submitted_code() {
        let err = compile_and_run("const SECRETTOKEN = = 1;")
            .await
            .expect_err("a syntax error");
        match err {
            ExecutionError::InvalidScript { message } => {
                assert!(
                    !message.contains("SECRETTOKEN"),
                    "echoed the code: {message}"
                );
                assert!(message.contains("syntax error"), "{message}");
            },
            other => panic!("expected InvalidScript, got {other:?}"),
        }
    }

    #[tokio::test]
    async fn code_executor_echo() {
        let executor = EchoExecutor;
        let result = executor.execute("SELECT 1", None).await.unwrap();
        assert_eq!(result["code"], "SELECT 1");
    }

    #[tokio::test]
    async fn code_executor_with_variables() {
        let executor = EchoExecutor;
        let vars = json!({"limit": 10});
        let result = executor
            .execute("query { users }", Some(&vars))
            .await
            .unwrap();
        assert_eq!(result["variables"]["limit"], 10);
    }

    #[tokio::test]
    async fn code_executor_returns_error() {
        struct FailingExecutor;

        #[async_trait::async_trait]
        impl CodeExecutor for FailingExecutor {
            async fn execute(
                &self,
                _code: &str,
                _variables: Option<&serde_json::Value>,
            ) -> Result<serde_json::Value, ExecutionError> {
                Err(ExecutionError::BackendError(
                    "database unavailable".to_string(),
                ))
            }
        }

        let executor = FailingExecutor;
        let result = executor.execute("SELECT 1", None).await;
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert!(err.to_string().contains("database unavailable"));
    }

    // Compile-time test: CodeExecutor requires Send + Sync
    fn _assert_send_sync<T: Send + Sync>() {}
    fn _code_executor_is_send_sync() {
        _assert_send_sync::<EchoExecutor>();
    }

    /// T-128-21a — `NoopHttpExecutor`'s refusal names the METHOD and never the
    /// path. After Phase 128 D-09 the incoming `path` is the RESOLVED path rather
    /// than the template the script wrote, so this would otherwise be the one
    /// surviving path-echo site in the crate.
    #[cfg(feature = "js-runtime")]
    #[tokio::test]
    async fn noop_http_executor_error_names_the_method_and_not_the_path() {
        use crate::executor::{HttpExecutor, ResolvedPath};

        let path = ResolvedPath::from_checked("/secret/inventory/endpoint")
            .expect("a clean resolved path");
        let rendered = NoopHttpExecutor
            .execute_request("GET", path, None)
            .await
            .expect_err("the noop executor always refuses")
            .to_string();
        assert!(rendered.contains("GET"), "must name the method: {rendered}");
        assert!(
            !rendered.contains("/secret/inventory/endpoint"),
            "must NOT echo the resolved path: {rendered}"
        );
    }
}