Repository navigation
fix(agents): gate repository tool loading to first-party modules (CVE-2026-92206 carrier) - #9666
Freedomn (freedom2132) wants to merge 5 commits into
Conversation
Extend the same gate pattern used by _resolve_tool_dict (crewAIInc#8623, SECT-601) to load_agent_from_repository: tool modules from agent repository definitions must be first-party (crewai.*/crewai_tools.*) or explicitly opted in via CREWAI_DESERIALIZE_CALLBACKS=1. Addresses the CVE-2026-92206 carrier (ungated importlib/getattr/kwargs reflection on repository responses).
Strix Security ReviewWarning This pull request has 4 commits after the last Strix review ( To fix before merging (2)
PR summary: The PR gates tool loading in `load_agent_from_repository` so that tool modules named by an agent-repository API response must be first-party (`crewai.*` / `crewai_tools.*`) unless `CREWAI_DESERIALIZE_CALLBACKS=1` is set, mirroring the existing checkpoint gate. It touches only the `tools` branch of that loop in `lib/crewai/src/crewai/utilities/agent_utils.py`. Review summaryThis PR adds a first-party module-prefix allowlist in front of the repository tool-loading loop in Ruled out (6)
Fixed the findings? re-run the review, or tag Review 1 on this PR · Reviewed by Strix |
…check, mcps/memory gates Per review feedback on the first commit: - accept the bare package names crewai / crewai_tools (not only dotted submodules) so published repository tools load without the opt-in - require the resolved attribute to be a BaseTool subclass before instantiation, even under CREWAI_DESERIALIZE_CALLBACKS=1 (mirrors the checkpoint behavior that rejects non-tool callables like os.system) - gate repository-supplied inline MCP server definitions (non-string entries) and memory configuration (embedder endpoint / storage path) behind the same opt-in
| tool_class = getattr(module, tool["name"]) | ||
|
|
||
| tool_value = tool_class(**tool["init_params"]) |
There was a problem hiding this comment.
🟡 Repository tool loading: new first-party module gate leaves attacker-controlled attribute name and constructor arguments (unsafe reflection)
Severity: MEDIUM
TL;DR: In load_agent_from_repository the new check gates only tool["module"]; attacker-supplied name/init_params still reach getattr plus a call, so import_utils.require imports any module on request.
Impact: Anyone controlling an agent definition consumed by the loader can still make a user's process import a module of their choosing and call any first-party helper with chosen arguments, so the code-execution carrier this PR claims to close stays reachable.
Root cause:
- The fix assumes the module string is the only attacker-controlled reflection input, so a prefix match on it is treated as making the getattr-and-call that follows safe; that ungated sink itself predates the PR.
tool["name"]andtool["init_params"]stay unrestricted after the gate, so any callable in anycrewai.*module is invoked with attacker-chosen keyword arguments.- First-party helpers re-enter
importlib.import_moduleon their own argument (import_utils.require,validate_import_path,declarative_refs.resolve_ref), so namingcrewai.utilities.import_utils+requirestill imports an attacker-chosen module; the sibling_resolve_tool_dictavoids this by restricting the resolved object to BaseTool subclasses.
| tool_class = getattr(module, tool["name"]) | |
| tool_value = tool_class(**tool["init_params"]) | |
| tool_class = getattr(module, tool["name"]) | |
| if not ( | |
| isinstance(tool_class, type) | |
| and issubclass(tool_class, BaseTool) | |
| ): | |
| raise AgentRepositoryError( | |
| f"Tool '{tool['name']}' in module '{module_name}' is " | |
| "not a BaseTool subclass" | |
| ) | |
| tool_value = tool_class(**tool["init_params"]) |
Prompt to fix with AI
This is a security vulnerability found during a code review.
Vulnerability: Repository tool loading: new first-party module gate leaves attacker-controlled attribute name and constructor arguments (unsafe reflection)
Severity: MEDIUM
CWE: CWE-470
**TL;DR:** In `load_agent_from_repository` the new check gates only `tool["module"]`; attacker-supplied `name`/`init_params` still reach `getattr` plus a call, so `import_utils.require` imports any module on request.
**Impact:** Anyone controlling an agent definition consumed by the loader can still make a user's process import a module of their choosing and call any first-party helper with chosen arguments, so the code-execution carrier this PR claims to close stays reachable.
**Root cause:**
- The fix assumes the module string is the only attacker-controlled reflection input, so a prefix match on it is treated as making the getattr-and-call that follows safe; that ungated sink itself predates the PR.
- `tool["name"]` and `tool["init_params"]` stay unrestricted after the gate, so any callable in any `crewai.*` module is invoked with attacker-chosen keyword arguments.
- First-party helpers re-enter `importlib.import_module` on their own argument (`import_utils.require`, `validate_import_path`, `declarative_refs.resolve_ref`), so naming `crewai.utilities.import_utils` + `require` still imports an attacker-chosen module; the sibling `_resolve_tool_dict` avoids this by restricting the resolved object to BaseTool subclasses.
Location: lib/crewai/src/crewai/utilities/agent_utils.py:1215-1217
Context: Primary fix: restrict the resolved attribute to a BaseTool subclass before calling it
```
// Before:
tool_class = getattr(module, tool["name"])
tool_value = tool_class(**tool["init_params"])
// After:
tool_class = getattr(module, tool["name"])
if not (
isinstance(tool_class, type)
and issubclass(tool_class, BaseTool)
):
raise AgentRepositoryError(
f"Tool '{tool['name']}' in module '{module_name}' is "
"not a BaseTool subclass"
)
tool_value = tool_class(**tool["init_params"])
```
Location: lib/crewai/src/crewai/utilities/agent_utils.py:1204-1213
Context: Context: the new gate covers only the module name
```
if not (
module_name.startswith(_FIRST_PARTY_TOOL_PACKAGES)
or _trusted_deserialize()
):
raise AgentRepositoryError(
f"Tool module '{module_name}' is not a first-party CrewAI "
"package; refusing to import third-party modules from agent "
"repository definitions. Set CREWAI_DESERIALIZE_CALLBACKS=1 "
"to allow trusted third-party modules."
)
```
How to fix:
Restrict the object resolved by `getattr(module, tool["name"])` before instantiating it: require a `type` that is a `BaseTool` subclass (or a `_TOOL_TYPE_REGISTRY` lookup), as `_resolve_tool_dict` and `_resolve_tool_class` already do. Reject non-string `module` values explicitly instead of relying on the `startswith` call to raise, and treat the whole `tools` entry as untrusted reflection rather than gating only the module path.
Please fix this vulnerability. If you propose a fix, make it concise and minimal.React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss the finding.
| if not ( | ||
| module_name.startswith(_FIRST_PARTY_TOOL_PACKAGES) | ||
| or _trusted_deserialize() | ||
| ): | ||
| raise AgentRepositoryError( | ||
| f"Tool module '{module_name}' is not a first-party CrewAI " | ||
| "package; refusing to import third-party modules from agent " | ||
| "repository definitions. Set CREWAI_DESERIALIZE_CALLBACKS=1 " | ||
| "to allow trusted third-party modules." | ||
| ) |
There was a problem hiding this comment.
Context: the new gate covers only the module name
| "to allow trusted third-party modules." | ||
| ) | ||
| module = importlib.import_module(module_name) | ||
| tool_class = getattr(module, tool["name"]) |
There was a problem hiding this comment.
🟠 First-party tool gate is bypassable: repository-supplied mcps stdio config still spawns an arbitrary local process
Severity: HIGH
TL;DR: The new first-party module gate in load_agent_from_repository covers only the tools key; the same response can set mcps, which coerces to MCPServerStdio and spawns an arbitrary command at kickoff.
Impact: Whoever controls the agent-repository response gets arbitrary code execution on any developer who loads that agent: {"command": "sh", "args": ["-c", "..."]} is spawned with attacker-chosen argv and environment, without the CREWAI_DESERIALIZE_CALLBACKS=1 opt-in the new gate requires for tools.
Root cause:
- The loader treats the repository JSON as a bag of Agent fields and copies every non-null key verbatim, gating only the one key it knows is dangerous, so any other field that reaches a code-loading sink stays open.
attributes[key] = value(agent_utils.py:1228-1229) passes the response'smcpsvalue straight intoAgent.mcps: list[str | MCPServerConfig](base_agent.py:381), where pydantic coerces a plain dict intoMCPServerStdioandvalidate_mcpsonly type-checks it.- At kickoff
_prepare_kickoffcallsget_mcp_tools(self.mcps)->MCPToolResolver._create_transport, which buildsStdioTransport(command, args, env)and spawns the process, so the carrier the PR closes fortoolsremains reachable one key over (this path predates the PR but sits on the same untrusted-response boundary it hardens).
Prompt to fix with AI
This is a security vulnerability found during a code review.
Vulnerability: First-party tool gate is bypassable: repository-supplied `mcps` stdio config still spawns an arbitrary local process
Severity: HIGH
**TL;DR:** The new first-party module gate in `load_agent_from_repository` covers only the `tools` key; the same response can set `mcps`, which coerces to `MCPServerStdio` and spawns an arbitrary command at kickoff.
**Impact:** Whoever controls the agent-repository response gets arbitrary code execution on any developer who loads that agent: `{"command": "sh", "args": ["-c", "..."]}` is spawned with attacker-chosen argv and environment, without the `CREWAI_DESERIALIZE_CALLBACKS=1` opt-in the new gate requires for tools.
**Root cause:**
- The loader treats the repository JSON as a bag of Agent fields and copies every non-null key verbatim, gating only the one key it knows is dangerous, so any other field that reaches a code-loading sink stays open.
- `attributes[key] = value` (agent_utils.py:1228-1229) passes the response's `mcps` value straight into `Agent.mcps: list[str | MCPServerConfig]` (base_agent.py:381), where pydantic coerces a plain dict into `MCPServerStdio` and `validate_mcps` only type-checks it.
- At kickoff `_prepare_kickoff` calls `get_mcp_tools(self.mcps)` -> `MCPToolResolver._create_transport`, which builds `StdioTransport(command, args, env)` and spawns the process, so the carrier the PR closes for `tools` remains reachable one key over (this path predates the PR but sits on the same untrusted-response boundary it hardens).
Location: lib/crewai/src/crewai/utilities/agent_utils.py:1228-1229
Context: Primary fix: gate repository-supplied structured MCP configs like the tools loop
```
// Before:
else:
attributes[key] = value
// After:
elif key == "mcps" and not _trusted_deserialize():
if any(isinstance(mcp, dict) for mcp in value):
raise AgentRepositoryError(
"Structured MCP server configurations are not accepted from agent "
"repository definitions; refusing to start repository-supplied "
"processes. Set CREWAI_DESERIALIZE_CALLBACKS=1 to allow trusted "
"configurations."
)
attributes[key] = value
else:
attributes[key] = value
```
Location: lib/crewai/src/crewai/utilities/agent_utils.py:1199-1215
Context: Context: the added gate applies only inside the tools branch
```
elif key == "tools":
attributes[key] = []
for tool in value:
try:
module_name = tool["module"]
if not (
module_name.startswith(_FIRST_PARTY_TOOL_PACKAGES)
or _trusted_deserialize()
):
```
How to fix:
Gate `mcps` alongside `tools` in the repository loader: reject structured MCP server configs (any object entry that can carry a `command`) coming from the repository response unless `CREWAI_DESERIALIZE_CALLBACKS=1`, allowing only `https://` URLs and bare slugs by default. Prefer replacing the copy-every-key mapping with an explicit allow-list of repository-safe Agent fields, so future fields that reach dynamic imports, process spawns or file access are not silently exposed to the response.
Please fix this vulnerability. If you propose a fix, make it concise and minimal.React 👍 / 👎 to tune Strix for this repo. A repo collaborator (or the PR author) can resolve this thread to dismiss the finding.
|
Addressing the review findings in 886e474: Cursor HIGH (gate design):
Strix HIGH ×2 (ungated sibling keys):
The longer-term suggestion (explicit allowlist of accepted agent attributes instead of the copy loop) is noted for maintainers — that's a larger refactor than this PR should carry, but the Both bots' reviews were genuinely useful — thanks. |
Per the Cursor review of the gate: importlib.import_module("crewai.cli.cli")
installs the _ShimFinder and returns the crewai_cli.cli module, so a
"crewai.*" import name can resolve to another distribution. After import,
the module's real top-level package must be crewai or crewai_tools, else
the repository tool definition is refused.
|
Re: the Cursor review — the described chain targets the first commit (the hunk is marked outdated); as of 886e474 the The import-shim residual it correctly points at is real, though, and is now closed in the follow-up commit: Remaining declared residual: the import itself can have side effects (e.g. |
Nick (surlymochan)
left a comment
There was a problem hiding this comment.
Verified the gate against the local checkout. _FIRST_PARTY_TOOL_PACKAGES is ("crewai.", "crewai_tools.") in crewai/tools/base_tool.py, so the startswith check rejects lookalike packages, and _trusted_deserialize() reads CREWAI_DESERIALIZE_CALLBACKS as the error message says. The same gate pattern is already used at base_tool.py:70, so this is consistent with the existing approach.
One thing I checked: the new refusals raise inside the try, so the existing except re-wraps them as Tool X could not be loaded: <refusal>. The full reason still surfaces in the message, so that reads fine.
One question: this PR adds no test pinning the refusals. test_agent_from_repository_with_invalid_tools already covers invalid tools in this file, so would it make sense to extend it (or add a case) for a third-party module, an inline MCP definition, and a dict memory config?
- refuse repository-supplied dotted import strings for ImportString-typed tool fields (custom_embedding_fn) and package-name fields later passed to import_module (qdrant_package / db2_package / db2_dbi_package) unless CREWAI_DESERIALIZE_CALLBACKS=1 — closes the chain where a repository entry binds e.g. os.system into a first-party tool - extend test_agent.py with six refusal tests: third-party module, non-BaseTool callable, import shim, ImportString params, inline MCP definition, dict memory config (per review request)
|
Nick (@surlymochan) thanks for the review — tests added in the latest commit, extending
The last two rounds of bot review also drove two more gates in the same commit:
Happy to fold the six tests into fewer cases or adjust naming/asserts to match the suite's conventions. |
| ) from e | ||
| elif key == "mcps": | ||
| entries = value if isinstance(value, list) else [value] | ||
| if not _trusted_deserialize() and any( |
There was a problem hiding this comment.
🔒 Agentic Security Review
Severity: MEDIUM
Description: With CREWAI_DESERIALIZE_CALLBACKS unset, load_agent_from_repository keeps every string in a repository agent's mcps list. Agent.validate_mcps accepts https:// strings as external MCP servers, and both Agent kickoff and Crew task setup call get_mcp_tools with no further host allowlist. That opens the URL, loads the remote tool schemas into the agent prompt, and registers wrappers whose later calls send the model's arguments to that host.
Impact: An authenticated organization member who can publish the agent record returned by PlusAPI.get_agent can set mcps to an attacker HTTPS URL. The next victim Agent(from_repository=...) kickoff or crew run, under the default unset opt-in, connects from the victim process, installs attacker-controlled tool descriptions into the prompt, and sends later tool-call arguments to the attacker. Repository MCP config is the lower-trust boundary this change is closing; the string form still reaches the external MCP sink the refusal says it is blocking. Discovery itself sends MCP initialize and list_tools, and the platform API token is not attached on that request.
Remediation: When _trusted_deserialize() is false, accept only AMP slug strings that match the existing slug form (optional crewai-amp: prefix, name, optional #tool) and raise AgentRepositoryError for https:// URLs and any other non-slug string. Leave URL strings and inline server objects behind CREWAI_DESERIALIZE_CALLBACKS.
| fdef = fields.get(field_name) | ||
| is_import_string = False | ||
| if fdef is not None and fdef.annotation is not None: | ||
| annotations = [fdef.annotation, *get_args(fdef.annotation)] |
There was a problem hiding this comment.
🔒 Agentic Security Review
Severity: HIGH
Description: The new repository import-string refusal does not recognize the production annotation ImportString[Callable[[str], list[float]]] | None. A repository agent can still pass a dotted path as custom_embedding_fn on QdrantVectorSearchTool or DB2VectorSearchTool, and Pydantic's ImportString validator imports that module while the tool is constructed.
Impact: Agent(from_repository=...) treats Plus API agent JSON as untrusted unless CREWAI_DESERIALIZE_CALLBACKS is set, but that opt-in is skipped when detection fails. Any publisher who can write an agent the victim loads (same org or other handle the victim's token can read) can name a crewai_tools BaseTool and set custom_embedding_fn to a dotted path such as os.system. With crewai_tools installed, DB2VectorSearchTool builds successfully from a dummy connection_string: importlib runs at construction, the callable is stored, and _generate_embedding invokes it with the search string before any DB2 connection. That is in-process code execution in the loader, which typically holds model and API credentials. The new test only covers bare ImportString | None, the one shape the identity check matches, so this hole is untested.
Remediation: Walk the full annotation tree, including Annotated metadata nested inside unions and FieldInfo.metadata, and treat both the ImportString class and ImportString() instances as import strings. Refuse every repository string that will reach an ImportString validator or importlib, not only the three package field names. Add a regression that instantiates the real QdrantVectorSearchTool and DB2VectorSearchTool annotations (ImportString[Callable[[str], list[float]]] | None), not a bare ImportString | None stand-in, and assert the dotted path is rejected before tool construction.
| tool_class, init_params, tool["name"] | ||
| ) | ||
|
|
||
| tool_value = tool_class(**init_params) |
There was a problem hiding this comment.
🔒 Agentic Security Review
Severity: MEDIUM
Description: Repository agent tool entries can still construct crewai.tools.mcp_tool_wrapper.MCPToolWrapper when CREWAI_DESERIALIZE_CALLBACKS is unset. The class is a first-party BaseTool, and _refuse_repository_import_strings only inspects string init values, so a nested mcp_server_params dict is passed straight into the constructor. That constructor stores an arbitrary url plus the publisher-supplied description and args schema. The tool is appended to Agent.tools and offered to the model. On invocation, _execute_tool opens streamablehttp_client to mcp_server_params['url'] and forwards the tool arguments. The new mcps refusal never sees this path. validate_mcps only allows https:// string refs or platform slugs; this path also accepts http and other URLs, including localhost and link-local addresses, and it registers the tool without a discovery handshake.
Impact: A publisher of the org agent returned by PlusAPI.get_agent can make another member's crew process open an MCP session to a URL the new repository policy does not allow, including plain HTTP, localhost, and link-local metadata, and send the model-supplied tool arguments there. That is a real egress and internal-request side effect from repository JSON the PR treats as untrusted. HTTPS argument exfil to an attacker-controlled MCP server is already possible through mcps string refs, which this PR still allows and which build the same MCPToolWrapper after discovery. The incremental break is the missing scheme and host gate and the forged tool that never passes validate_mcps. This path does not restore stdio process execution: MCPNativeTool requires a live client_factory and cannot be built from the JSON dict.
Remediation: When CREWAI_DESERIALIZE_CALLBACKS is unset, refuse repository instantiation of MCP client tools (at least MCPToolWrapper). Do not forward init_params that carry a url or transport dict into first-party tools. Keep remote MCP binding on the mcps field so it still goes through validate_mcps (https or platform slug only).
Per review on crewAIInc#9665: the loop wrapped every failure as "Tool X could not be loaded", so a deliberate refusal read like a broken repository entry. AgentRepositoryError now passes through the except unchanged; load failures keep the existing wrapping.
Nick (surlymochan)
left a comment
There was a problem hiding this comment.
Reviewed the repository tool-loading gate against #9665. The layering is sound: the first-party check gates the import, the post-import check (resolved module's top-level package must be crewai / crewai_tools) closes the prefix-collision hole even if _FIRST_PARTY_TOOL_PACKAGES ever contains a bare prefix without a trailing dot (e.g. a hypothetical 'crewai_tools_evil' would pass startswith but fail the resolved-name check), the BaseTool-subclass check blocks instantiating arbitrary callables, and _refuse_repository_import_strings covers ImportString fields including Optional/Union forms via get_args. The added 'except AgentRepositoryError: raise' is important — without it a deliberate gate refusal would be re-wrapped as a generic 'could not be loaded' error and look like a broken entry.
One thing I checked for but could not fully confirm from the diff alone: the mcps branch (truncated in my read) and whether _trusted_deserialize() is consulted consistently on every repository-controlled import path in this function. If there are other import_module call sites in load_agent_from_repository beyond the tool loop, they would be worth the same treatment. Non-blocking review — the tool-loading path itself looks correct.
Fixes #9665.
Summary
load_agent_from_repositorycurrently performs ungated reflection on agent repository server responses — thetoolsarray is loaded viaimportlib.import_module(tool["module"])+getattr(module, tool["name"])+tool_class(**tool["init_params"]), all three controlled by the repository response. This is the carrier named in CVE-2026-92206 (ZDI disclosure, 2026-10-21), and it remains unpatched on main (see #9665).This PR extends the same gate pattern already introduced for the sibling path in #8623 ([SECT-601],
base_tool.py:_resolve_tool_dict) to the repository tool-loading loop:crewai.*/crewai_tools.*), orCREWAI_DESERIALIZE_CALLBACKS=1(the existing trusted-data opt-in), otherwise anAgentRepositoryErroris raised explaining the flag.Behavior change
Repository-defined agents that load third-party tool modules will now require
CREWAI_DESERIALIZE_CALLBACKS=1. First-party tools keep working unchanged. This mirrors the trade-off already accepted for checkpoint deserialization in #8623.Notes
_FIRST_PARTY_TOOL_PACKAGESand_trusted_deserializeas-is, imported where the loop runs (the function already uses inline imports).CREWAI_ALLOW_THIRD_PARTY_REPO_TOOLS=1) or the error wording if you prefer a separate opt-in for this path.lib/crewai/src/crewai/utilities/agent_utils.py(tools loop inload_agent_from_repository); the gate mirrorslib/crewai/src/crewai/tools/base_tool.py:64-82.Reported as part of research on agent-harness security-fix practices. All analysis was static, on public code.