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// High-level CodeExecutor trait (always available, no feature gate) (D-04)
119pub use code_executor::CodeExecutor;
120
121// Re-export public types
122pub use config::{resolve_server_id_from_env, CodeModeConfig};
123
124pub use explanation::{ExplanationGenerator, TemplateExplanationGenerator};
125
126pub use graphql::{GraphQLOperationType, GraphQLQueryInfo, GraphQLValidator};
127
128// JavaScript/OpenAPI Code Mode exports
129#[cfg(feature = "openapi-code-mode")]
130pub use javascript::{
131    ApiCall, HttpMethod, JavaScriptCodeInfo, JavaScriptValidator, OutputDeclaration,
132    SafetyViolation, SafetyViolationType,
133};
134
135// SQL Code Mode exports
136#[cfg(feature = "sql-code-mode")]
137pub use sql::{SqlStatementInfo, SqlStatementType, SqlValidator};
138
139// JavaScript execution runtime exports
140#[cfg(feature = "js-runtime")]
141pub use executor::{
142    filter_blocked_fields, find_blocked_fields_in_output, ApiCallLog, ArrayMethodCall,
143    BinaryOperator, BuiltinFunction, CompileError, ExecutionConfig, ExecutionPlan, ExecutionResult,
144    HttpExecutor, JsExecutor, MockExecutionMode, MockHttpExecutor, MockedCall, PathPart,
145    PathTemplate, PlanCompiler, PlanExecutor, PlanMetadata, PlanStep, SdkExecutor, UnaryOperator,
146    ValueExpr,
147};
148
149// Standard CodeExecutor adapters (bridge low-level traits to derive-macro-compatible API)
150#[cfg(feature = "js-runtime")]
151pub use code_executor::{JsCodeExecutor, SdkCodeExecutor};
152
153// MCP Code Mode executor
154#[cfg(feature = "mcp-code-mode")]
155pub use executor::McpExecutor;
156
157#[cfg(feature = "mcp-code-mode")]
158pub use code_executor::McpCodeExecutor;
159
160pub use token::{
161    canonicalize_code, compute_context_hash, hash_code, ApprovalToken, HmacTokenGenerator,
162    TokenGenerator, TokenSecret,
163};
164
165pub use types::{
166    CodeLanguage, CodeLocation, CodeType, Complexity, ExecutionError, PolicyViolation, RiskLevel,
167    SecurityAnalysis, SecurityIssue, SecurityIssueType, TokenError, UnifiedAction, ValidationError,
168    ValidationMetadata, ValidationResult,
169};
170
171pub use validation::{ValidationContext, ValidationPipeline};
172
173// Code Mode templates
174pub use templates::TemplateContext;
175
176// Code Mode handler trait and utilities
177pub use handler::{
178    format_error_response, format_execution_error, CodeModeHandler, CodeModeToolBuilder,
179    ExecuteCodeInput, ValidateCodeInput, ValidationResponse,
180};
181
182// Policy types re-exports
183pub use policy::{
184    get_baseline_policies, get_code_mode_schema_json, AuthorizationDecision, NoopPolicyEvaluator,
185    OperationEntity, PolicyEvaluationError, PolicyEvaluator, ServerConfigEntity,
186};
187
188#[cfg(feature = "openapi-code-mode")]
189pub use policy::{
190    get_openapi_baseline_policies, get_openapi_code_mode_schema_json, normalize_operation_format,
191    normalize_path_to_pattern, OpenAPIServerEntity, ScriptEntity,
192};
193
194#[cfg(feature = "sql-code-mode")]
195pub use policy::{
196    get_sql_baseline_policies, get_sql_code_mode_schema_json, SqlServerEntity, StatementEntity,
197};
198
199// Cedar policy evaluator
200#[cfg(feature = "cedar")]
201pub use policy::cedar::CedarPolicyEvaluator;
202
203// AVP (AWS Verified Permissions) policy evaluator
204#[cfg(feature = "avp")]
205pub use avp::{AvpClient, AvpConfig, AvpError, AvpPolicyEvaluator};
206
207// Schema Exposure Architecture types
208pub use schema_exposure::{
209    CodeModeExposurePolicy, DerivationMetadata, DerivationStats, DerivedSchema, ExposureMode,
210    FilterReason, FilteredOperation, GlobalBlocklist, McpExposurePolicy, MethodExposurePolicy,
211    Operation, OperationCategory, OperationDetails, OperationParameter, OperationRiskLevel,
212    SchemaDeriver, SchemaFormat, SchemaMetadata, SchemaSource, ToolExposurePolicy, ToolOverride,
213};