execute_python_code
Execute Python code in a sandboxed subprocess with access to all QWED SDK libraries.As of v0.2.0,
execute_python_code is the single MCP tool exposed by QWED-MCP. It replaces all previous verify_* tools to solve context bloat (RFC-9728 compatibility). See migration from v0.1.x below.Description
Theexecute_python_code tool runs arbitrary Python code in a subprocess with restricted environment variables. The subprocess has access to all installed QWED SDK packages (qwed_new, qwed_legal, qwed_finance, qwed_ucp, etc.), so LLMs can write verification scripts that import and call any QWED engine directly.
The tool captures stdout and stderr from the subprocess and returns them as text.
Parameters
Risk gateway pre-validation
All tool calls pass through theRiskBasedExecutionGateway before dispatch. The gateway normalizes arguments, verifies code safety, and enforces server policy. If the gateway blocks a request, the tool returns a structured BLOCKED response with a verification_id and error code instead of executing the code. See governance error codes for the full list.
Environment
The subprocess runs with a restricted environment. OnlyPATH, PYTHONPATH, and SYSTEMROOT (Windows) are forwarded. Secrets, API keys, and other environment variables are stripped.
The server admin must set QWED_MCP_TRUSTED_CODE_EXECUTION=true to enable this tool. When disabled, the tool returns a BLOCKED_ADMIN_POLICY response even if the code passes safety verification.
Execution limits
When the 1 MB output cap is reached, the subprocess is terminated and the output is truncated with a warning message.
Examples
Verify a math calculation
Verify a financial calculation
Check code for security vulnerabilities
Verify SQL safety
Verify a legal deadline
Verify AI content provenance
Run a heavy verification in the background
Error responses
verification_status
Check the execution status and output of a background verification task dispatched viaexecute_python_code with background=true.
Parameters
The risk gateway validates
job_id as a canonical UUID before dispatch. Non-UUID values are rejected with error code QWED-MCP-RISK-008.Response format
The response text depends on the job state:success, failed, cancelled, and timed_out are terminal states. Once a job reaches a terminal state, its result remains available until the 1-hour TTL expires.Example
Job lifecycle
- Background jobs expire after 1 hour (3600 seconds). Expired jobs are pruned automatically.
- A maximum of 5 jobs can run concurrently. Additional jobs are queued until a slot opens.
- Each background job is bounded by
QWED_MCP_BACKGROUND_TIMEOUT(default 120 s, max 600 s). Jobs that exceed this are killed and markedtimed_out. - Once a job completes (
success,failed,cancelled, ortimed_out), its result is available until the TTL expires.
Migrating from v0.1.x
In v0.1.x, QWED-MCP exposed individual tools (verify_math, verify_logic, verify_code, verify_sql, and others). In v0.2.0, all of these were consolidated into execute_python_code to reduce context bloat. The LLM now loads one tool schema instead of 14.
Before (v0.1.x)
After (v0.2.0)
Tool mapping
Use these QWED SDK imports in yourexecute_python_code scripts to replicate the previous tool behavior:
Deprecated tools (v0.1.x)
The following tools were available in v0.1.x and have been removed in v0.2.0. They are listed here for reference. Use execute_python_code with the corresponding SDK imports instead.verify_math (deprecated)
Verified mathematical calculations using the SymPy symbolic mathematics engine.verify_logic (deprecated)
Verified logical arguments using the Z3 SMT solver.verify_code (deprecated)
Checked code for security vulnerabilities using AST analysis.verify_sql (deprecated)
Detected SQL injection vulnerabilities and validated queries.verify_banking_compliance (deprecated)
Verified banking logic using QWED Finance Guard.verify_commerce_transaction (deprecated)
Verified e-commerce transactions using QWED UCP.verify_legal_deadline (deprecated)
Verified contract deadlines using LegalGuard.verify_legal_citation (deprecated)
Verified legal citation format and validity.verify_legal_liability (deprecated)
Verified liability cap calculations.verify_system_command (deprecated)
Verified shell commands for security risks.verify_file_path (deprecated)
Verified file paths are within allowed sandbox directories.verify_config_secrets (deprecated)
Scanned configuration JSON for exposed secrets.AIBOMGenerator (observability)
Generate an AI Bill of Materials (AI-BOM) manifest for visibility into your agent supply chain. This is useful for AI-SPM compliance auditing — tracking which models, verification engines, and MCP tools were used in a given session.Description
TheAIBOMGenerator produces a JSON manifest listing all components involved in an AI pipeline run. Each manifest includes a deterministic manifest_hash (SHA-256) so you can verify that two runs used the same component stack.
Usage
Parameters
Manifest fields
The
manifest_hash is deterministic for identical inputs — the timestamp is excluded from the hash computation so that two manifests with the same components always produce the same hash.SkillProvenanceGuard (security)
Verify MCP skill manifests before allowing dynamic tool loading. Protects against skill marketplace poisoning attacks where malicious agents upload trojanized skills to registries and inflate download counts.Description
SkillProvenanceGuard performs deterministic provenance verification on skill manifests. When the QWED_SKILL_MANIFEST environment variable points to a JSON manifest file, the MCP server validates it at startup and refuses to start if verification fails.
You can also use SkillProvenanceGuard directly in your own code to vet skills before loading them.
Usage
Constructor parameters
Strict allowlist of registry domains. When set, only skills from these registries are accepted. When
None, the default blocklist is used instead.Additional source URL domains to trust, merged with the built-in trusted list (
github.com, gitlab.com, bitbucket.org, pypi.org, npmjs.com, qwedai.com).Whether to enforce cryptographic digest presence in the manifest.
Manifest fields
Verification checks
The guard runs five checks on every manifest:
Additionally, manifest values (excluding metadata fields like
name, description, source_url) are scanned for suspicious code patterns such as eval(), exec(), os.system(), and credential access attempts.
Response format
Server-level validation
When theQWED_SKILL_MANIFEST environment variable is set, the MCP server validates the manifest at startup:
RiskBasedExecutionGateway (governance)
Verification-first governance gateway that validates all MCP tool calls before dispatch. Every call toexecute_python_code or verification_status passes through this gateway automatically.
Description
RiskBasedExecutionGateway enforces deterministic policy checks on every tool invocation. It normalizes arguments, runs code safety analysis, enforces admin policy, and returns a structured governance decision. If the gateway blocks a request, the MCP server returns the decision directly without executing the tool.
The gateway is instantiated automatically when the MCP server starts — you do not need to configure it separately.
How it works
- Policy lookup — The gateway checks the tool name against its internal policy table. Unknown tools are blocked immediately (
QWED-MCP-RISK-001). - Argument validation — Required arguments are checked for type and presence. For
execute_python_code, thecodeparameter must be a non-empty string andbackgroundmust be a boolean. - Code safety verification — For
execute_python_code, the gateway runs AST-based analysis to detect dangerous patterns (e.g.,eval,exec,compile,open,__import__,os.system,os.popen,subprocess,pickle.loads,marshal.loads). The analyzer resolves import aliases andfrom ... importrenames to catch obfuscated calls such asimport os as x; x.system(...)orfrom os import popen as op; op(...). Raw pattern-based checks are used as a fallback only when AST parsing fails. - Admin policy enforcement — Even if code passes safety verification, the gateway checks
QWED_MCP_TRUSTED_CODE_EXECUTION. If not enabled, the request is blocked withBLOCKED_ADMIN_POLICY. - UUID validation — For
verification_status, thejob_idmust be a valid canonical UUID.
Usage
The gateway is used internally by the MCP server. You can also use it directly in custom integrations:Decision response fields
Governance error codes
Tool policies
The gateway defines built-in policies for each registered tool:
Tools not in this table are blocked by default with
QWED-MCP-RISK-001.
The
verification_id is a context-bound SHA-256 hash. In addition to the tool name and normalized arguments, the hash input includes a random nonce, a wall-clock timestamp, and a per-process server_instance_id generated when the gateway is constructed. Two identical requests always produce different verification_id values, which prevents replay attacks and stale-cache correlation. Treat each verification_id as a single-use, temporally-bound artifact when auditing.Error handling
All tool responses includestdout, stderr, and a return code summary. A non-zero return code indicates the script raised an exception or exited with an error.