Skip to main content

execute_python_code

Execute Python code in a subprocess after an allowlist admission check.
Admitted code runs with the server’s privileges. The subprocess is not a sandbox: it only gets a restricted set of environment variables. Code execution is off until the server admin sets QWED_MCP_TRUSTED_CODE_EXECUTION=true. Enable it only where you trust the inputs.
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

The execute_python_code tool parses the code and runs it in a subprocess only when it passes the allowlist admission check. Admitted code can use computation-only standard-library modules, such as decimal, fractions, math, statistics and itertools. From v0.3.0, it can’t import third-party packages, including SymPy and the QWED SDK packages (qwed_new, qwed_legal, qwed_finance, qwed_ucp). The tool captures stdout and stderr from the subprocess and returns them as text.

What code is admitted

Changed in v0.3.0. Earlier versions refused a list of dangerous names and ran everything else.
Before any code runs, the server parses it and admits it only when every module, builtin and attribute it uses is on an allowlist:
  • Modules: computation-only standard-library modules, such as math, cmath, decimal, fractions, statistics, itertools, functools, collections, json, re, datetime, hashlib and random, and in each only the listed names. Modules that reach files, the network, processes, the environment or the import system (os, sys, subprocess, socket, pathlib, importlib, ctypes and others) are refused. So is every third-party package, QWED SDK packages included. A module can be used only as module.name with a listed name, never as a value.
  • Builtins: only builtins that compute. open, eval, exec, compile, __import__, getattr, vars, globals, type, input, breakpoint and the other builtins that aren’t listed are refused wherever they appear, so they can’t be rebound or passed on.
  • Attributes: no special or private attribute (__x__, _x) apart from reading __init__ and __name__, no frame, code-object or traceback attribute, and str.format only on a string literal whose fields read no attribute.
  • Source encoding: a coding declaration other than UTF-8 is refused. The server writes the script as UTF-8, so the code that runs is the code that was checked.
Refused code never runs. The response lists each reason, with the line number where one applies, for example Module 'os' is not admitted (line 1). Admission is a static check of what the code can reach. It is not a proof that the code is correct, and it does not limit resource use: the execution timeouts limit run time, and nothing limits memory. The output of admitted code comes from that code, so treat it as untrusted data.

Parameters

Risk gateway pre-validation

All tool calls pass through the RiskBasedExecutionGateway before dispatch. The gateway normalizes arguments, runs the allowlist admission check, 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. Only PATH, PYTHONPATH, and SYSTEMROOT (Windows) are forwarded. Secrets, API keys, and other environment variables are stripped. From v0.3.0, the server starts the subprocess in Python’s isolated mode (python -I). The script’s directory, a shared temporary directory, is not on the import path, so a file placed there can’t stand in for an admitted module. Isolated mode also ignores PYTHON* variables, so the forwarded PYTHONPATH has no effect. 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 the admission check. The admission check runs first, so refused code is reported as refused whether or not execution is enabled.

Execution limits

When the 1 MB output cap is reached, the subprocess is terminated and the output is truncated with a warning message.
Background workers enforce a bounded timeout to prevent denial-of-service via unbounded execution. Jobs that exceed the timeout are killed and transition to the terminal timed_out status. Set QWED_MCP_BACKGROUND_TIMEOUT (seconds) to tune this; values above 600 are clamped to the ceiling, and non-numeric or non-positive values fall back to the 120 s default.

Examples

Verify a math calculation

Check that x = 3 and x = -5 solve x² + 2x - 15 = 0 with exact fractions:
Response:

Verify a financial calculation

Response:

Code that is refused

Code outside the allowlist is refused before it runs:
Response:
Imports of QWED SDK packages are refused the same way, for example Module 'qwed_legal' is not admitted (line 1). To run a QWED guard, call it from your own Python code instead of through execute_python_code.

Run a heavy verification in the background

Response:
Then poll for results:

Error responses


verification_status

Check the execution status and output of a background verification task dispatched via execute_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

Response (while running):
Response (completed):

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 marked timed_out.
  • Once a job completes (success, failed, cancelled, or timed_out), its result is available until the TTL expires.
Background job state is held in memory on the MCP server. If the server restarts, all pending and completed jobs are lost.

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.1, 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.1)

Replacing the removed tools

In v0.2.x, a script could import a QWED SDK package to replace a removed tool, for example from qwed_legal import DeadlineGuard. From v0.3.0, execute_python_code refuses every third-party import, QWED SDK packages and SymPy included (see What code is admitted). Scripts can still compute a check with the admitted standard-library modules, such as decimal for money, fractions for exact arithmetic and itertools.product for checking a propositional argument over every truth assignment. To run a QWED guard or engine, call its package from your own Python code.
A BLOCKED response with error code QWED-MCP-RISK-001 in Claude Desktop means the LLM is trying to call a tool that is not in the governance policy table. This typically happens with removed v0.1.x tools. Tell Claude: “The verify_* tools have been removed. Use execute_python_code to write and run a Python verification script.”

Deprecated tools (v0.1.x)

The following tools were available in v0.1.x and were removed in v0.2.1. They are listed here for reference. Use execute_python_code instead. See Replacing the removed tools.

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. Verified contract deadlines using LegalGuard. Verified legal citation format and validity. 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

The AIBOMGenerator 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)

Check MCP skill manifests before allowing dynamic tool loading, against skill marketplace poisoning where malicious agents upload trojanized skills to registries.

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. The registry, source URL and digest are claims the manifest makes about itself. The guard checks those claims against its lists, and the digest against the skill’s bytes when you pass them. It does not establish where the manifest came from.

Usage

Pass the skill’s bytes as content to check the digest against them. Without content, the digest is checked for form only, and a manifest that passes every other check gets status "TRUSTED_DIGEST_UNVERIFIED" with digest_verified False. The digest in this example is the SHA-256 of empty content.
Changed in v0.3.0: content, TRUSTED_DIGEST_UNVERIFIED, digest_verified and advisories are new, and TRUSTED now means the digest matched the content.

Constructor parameters

set[str] | None
default:"None"
Allowlist of registry domains, matched exactly. When None, the allowlist is the built-in trusted domains (github.com, gitlab.com, bitbucket.org, pypi.org, npmjs.com), and a registry not on it is refused. Before v0.3.0, None meant a blocklist that let any unlisted registry through.
set[str] | None
default:"None"
Additional source URL domains to trust, merged with the built-in trusted list (github.com, gitlab.com, bitbucket.org, pypi.org, npmjs.com). qwed-mcp 0.2.3 removed qwedai.com from the built-in list (QWED-AI/qwed-mcp#72). QWED no longer uses that domain, and it lapses on 9 December 2026. qwed-mcp 0.2.2 and earlier still trust it, so upgrade to 0.2.3 or later. To trust any other domain, pass it in trusted_domains.
bool
default:"True"
Whether to require a digest in the manifest. With False, a manifest without a digest can pass, but digest_verified stays False.

Manifest fields

Verification checks

The guard runs these checks on every manifest: Manifest values are also scanned for suspicious patterns. Every field, including description and source_url, is scanned for code-execution patterns such as eval(), exec() and os.system(). Fields other than the identity and free-text fields (name, description, source_url, registry, author, license, version, digest) are also scanned for secret-name keywords (credentials, api_key, secret_key). The download count comes from the registry being checked, so it is not a security signal. Notes about it (low, round, missing or malformed counts) go in advisories and never decide the result. Before v0.3.0, a count below 10 or divisible by 1,000 blocked the skill.

Response format

Server-level validation

When the QWED_SKILL_MANIFEST environment variable is set, the MCP server validates the manifest at startup:
If validation fails, the server logs the error and exits immediately. Otherwise it logs the provenance status and any advisories. The startup check has the manifest only, not the skill’s content, so a manifest that passes reports TRUSTED_DIGEST_UNVERIFIED: its digest was checked for form, not against the skill.
The startup check builds the guard with its defaults, so from v0.3.0 a manifest whose registry is not one of the built-in trusted domains stops the server from starting. To vet skills from another registry, call SkillProvenanceGuard in your own code with that registry in trusted_registries.

RiskBasedExecutionGateway (governance)

Verification-first governance gateway that validates all MCP tool calls before dispatch. Every call to execute_python_code or verification_status passes through this gateway automatically.

Description

RiskBasedExecutionGateway enforces deterministic policy checks on every tool invocation. It normalizes arguments, runs the allowlist admission check on Python code, 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

  1. Policy lookup — The gateway checks the tool name against its internal policy table. Unknown tools are blocked immediately (QWED-MCP-RISK-001).
  2. Argument validation — Required arguments are checked for type and presence. For execute_python_code, the code parameter must be a non-empty string and background must be a boolean.
  3. Allowlist admission — For execute_python_code, the gateway parses the code and admits it only when every module, builtin and attribute it uses is on the allowlist (see What code is admitted). Code that doesn’t parse, or that has no statements, is refused. Before v0.3.0, this step looked for a list of dangerous patterns instead.
  4. Admin policy enforcement — Even if code is admitted, the gateway checks QWED_MCP_TRUSTED_CODE_EXECUTION. If not enabled, the request is blocked with BLOCKED_ADMIN_POLICY.
  5. UUID validation — For verification_status, the job_id must 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 include stdout, stderr, and a return code summary. A non-zero return code indicates the script raised an exception or exited with an error.

Common errors