crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] Pydantic Validation Error with `security_context` in MCP Tools

Open silceNEtea opened this issue 8 months ago • 9 comments

Description

When using MCPServerAdapter from crewai-tools, CrewAI automatically injects a security_context parameter (containing agent_fingerprint and metadata) into tool calls. However, MCP tools' inputSchema (defined by the MCP server) does not include this field. This causes Pydantic validation to fail with an "Extra inputs are not permitted" error.

The CrewAIToolAdapter creates Pydantic models from MCP tool schemas using create_model_from_schema(), which by default rejects extra fields. Since CrewAI's tool execution framework adds security_context during parameter validation (before _run is called), the validation fails immediately.

Problematic Code Location: crewai-tools/lib/crewai_tools/adapters/mcp_adapter.py (Lines 52-59)

tool_name = sanitize_tool_name(mcp_tool.name)
tool_description = mcp_tool.description or ""
args_model = create_model_from_schema(mcp_tool.inputSchema)

class CrewAIMCPTool(BaseTool):
    name: str = tool_name
    description: str = tool_description
    args_schema: type[BaseModel] = args_model  # This model rejects extra fields

Steps to Reproduce

  1. Create an agent with MCP tools using MCPServerAdapter:
from crewai_tools import MCPServerAdapter

with MCPServerAdapter({
    "url": "http://localhost:9500/sse?mode=rag",
    "transport": "sse",
    "headers": {"X-User-ID": "1", "X-Workflow-Run-ID": "test"}
}) as mcp_tools:
    agent = Agent(
        role="RAG Agent",
        goal="Search knowledge base",
        backstory="Expert at searching knowledge",
        tools=mcp_tools,
        verbose=True
    )
  1. Execute a task that triggers the MCP tool (e.g., search_knowledge)
  2. The tool call fails with Pydantic validation error

Expected behavior

The security_context parameter should either:

  1. Be filtered out before Pydantic validation, OR
  2. The args_schema model should be configured to ignore extra fields (e.g., ConfigDict(extra='ignore'))

The tool should execute successfully with only the parameters defined in the MCP tool's inputSchema.

Screenshots/Code snippets

None

Operating System

Windows 11

Python Version

3.12

crewAI Version

1.10.1

crewAI Tools Version

1.10.1

Virtual Environment

Venv

Evidence

Error Output

│  Tool Failed                                                                                                    │
│  Tool: search_knowledge                                                                                         │
│  Iteration: 6                                                                                                   │
│  Attempt: 3                                                                                                     │
│  Error: Arguments validation failed: 1 validation error for DynamicModel                                        │
│  security_context                                                                                               │
│    Extra inputs are not permitted [type=extra_forbidden, input_value={'agent_fingerprint': {'u...61982',        │
│  'metadata': {}}}, input_type=dict]                                                                             │
│      For further information visit https://errors.pydantic.dev/2.11/v/extra_forbidden                           │
│  Expected arguments: {"query": {"title": "Query", "type": "string"}, "top_k": {"anyOf": [{"type": "integer"},   │
│  {"type": "null"}], "default": null, "title": "Top K"}}                                                         │
│  Required: ["query"]                                                                                            │

Possible Solution

None

Additional context

None

silceNEtea avatar Mar 10 '26 10:03 silceNEtea

Submitted a fix in PR (creating now). The issue is that _add_fingerprint_metadata injects security_context after the acceptable_args filter, so it bypasses schema validation. The fix moves the call to before the filter so the existing logic naturally strips security_context for tools that don't declare it.

mvanhorn avatar Mar 11 '26 06:03 mvanhorn

Fix submitted in #4807.

mvanhorn avatar Mar 11 '26 06:03 mvanhorn

Hi! I'd like to take a look at this.

The root cause is clear — create_model_from_schema() creates Pydantic models that reject extra fields by default, but CrewAI's tool execution framework injects security_context before validation.

The cleanest fix would be to set model_config = ConfigDict(extra='ignore') on the dynamically created model in create_model_from_schema(), so the security_context is silently dropped before it hits validation. This way MCP tools only receive the parameters defined in their inputSchema.

I'll put together a PR for this.

Ker102 avatar Mar 13 '26 13:03 Ker102

A2ABench has an accepted answer for this imported thread.

  • Thread: https://a2abench-api.web.app/q/cmmpnabhj00p914017q7y7kia
  • Accepted at: 2026-03-14T01:54:33.585Z
  • Accepted answer agent: partner-fast-1
  • Answer preview: "Direct answer for: [BUG] Pydantic Validation Error with security_context in MCP Tools Reproduce with exact versions and minimal failing input. Isolate root cause (API contract mismatch, config drift, or runtime assumptions). Apply minimal fix and verify with one success case + on"

khalidsaidi avatar Mar 14 '26 17:03 khalidsaidi

This is exactly why MCPS (MCP Secure) puts security metadata in the protocol envelope, not in tool parameters. MCPS adds a separate mcps field to MCP messages containing the ECDSA signature, nonce, timestamp, and passport_id — completely decoupled from the tool's inputSchema. No schema collision, no Pydantic validation errors, and the agent's cryptographic identity travels with every message without touching tool params. IETF Internet-Draft | github.com/razashariff/mcps

razashariff avatar Mar 16 '26 09:03 razashariff

@Ker102 that's a clean approach - setting extra='ignore' on the dynamically created model handles the root cause more directly than my PR (#4807), which reorders the injection to happen before filtering. Both work, but yours is less fragile if new fields get injected later. Happy to close #4807 if you want to take this, or I can update mine to use your approach - whatever's easier for the maintainers.

mvanhorn avatar Mar 16 '26 14:03 mvanhorn

Thank you for the reply, I would love to take this one if its fine with you, but yes, whichever one works best with the maintainers.

Ker102 avatar Mar 16 '26 15:03 Ker102

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 5 days.

github-actions[bot] avatar Apr 18 '26 12:04 github-actions[bot]

这题我会!CrewAI 和 MCP 的「参数内卷」——一边拼命塞 security_context 表示「我很安全」,一边 Pydantic 模型严格校验表示「我不认识你」。

根源是 security_context 的设计假设和 MCP 协议的 inputSchema 声明式校验冲突了。CrewAI 想给所有工具调用加一个「指纹追踪」,但 MCP 工具说「我的 schema 里没这个字段,你别乱来」。

我在踩 MCP 协议的坑时,也遇到过类似的「协议边界冲突」问题,写了个实战总结:https://miaoquai.com/stories/mcp-protocol-practical-guide.html

里面聊了 MCP 工具定义、transport 选择、以及这种「安全参数强行注入」的几种解法。

针对这个 issue,最直接的 fix 是在 那行后面加个 :

或者 CrewAI 在调用工具前先把 security_context 从 kwargs 里 pop 掉,等 执行时再手动传进去。

本质是个「安全策略 vs 协议兼容」的权衡。建议 CrewAI 参考 OpenAI 的 function calling 设计,把安全上下文放到单独的 metadata 字段,而不是混进 tool 参数里。

希望早日修复,现在用 MCP 工具的 crew 都得手动 patch 😅

jingchang0623-crypto avatar Apr 19 '26 00:04 jingchang0623-crypto

Fixed in #5216 (commit 4e4691304), released in 1.13.0. security_context is now passed via the config parameter on invoke/ainvoke instead of being merged into tool args, so MCP tools with strict schemas no longer see it during validation. Please upgrade to ≥1.13.0.

greysonlalonde avatar May 07 '26 18:05 greysonlalonde