crewAI icon indicating copy to clipboard operation
crewAI copied to clipboard

[BUG] MCPServerAdapter sends JSON null for every unset optional tool argument, breaking strict-schema MCP servers

Open shiqi446-blip opened this issue 1 month ago • 5 comments

Description

MCPServerAdapter-generated tools always send every optional argument to the MCP server, including arguments the agent/caller never set, as an explicit JSON null. Any MCP server whose JSON Schema does not itself mark that field nullable (i.e. a plain {"type": "string"} optional field, not anyOf: [{"type":"string"},{"type":"null"}]) rejects the call during its own schema validation, even though the field was correctly left unset by the caller.

This looks like a regression of #302 ("Agent unable to handle optional parameters for mcp server"), which was closed in 2025 after a fix landed in mcpadapt>=0.1.9. That fix was in mcpadapt's model-generation code. Since then, crewai_tools/adapters/mcp_adapter.py's CrewAIToolAdapter.adapt() was changed to bypass mcpadapt's model creation and instead use crewai.utilities.pydantic_schema_utils.create_model_from_schema() (the adapter's own docstring says this: "This adapter bypasses mcpadapt's model creation which adds invalid null values to field schemas, instead using CrewAI's own schema utilities."). That new path reintroduces the same problem in a different file, and the actual argument serialization step (crewai/tools/base_tool.py's _validate_kwargs) sends the null regardless of what the generated schema says, so it affects every optional field on every MCP tool, not just ones with an unusual schema.

Two separate causes combine:

  1. crewai/utilities/pydantic_schema_utils.py, _json_schema_to_pydantic_field: any property not in the schema's required list is unconditionally wrapped Optional[type_] with default = None, regardless of whether the server's own schema declares the field nullable.
  2. crewai/tools/base_tool.py, _validate_kwargs: calls validated.model_dump() with no exclude_none=True, so every field (including ones never set by the caller) is serialized, turning the Python None default into a JSON null sent to the server.

Steps to Reproduce

  1. Start a minimal MCP server using the official mcp python SDK's low-level Server (not FastMCP, to keep the schema explicit) with one tool, greet, that takes a required name: string and an optional nickname declared as plain {"type": "string"} in inputSchema (not wrapped in anyOf with null, and not in required). Use the default @server.call_tool() (i.e. validate_input=True, the SDK default), which runs jsonschema.validate(instance=arguments, schema=tool.inputSchema) before calling the handler.
  2. In a separate script, connect with crewai_tools.MCPServerAdapter({"url": "http://127.0.0.1: 8001/mcp", "transport": "streamable-http"}).
  3. Call the generated tool with only the required argument: greet_tool.run(name="Ada") (nickname intentionally omitted).
  4. Compare with calling it with nickname set: greet_tool.run(name="Ada", nickname="Addie").

Minimal server (mini_server_strict.py):

import anyio
import mcp.types as types
from mcp.server.lowlevel import Server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from starlette.applications import Starlette
from starlette.routing import Mount
import uvicorn

server = Server("mini-strict-server")

TOOL_SCHEMA = {
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "nickname": {"type": "string"},
    },
    "required": ["name"],
    "additionalProperties": False,
}


@server.list_tools()
async def list_tools() -> list[types.Tool]:
    return [types.Tool(name="greet", description="Greet someone.", inputSchema=TOOL_SCHEMA)]


@server.call_tool()
async def call_tool(name: str, arguments: dict) -> list[types.TextContent]:
    nickname = arguments.get("nickname")
    person = arguments["name"]
    text = f"Hello, {nickname} ({person})!" if nickname else f"Hello, {person}!"
    return [types.TextContent(type="text", text=text)]


session_manager = StreamableHTTPSessionManager(app=server)
app = Starlette(routes=[Mount("/mcp", app=session_manager.handle_request)])


async def main():
    config = uvicorn.Config(app, host="127.0.0.1", port=8001, log_level="info")
    srv = uvicorn.Server(config)
    async with session_manager.run():
        await srv.serve()


if __name__ == "__main__":
    anyio.run(main)

Client:

from crewai_tools import MCPServerAdapter

server_params = {"url": "http://127.0.0.1:8001/mcp", "transport": "streamable-http"}

with MCPServerAdapter(server_params) as tools:
    greet_tool = [t for t in tools if "greet" in t.name][0]
    print(greet_tool.args_schema.model_json_schema())
    print(greet_tool.run(name="Ada"))                     # nickname omitted
    print(greet_tool.run(name="Ada", nickname="Addie"))   # nickname set

Expected behavior

Omitting the optional nickname argument should produce the same result as explicitly passing nickname=None would in a server that supports it, or at minimum should not fail validation against a server that correctly declares nickname as a plain optional string. The call should succeed and return "Hello, Ada!".

Screenshots/Code snippets

Actual output:

schema: {'additionalProperties': False, 'properties': {'name': {'title': 'Name', 'type':
'string'}, 'nickname': {'anyOf': [{'type': 'string'}, {'type': 'null'}], 'default': None,
'title': 'Nickname'}}, 'required': ['name'], 'title': 'DynamicModel', 'type': 'object'}

RESULT (no nickname passed): Input validation error: None is not of type 'string'
RESULT (nickname passed): Hello, Addie (Ada)!

Note the generated args_schema already shows nickname as anyOf: [string, null], even though the server's real inputSchema for nickname was plain {"type": "string"} with no null option and no default. CrewAI derives "nullable" purely from "not in required", not from the server's actual declared schema. The error itself ("Input validation error: None is not of type 'string'") comes from the official MCP SDK's own default jsonschema.validate() in mcp/server/lowlevel/server.py's call_tool() decorator, not from custom application code in the test server. My own handler function was never reached.

Operating System

macOS Sonoma

Python Version

3.12

crewAI Version

1.15.23

crewAI Tools Version

1.15.23

Virtual Environment

Venv

Evidence

mcp==1.28.1, mcpadapt==0.1.20 (both current resolutions when installing crewai-tools fresh from PyPI on 2026-10-05; mcpadapt is not pulled in automatically, crewai_tools.adapters. mcp_adapter.MCP_AVAILABLE is False until it's installed explicitly, a separate small papercut worth mentioning here since it affects anyone reproducing this).

This also breaks real-world strict-schema MCP servers, not just the hand-rolled one above. We hit the identical failure mode (different error text, same shape: "Input validation error: ..." followed by a list of fields that got null when they should have been absent) against our own production MCP server in a separate project, which is why we went looking for the root cause.

Likely the same root cause as the original report in #302 (optional args on the GitHub MCP server), which was closed as fixed via mcpadapt>=0.1.9, but the fix doesn't apply anymore because CrewAIToolAdapter stopped using mcpadapt's model generation for this.

Possible Solution

In crewai/tools/base_tool.py, _validate_kwargs, change:

validated = self.args_schema.model_validate(kwargs)
return validated.model_dump()

to exclude fields that were never actually supplied by the caller, e.g.:

validated = self.args_schema.model_validate(kwargs)
return validated.model_dump(exclude_none=True, exclude_unset=True)

(exclude_unset=True alone may be enough and is safer than exclude_none=True, since a field whose caller-supplied value genuinely is None for a field that is schema-nullable should probably still be sent; exclude_unset only drops fields nobody touched.)

Separately, in crewai/utilities/pydantic_schema_utils.py, _json_schema_to_pydantic_field could preserve the server's actual nullability instead of always wrapping non-required fields in Optional[...], i.e. only add null to the type if the original JSON Schema property itself allows it (via anyOf/type: [X, "null"]), and otherwise keep the field optional-but-typed with no default sent when unset. The _validate_kwargs fix above is the smaller, lower-risk change and is sufficient on its own to stop sending null for fields the caller didn't set.

Additional context

Also related to #7609 ("Knowledge sources reject file_paths when file_path is passed as None, which also breaks model_validate(model_dump())"), a different subsystem but the same underlying pattern of model_dump() without exclude_none/exclude_unset round-tripping None incorrectly.

shiqi446-blip avatar Oct 05 '26 12:10 shiqi446-blip

Reproduced on current main with a minimal strict MCP server: omitting an optional argument sends it as explicit JSON null and fails the server's schema validation, while set values work fine.

Root cause confirmed at both sites named above — _validate_kwargs dumps without excluding unset fields, and non-required properties are unconditionally Optional in the generated model.

Minimal direction: model_dump(exclude_unset=True) in _validate_kwargs, so never-provided fields are dropped while explicitly passed values (including explicit None) keep current behavior. I'll put up a PR with that plus a regression test unless you're already on it — happy to go another way if you prefer.

kpdagrt22 avatar Oct 05 '26 12:10 kpdagrt22

Thanks for confirming on main. I'm not working on a fix, so please go ahead with the PR. exclude_unset=True sounds right to me, since explicitly passed None keeps its current behaviour. Happy to test the branch against the strict server from the repro.

shiqi446-blip avatar Oct 05 '26 16:10 shiqi446-blip

Thanks for confirming — PR is up at #7900 (branch fix/7891-mcp-adapter-omit-unset-optionals), minimal direction as discussed plus a second commit preserving non-None schema defaults per review feedback. A test run against your strict server would be much appreciated.

kpdagrt22 avatar Oct 06 '26 05:10 kpdagrt22

I'd like to take this one, since #7900 was closed and nothing else is open for it. Plan: in BaseTool._validate_kwargs, drop fields the caller never set that resolve to None (so they are not sent as JSON null), while keeping explicit values, explicit None and real schema defaults, with regression tests for run and arun. This is AI-assisted, so the PR will be marked llm-generated per the contributing guide.

Phantom-TA avatar Oct 29 '26 06:10 Phantom-TA

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 Nov 28 '26 12:11 github-actions[bot]