Skip to content

fix(agents): gate repository tool loading to first-party modules (CVE-2026-92206 carrier) - #9666

Open
Freedomn (freedom2132) wants to merge 5 commits into
crewAIInc:mainfrom
freedom2132:security-gate-repo-tools
Open

Freedomn (freedom2132) wants to merge 5 commits into
crewAIInc:mainfrom
freedom2132:security-gate-repo-tools

Conversation

@freedom2132

Copy link
Copy Markdown

Fixes #9665.

Summary

load_agent_from_repository currently performs ungated reflection on agent repository server responses — the tools array is loaded via importlib.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:

  • tool modules must be first-party (crewai.* / crewai_tools.*), or
  • explicitly opted in via CREWAI_DESERIALIZE_CALLBACKS=1 (the existing trusted-data opt-in), otherwise an AgentRepositoryError is 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

  • The gate reuses _FIRST_PARTY_TOOL_PACKAGES and _trusted_deserialize as-is, imported where the loop runs (the function already uses inline imports).
  • Happy to adjust the env var (e.g., a dedicated CREWAI_ALLOW_THIRD_PARTY_REPO_TOOLS=1) or the error wording if you prefer a separate opt-in for this path.
  • Verbatim vulnerable code at lib/crewai/src/crewai/utilities/agent_utils.py (tools loop in load_agent_from_repository); the gate mirrors lib/crewai/src/crewai/tools/base_tool.py:64-82.
  • Supersedes fix(agents): gate repository tool loading to first-party modules (CVE-2026-92206 carrier) #9664 (auto-closed by the first-time-contributor issue-linkage policy; this one references the companion issue).

Reported as part of research on agent-harness security-fix practices. All analysis was static, on public code.

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

strix-security Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Strix Security Review

Warning

This pull request has 4 commits after the last Strix review (596fc36). Strix has not reviewed these changes.
Automatic review on push is off for this repository. To review the latest changes, tag @strix-security in a comment, or turn on re-review on push.

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 summary

This PR adds a first-party module-prefix allowlist in front of the repository tool-loading loop in load_agent_from_repository, mirroring the checkpoint gate in base_tool.py. The intent is right, but the control validates only the module string: the attribute name and constructor kwargs taken from the repository response are still unbounded, and a first-party helper reachable by name (crewai.utilities.import_utils.require) re-imports any module the gate refuses, so the reflection sink it targets stays open — filed as the unsafe-reflection finding. One key over, the same response's mcps entry is copied through untouched and coerced into a stdio MCP server config, letting the repository definition spawn an arbitrary local process with no opt-in, which is filed separately as the mcps gate-bypass finding. Taken together the change narrows the path but does not close the carrier it claims to close.

Ruled out (6)
  • Can a repository response pick the checkpoint output directory through the `checkpoint` key?
    The key is copied by an else-branch the PR does not change, and it only selects a directory under which a generated filename is written, so it is not the reflection sink being gated.
  • Can a repository response make the agent read arbitrary local files via `knowledge_sources`?
    The file-backed knowledge classes and path handling are pre-existing code the PR neither edits nor routes new data through, and no import sink is involved.
  • Can a repository response redirect all model traffic and credentials via `llm` / `function_calling_llm`?
    That pass-through and the `LLM(**kwargs)` construction it feeds are unchanged and outside the branch the PR modifies; the definition author already dictates model settings by design.
  • Can a repository response make the agent scan attacker-chosen filesystem paths via `skills`?
    Skill discovery runs entirely through pre-existing code and only surfaces path-existence and SKILL.md content on the local machine, with no channel back to the sender.
  • Is the trust boundary void because a project `.env` can repoint `CREWAI_PLUS_URL` at an attacker host?
    That base-URL resolution is pre-existing, deliberately supported self-hosted configuration, and it does not bypass the new gate; an actor who can plant the `.env` already controls code the victim executes.
  • Do the project-definition loaders import third-party tool modules without any gate?
    Those loaders consume operator-authored local project files, and the same loader already executes project-local Python by design, so no attacker/victim boundary is crossed and they are not twins of the network-response path.

Fixed the findings? re-run the review, or tag @strix-security in a PR comment to run a fresh review.

Review 1 on this PR · 596fc36 · requested Nov 23 02:53 UTC when the PR was opened


Reviewed by Strix
Re-run review · Configure security review settings · Try a deeper review with @strix-security /deep

…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

@strix-security strix-security Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Strix flagged 2 new security findings below. See the pinned summary comment for the full PR status.

Comment on lines 1215 to 1217
tool_class = getattr(module, tool["name"])

tool_value = tool_class(**tool["init_params"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 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"] 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.
Suggested change
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.

Comment on lines +1204 to +1213
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."
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 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).
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.

@freedom2132

Copy link
Copy Markdown
Author

Addressing the review findings in 886e474:

Cursor HIGH (gate design):

  • The prefix check now also accepts the bare package names crewai and crewai_tools (not only dotted submodules), so published repository tools load without the opt-in — no more error message nudging operators toward CREWAI_DESERIALIZE_CALLBACKS=1 for legitimate first-party tools.
  • The resolved attribute must now be a BaseTool subclass before instantiation, even under the opt-in — arbitrary callables (os.system, reset_memories_command, fetch_agent_card) are refused regardless of the flag, mirroring the checkpoint behavior of _resolve_tool_dict (which registers and accepts only BaseTool subclasses). This also covers the first-party-gadget cases (SystemExit escape, outbound GET, memory reset) since none are BaseTool subclasses.

Strix HIGH ×2 (ungated sibling keys):

  • mcps: repository-supplied inline MCP server objects (non-string entries) are refused unless CREWAI_DESERIALIZE_CALLBACKS=1; plain string refs pass. Applied the suggested snippet as-is.
  • memory: repository-supplied memory dicts (embedder endpoint / storage path) are refused unless the opt-in. Applied the suggested snippet as-is.

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 mcps/memory gates close the two demonstrated capability paths.

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.
@freedom2132

Copy link
Copy Markdown
Author

Re: the Cursor review — the described chain targets the first commit (the hunk is marked outdated); as of 886e474 the uv Click command is already refused at instantiation: it is not a BaseTool subclass, so tool_class(**tool.init_params) never runs, with or without the opt-in.

The import-shim residual it correctly points at is real, though, and is now closed in the follow-up commit: importlib.import_module("crewai.cli.cli") resolves to a module named crewai_cli.cli, so after import the module's real top-level package must be crewai or crewai_tools — a repository tool definition whose import name starts with crewai. but resolves to another distribution (shim/alias) is refused. This implements the remediation's "reject the crewai.cli shim target even though its import name starts with crewai".

Remaining declared residual: the import itself can have side effects (e.g. _ShimFinder installation) before the identity check rejects the module — the same residual exposure the checkpoint path (_resolve_tool_dict) carries for its first-party imports. The instantiation gate (BaseTool subclass only) remains the code-execution boundary.

@surlymochan Nick (surlymochan) left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)
@freedom2132

Copy link
Copy Markdown
Author

Nick (@surlymochan) thanks for the review — tests added in the latest commit, extending test_agent.py next to the existing test_agent_from_repository_with_invalid_tools:

  • test_agent_from_repository_refuses_third_party_tool_module (module os)
  • test_agent_from_repository_refuses_non_basetool_callable (a first-party function, not a BaseTool)
  • test_agent_from_repository_refuses_import_shim_module (monkeypatched import returning a crewai_cli.cli module)
  • test_agent_from_repository_refuses_import_string_tool_params (a fake BaseTool with an ImportString field receiving "os.system")
  • test_agent_from_repository_refuses_inline_mcp_definition (your inline-MCP case)
  • test_agent_from_repository_refuses_repository_memory_config (your dict-memory case)

The last two rounds of bot review also drove two more gates in the same commit:

  1. Import-string parameters (Cursor): init_params for a first-party BaseTool could carry dotted import strings — ImportString-typed fields like custom_embedding_fn bind e.g. os.system at construction, and package-name fields (qdrant_package/db2_package/db2_dbi_package) reach import_module. String values for those fields are now refused unless the opt-in is set (real callables from in-process callers still pass).
  2. Re-confirmed the shim gate from the previous commit (import name crewai.* resolving to another distribution is refused post-import).

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(

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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)]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 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.

@surlymochan Nick (surlymochan) left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Harden load_agent_from_repository tool loading (CVE-2026-92206 carrier unpatched on main)

2 participants