Skip to main content

pmcp_code_mode/
lib.rs

1// Originated from pmcp-run/built-in/shared/pmcp-code-mode (https://github.com/guyernest/pmcp-run)
2// Moved into rust-mcp-sdk workspace as a first-class SDK crate for Phase 67.1
3//
4// Clippy pedantic/nursery allows for code imported from pmcp-run.
5// These will be cleaned up incrementally in future phases.
6#![allow(clippy::use_self)]
7#![allow(clippy::doc_markdown)]
8#![allow(clippy::needless_raw_string_hashes)]
9#![allow(clippy::needless_borrows_for_generic_args)]
10#![allow(clippy::if_same_then_else)]
11#![allow(clippy::map_unwrap_or)]
12#![allow(clippy::unused_self)]
13#![allow(clippy::too_many_arguments)]
14#![allow(clippy::struct_excessive_bools)]
15#![allow(clippy::cast_possible_wrap)]
16#![allow(clippy::only_used_in_recursion)]
17#![allow(clippy::self_only_used_in_recursion)]
18#![allow(clippy::redundant_pub_crate)]
19#![allow(clippy::manual_is_variant_and)]
20#![allow(clippy::unnecessary_literal_bound)]
21
22//! Code Mode - LLM-generated query validation and execution.
23//!
24//! This crate provides the infrastructure for "Code Mode", which allows MCP clients
25//! to generate and execute structured queries (GraphQL, SQL, REST) with a validation
26//! pipeline that ensures security and provides human-readable explanations.
27//!
28//! ## Architecture
29//!
30//! ```text
31//! describe_schema() → LLM generates code → validate_code() → user approval → execute_code()
32//! ```
33//!
34//! ## Key Components
35//!
36//! - **Validation Pipeline**: Parse → Policy Check → Security Analysis → Explanation → Token
37//! - **Approval Tokens**: HMAC-signed tokens binding code hash to validation result
38//! - **Explanations**: Template-based business-language descriptions of queries
39//! - **Policy Evaluation**: Pluggable trait for Cedar/AVP/custom policy engines
40//!
41//! ## Example Usage
42//!
43//! ```ignore
44//! use pmcp_code_mode::{
45//!     CodeModeConfig, ValidationPipeline, ValidationContext
46//! };
47//!
48//! // Create a validation pipeline
49//! let config = CodeModeConfig::enabled();
50//! let pipeline = ValidationPipeline::new(config, b"secret-key".to_vec());
51//!
52//! // Validate a query
53//! let context = ValidationContext::new("user-123", "session-456", "schema-hash", "perms-hash");
54//! let result = pipeline.validate_graphql_query("query { users { id name } }", &context)?;
55//! ```
56
57// High-level CodeExecutor trait (always available, no feature gate)
58mod code_executor;
59
60pub mod config;
61mod explanation;
62mod graphql;
63pub mod handler;
64mod token;
65mod types;
66pub mod validation;
67
68// Code Mode instruction and policy templates
69pub mod templates;
70
71// Schema Exposure Architecture - Three-Layer Schema Model
72pub mod schema_exposure;
73
74// Policy evaluation framework
75pub mod policy;
76
77// Cedar policy annotation parsing (no AWS dependency)
78pub mod policy_annotations;
79
80// Cedar schema and policy validation (test only)
81#[cfg(test)]
82pub mod cedar_validation;
83
84// JavaScript validation for OpenAPI Code Mode (requires SWC parser)
85#[cfg(feature = "openapi-code-mode")]
86mod javascript;
87
88// SQL validation for SQL Code Mode (requires sqlparser)
89#[cfg(feature = "sql-code-mode")]
90pub mod sql;
91
92// AWS Verified Permissions policy evaluator
93#[cfg(feature = "avp")]
94pub mod avp;
95
96// JavaScript execution runtime (AST-based execution in pure Rust)
97#[cfg(feature = "js-runtime")]
98pub mod executor;
99
100// Shared expression evaluation logic (used by both sync and async executors).
101//
102// `pub` (rather than the original `mod`) so that `tests/eval_semantic_regression.rs`
103// can pin the JsonValue output of `evaluate_with_scope` and
104// `evaluate_array_method_with_scope` against representative ValueExpr programs
105// (Phase 75 Wave 0 Task 2 — regression contract for Wave 3's mandatory cog 123/117 → ≤25 refactor).
106//
107// Why public: the eval functions need to be directly callable from a separate
108// `tests/` integration target so the snapshot can detect semantic drift. Making
109// the module `pub` is the smallest change that exposes the symbols; alternative
110// (per-symbol re-export at the crate root) would clutter the public surface
111// with internal helpers like `is_truthy` / `to_number` / `evaluate_binary_op`.
112#[cfg(feature = "js-runtime")]
113pub mod eval;
114
115// Re-export async_trait to avoid version conflicts in derive macro output (D-07)
116pub use async_trait::async_trait;
117
118/// The D4 path-placeholder floor, re-exported from core `pmcp`.
119///
120/// There is exactly **ONE** implementation of these rules and it lives in
121/// `pmcp::server::schema_validation`. This is a `pub use`, never a second copy
122/// (Phase 128, Q2). Two reasons the home is core rather than here:
123///
124/// 1. The toolkit's curated `http` build has no `pmcp-code-mode` edge and must
125///    not gain one (SC-1), so the shared rule cannot live in this crate.
126/// 2. This repo has a documented three-way-drift incident from a security rule
127///    that existed in more than one copy, so a second denylist is a prohibited
128///    shape rather than a style preference.
129///
130/// The re-export exists because D-09 obliges the SDK to publish the helper under
131/// the name a third-party `HttpExecutor` implementor would look for. An
132/// implementor whose template syntax is not OpenAPI's `{key}` can call
133/// `pmcp_code_mode::validate_path_placeholder` on each value it substitutes and
134/// `pmcp_code_mode::validate_resolved_path` on the composed result — or
135/// `pmcp_code_mode::validate_resolved_target`, which is that rule widened by the
136/// single author-written `?` separator, and is what `ResolvedPath::from_checked`
137/// itself calls. Either reaches the
138/// same rule the SDK itself applies before calling
139/// `HttpExecutor::execute_request`. (Plain backticks, not an intra-doc link:
140/// `executor` is gated on `js-runtime` and the link would not resolve in a
141/// default-feature doc build.)
142pub use pmcp::server::schema_validation::{
143    validate_path_placeholder, validate_resolved_path, validate_resolved_target,
144    PlaceholderRefusal, PlaceholderRules, PLACEHOLDER_MAX_LENGTH,
145};
146
147// High-level CodeExecutor trait (always available, no feature gate) (D-04)
148pub use code_executor::CodeExecutor;
149
150// Re-export public types
151pub use config::{resolve_server_id_from_env, CodeModeConfig};
152
153pub use explanation::{ExplanationGenerator, TemplateExplanationGenerator};
154
155pub use graphql::{GraphQLOperationType, GraphQLQueryInfo, GraphQLValidator};
156
157// JavaScript/OpenAPI Code Mode exports
158#[cfg(feature = "openapi-code-mode")]
159pub use javascript::{
160    ApiCall, HttpMethod, JavaScriptCodeInfo, JavaScriptValidator, OutputDeclaration,
161    SafetyViolation, SafetyViolationType,
162};
163
164// SQL Code Mode exports
165#[cfg(feature = "sql-code-mode")]
166pub use sql::{SqlStatementInfo, SqlStatementType, SqlValidator};
167
168// JavaScript execution runtime exports
169#[cfg(feature = "js-runtime")]
170pub use executor::{
171    filter_blocked_fields, find_blocked_fields_in_output, ApiCallLog, ArrayMethodCall,
172    BinaryOperator, BuiltinFunction, CompileError, ExecutionConfig, ExecutionPlan, ExecutionResult,
173    HttpExecutor, JsExecutor, MockExecutionMode, MockHttpExecutor, MockedCall, PathPart,
174    PathTemplate, PlanCompiler, PlanExecutor, PlanMetadata, PlanStep, ResolvedPath, SdkExecutor,
175    UnaryOperator, ValueExpr,
176};
177
178// Standard CodeExecutor adapters (bridge low-level traits to derive-macro-compatible API)
179#[cfg(feature = "js-runtime")]
180pub use code_executor::{JsCodeExecutor, SdkCodeExecutor};
181
182// MCP Code Mode executor
183#[cfg(feature = "mcp-code-mode")]
184pub use executor::McpExecutor;
185
186#[cfg(feature = "mcp-code-mode")]
187pub use code_executor::McpCodeExecutor;
188
189pub use token::{
190    canonicalize_code, compute_context_hash, hash_code, ApprovalToken, HmacTokenGenerator,
191    TokenGenerator, TokenSecret,
192};
193
194pub use types::{
195    CodeLanguage, CodeLocation, CodeType, Complexity, ExecutionError, PolicyViolation, RiskLevel,
196    SecurityAnalysis, SecurityIssue, SecurityIssueType, TokenError, UnifiedAction, ValidationError,
197    ValidationMetadata, ValidationResult,
198};
199
200pub use validation::{ValidationContext, ValidationPipeline};
201
202// Code Mode templates
203pub use templates::TemplateContext;
204
205// Code Mode handler trait and utilities
206pub use handler::{
207    format_error_response, format_execution_error, CodeModeHandler, CodeModeToolBuilder,
208    ExecuteCodeInput, ValidateCodeInput, ValidationResponse,
209};
210
211// Policy types re-exports
212pub use policy::{
213    get_baseline_policies, get_code_mode_schema_json, AuthorizationDecision, NoopPolicyEvaluator,
214    OperationEntity, PolicyEvaluationError, PolicyEvaluator, ServerConfigEntity,
215};
216
217#[cfg(feature = "openapi-code-mode")]
218pub use policy::{
219    get_openapi_baseline_policies, get_openapi_code_mode_schema_json, normalize_operation_format,
220    normalize_path_to_pattern, OpenAPIServerEntity, ScriptEntity,
221};
222
223#[cfg(feature = "sql-code-mode")]
224pub use policy::{
225    get_sql_baseline_policies, get_sql_code_mode_schema_json, SqlServerEntity, StatementEntity,
226};
227
228// Cedar policy evaluator
229#[cfg(feature = "cedar")]
230pub use policy::cedar::CedarPolicyEvaluator;
231
232// AVP (AWS Verified Permissions) policy evaluator
233#[cfg(feature = "avp")]
234pub use avp::{AvpClient, AvpConfig, AvpError, AvpPolicyEvaluator};
235
236// Schema Exposure Architecture types
237pub use schema_exposure::{
238    CodeModeExposurePolicy, DerivationMetadata, DerivationStats, DerivedSchema, ExposureMode,
239    FilterReason, FilteredOperation, GlobalBlocklist, McpExposurePolicy, MethodExposurePolicy,
240    Operation, OperationCategory, OperationDetails, OperationParameter, OperationRiskLevel,
241    SchemaDeriver, SchemaFormat, SchemaMetadata, SchemaSource, ToolExposurePolicy, ToolOverride,
242};