crewai - ✅(Solved) Fix [BUG] Pydantic Validation Error with `security_context` in MCP Tools [3 pull requests, 7 comments, 4 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
crewAIInc/crewAI#4796Fetched 2026-04-08 00:40:16
View on GitHub
Comments
7
Participants
4
Timeline
23
Reactions
0
Timeline (top)
cross-referenced ×7referenced ×7commented ×6labeled ×1

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

Error Message

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

Root Cause

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

Fix Action

Fixed

PR fix notes

PR #4797: fix: ignore extra fields (security_context) in MCP tool schemas

Description (problem / solution / changelog)

Summary

Fixes #4796.

CrewAI's tool execution framework injects a security_context parameter (containing agent_fingerprint and metadata) into tool arguments via _add_fingerprint_metadata() in tool_usage.py. MCP tool schemas are created using create_model_from_schema(), which defaults to ConfigDict(extra="forbid"). This causes Pydantic validation to fail with "Extra inputs are not permitted" when any MCP tool is invoked.

The fix passes ConfigDict(extra="ignore") when creating Pydantic models for MCP tool schemas in two places:

  • lib/crewai-tools/.../mcp_adapter.py — the CrewAIToolAdapter used by MCPServerAdapter
  • lib/crewai/src/crewai/mcp/tool_resolver.py — the native MCP tool resolver

This ensures extra fields like security_context are silently dropped during validation rather than raising errors, while still validating declared tool parameters normally.

Review & Testing Checklist for Human

  • Verify CrewAIPlatformActionTool doesn't have the same issue — it also uses create_model_from_schema() without extra="ignore" (lib/crewai-tools/.../crewai_platform_action_tool.py:38). If platform tools are also invoked through tool_usage.py, they'll hit the same security_context validation failure.
  • Confirm extra="ignore" is the right policy for MCP tools — this silently drops all unknown fields, not just security_context. Verify there's no scenario where rejecting unknown MCP tool arguments would be desirable (e.g., catching LLM hallucinated parameters).
  • Test with a real MCP server end-to-end — run a crew with an MCP tool (SSE or stdio) and confirm tool calls succeed without the validation error from the issue.

Notes

<!-- CURSOR_SUMMARY -->

[!NOTE] Medium Risk Changes tool argument validation behavior for MCP tools to silently drop unknown fields, which could mask mis-specified/hallucinated parameters; otherwise the change is localized and covered by new tests.

Overview Fixes MCP tool invocation failures when CrewAI injects extra arguments (e.g. security_context) by building MCP argument schemas with Pydantic ConfigDict(extra="ignore") in both the crewai-tools MCP adapter and CrewAI’s native MCPToolResolver.

Adds regression coverage ensuring security_context is silently dropped while declared args remain validated, and updates tool.specs.json to remove several unintended/extra init schema fields (e.g. client/cluster/API handle parameters) from generated specs.

<sup>Written by Cursor Bugbot for commit 959534d506e2ddad8513b8d5fb4daf1e57340719. This will update automatically on new commits. Configure here.</sup>

<!-- /CURSOR_SUMMARY -->

Changed files

  • lib/crewai-tools/src/crewai_tools/adapters/mcp_adapter.py (modified, +5/-2)
  • lib/crewai-tools/tests/adapters/mcp_adapter_test.py (modified, +68/-0)
  • lib/crewai-tools/tool.specs.json (modified, +0/-61)
  • lib/crewai/src/crewai/mcp/tool_resolver.py (modified, +3/-0)
  • lib/crewai/tests/utilities/test_pydantic_schema_utils.py (modified, +83/-0)

PR #4807: fix(tools): prevent Pydantic validation error with security_context in MCP tools

Description (problem / solution / changelog)

Summary

  • _add_fingerprint_metadata injects security_context into tool arguments after the acceptable_args filtering, so it bypasses the filter and causes Pydantic ValidationError on strict MCP tool schemas that don't declare security_context as a valid field.
  • Fix: move the _add_fingerprint_metadata call to before the acceptable_args filtering in both the sync and async code paths. The existing filter naturally strips any keys not in the tool's schema, so security_context is only passed to tools that explicitly declare it.
  • No new dependencies or breaking changes.

Test plan

  • Use an MCP tool with a strict Pydantic schema that does not include security_context -- should no longer raise ValidationError
  • Use a tool that declares security_context in its schema -- should still receive the field
  • Verify fingerprint metadata is still injected correctly for tools that accept it

Fixes #4796

🤖 Generated with Claude Code

<!-- CURSOR_SUMMARY -->

[!NOTE] Low Risk Small, localized change to tool argument preparation that mainly affects whether extra metadata keys are forwarded; minimal behavioral risk outside of tools that relied on previously unfiltered metadata.

Overview Prevents strict-schema (e.g., MCP) tools from failing Pydantic validation by changing when fingerprint metadata is injected into tool call arguments.

In both sync and async tool execution paths, _add_fingerprint_metadata now runs before filtering against tool.args_schema properties, so injected keys like security_context are stripped unless explicitly allowed; the exception fallback also copies arguments before enrichment to avoid mutating the original input.

<sup>Written by Cursor Bugbot for commit 5ef8ac3c4b66ff61e537ef9d2c069e26eb993800. This will update automatically on new commits. Configure here.</sup>

<!-- /CURSOR_SUMMARY -->

Changed files

  • lib/crewai/src/crewai/tools/tool_usage.py (modified, +14/-8)

PR #4815: fix(mcp): use extra='ignore' in _json_schema_to_pydantic to allow CrewAI-injected security_context

Description (problem / solution / changelog)

Problem

CrewAI's tool_usage.py injects a security_context field into every tool call's arguments before Pydantic validation (lines 1024-1045). MCP tools build their argument schema from the MCP server's inputSchema via create_model_from_schema(), which defaults to ConfigDict(extra='forbid').

Since the MCP server's schema never includes security_context, validation raises (closes #4796):

pydantic_core.ValidationError: Extra inputs are not permitted
  security_context
    Extra inputs are not permitted [type=extra_forbidden, ...]

Root cause

MCPToolResolver._json_schema_to_pydantic() calls create_model_from_schema() without overriding the default ConfigDict(extra='forbid').

Fix

Pass ConfigDict(extra='ignore') explicitly when building the schema model for MCP tools:

return create_model_from_schema(
    json_schema,
    model_name=model_name,
    enrich_descriptions=True,
    __config__=ConfigDict(extra="ignore"),   # ← allow security_context to pass through
)

Framework-injected fields are silently dropped before the model sees only the fields it declared. The MCP tool's own validation is unaffected.

Closes #4796

<!-- CURSOR_SUMMARY -->

[!NOTE] Medium Risk Relaxes Pydantic validation for MCP tool arguments by ignoring unknown fields, which could mask unexpected/typoed inputs but is scoped to MCP-derived schemas and prevents runtime failures from framework-injected metadata.

Overview Fixes MCP tool argument validation failures by generating Pydantic models with extra="ignore" in MCPToolResolver._json_schema_to_pydantic, allowing CrewAI-injected fields like security_context to pass through without raising extra_forbidden errors.

This changes MCP tool schemas created via create_model_from_schema to silently drop unknown keys instead of rejecting them.

<sup>Written by Cursor Bugbot for commit 81037f4c585f6011586a2e6de1aad983c9e72f34. This will update automatically on new commits. Configure here.</sup>

<!-- /CURSOR_SUMMARY -->

Changed files

  • lib/crewai/src/crewai/mcp/tool_resolver.py (modified, +7/-0)

Code Example

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

---

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
    )

---

Tool FailedTool: search_knowledge                                                                                         │
Iteration: 6Attempt: 3Error: 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"]
RAW_BUFFERClick to expand / collapse

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

extent analysis

Fix Plan

To resolve the issue, we need to configure the args_schema model to ignore extra fields. We can achieve this by using Pydantic's Config class to set extra='ignore'.

Step-by-Step Solution

  1. Modify the args_model creation: Update the create_model_from_schema function to include the Config class with extra='ignore'.
from pydantic import create_model, BaseModel

# ...

args_model = create_model(
    f"{tool_name}Args",
    __base__=BaseModel,
    **mcp_tool.inputSchema,
    __config__=BaseModel.Config(extra='ignore')
)

Alternatively, if you cannot modify the create_model_from_schema function, you can create a new model that wraps the original model and ignores extra fields:

from pydantic import BaseModel

# ...

class ArgsModel(BaseModel):
    class Config:
        extra = 'ignore'

    **mcp_tool.inputSchema

args_model = ArgsModel
  1. Update the CrewAIMCPTool class: Use the updated args_model in the CrewAIMCPTool class.
class CrewAIMCPTool(BaseTool):
    name: str = tool_name
    description: str = tool_description
    args_schema: type[BaseModel] = args_model  # Updated model that ignores extra fields

Verification

To verify that the fix worked, execute the same task that triggered the MCP tool (e.g., search_knowledge) and check that the tool call succeeds without any Pydantic validation errors.

Extra Tips

  • Make sure to update the crewai-tools library to the latest version to ensure you have the latest fixes and features.
  • If you're using a virtual environment, ensure that the pydantic library is up-to-date, as older versions may not support the extra='ignore' configuration.
  • Consider adding additional logging or error handling to catch and handle any unexpected errors that may occur during tool execution.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

FAQ

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.

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

crewai - ✅(Solved) Fix [BUG] Pydantic Validation Error with `security_context` in MCP Tools [3 pull requests, 7 comments, 4 participants]