agents icon indicating copy to clipboard operation
agents copied to clipboard

Validation error due to unexpected $schema in parameters for FunctionDeclaration

Open Leandroglez39 opened this issue 1 year ago • 3 comments

🐞 Issue: Validation error due to unexpected $schema in parameters for FunctionDeclaration

Description

When using the livekit-plugins-google==1.1.1 package, we encounter a validation error in Pydantic when the FunctionDeclaration class is instantiated.

The error arises exactly in the livekit.plugins.google.utils module, in the method to_fnc_ctx Inside this method is called info = get_raw_function_info(fnc)

In our case, the fnc comes from a MCP server developed with Zod TypeScript, which generates a JSON schema that includes an unexpected $schema field in the parameters object. So if continue with the next step with the instantiation of FunctionDeclaration, it raises a validation error because Pydantic does not expect this field.

While using the FunctionDeclaration class:

class FunctionDeclaration(_common.BaseModel):
    parameters: Optional[Schema]

and the Schema class (which follows OpenAPI 3.0):

class Schema(_common.BaseModel):
    # OpenAPI 3.0 schema definition...

We integrate dynamically with MCP (Model Context Protocol), which leverages Zod for data modeling. During JSON Schema generation, Zod automatically injects a $schema field into the parameters object. However, this extra field is not expected by Pydantic and triggers a validation error:

pydantic_core._pydantic_core.ValidationError: 1 validation error for FunctionDeclaration
parameters.$schema
  Extra inputs are not permitted [type=extra_forbidden, input_value='http://json-schema.org/draft-07/schema#', input_type=str]

Incomming field '$schema': 'http://json-schema.org/draft-07/schema#'}

Expected Behavior

There are two acceptable approaches to resolve this:

  1. Allow $schema as an optional property on the Schema model,
  2. Silently ignore extra fields when parsing parameters, so the presence of $schema doesn’t cause validation errors.

Steps to Reproduce

  1. Generate a JSON schema from a Zod model used in MCP.
  2. Pass that schema as parameters to FunctionDeclaration.
  3. Receive a Pydantic validation error due to the extra $schema field.

Suggested Solutions

  • Modify the Schema model to include schema_: Optional[str] = Field(None, alias="$schema"), or
  • Adjust Config (e.g. extra = Extra.ignore) to ignore unknown fields in parameters.

Environment

  • Python version: e.g. 3.12
  • Pydantic version: e.g. 2.7.4
  • MCP / Zod versions: e.g. 1.13.0
  • livekit-plugins-google version: 1.1.1

Leandroglez39 avatar Jun 23 '25 07:06 Leandroglez39

Can you share the raw_schema with this error?

longcw avatar Jun 23 '25 08:06 longcw

raw_schema object

raw_schema={'name': 'XXX', 'description': 'XXXXX', 'parameters': {'type': 'object', 'properties': {'organizationId': {'type': 'string', 'format': 'uuid'}, 'brand': {'type': 'string'}}, 'required': ['organizationId', 'brand'], 'additionalProperties': False, '$schema': 'http://json-schema.org/draft-07/schema#'}})

Error

Traceback (most recent call last):
  File "/home/vscode/.cache/pypoetry/virtualenvs/onlive-agent-PBcHY-hx-py3.12/lib/python3.12/site-packages/livekit/plugins/google/llm.py", line 305, in _run
    function_declarations = to_fnc_ctx(self._tools)
                            ^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/onlive-agent-PBcHY-hx-py3.12/lib/python3.12/site-packages/livekit/plugins/google/utils.py", line 31, in to_fnc_ctx
    tools.append(types.FunctionDeclaration(**info.raw_schema))
                 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/onlive-agent-PBcHY-hx-py3.12/lib/python3.12/site-packages/pydantic/main.py", line 253, in __init__
    validated_self = self.__pydantic_validator__.validate_python(data, self_instance=self)
                     ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
pydantic_core._pydantic_core.ValidationError: 1 validation error for FunctionDeclaration
parameters.$schema
  Extra inputs are not permitted [type=extra_forbidden, input_value='http://json-schema.org/draft-07/schema#', input_type=str]
    For further information visit https://errors.pydantic.dev/2.11/v/extra_forbidden

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "/home/vscode/.cache/pypoetry/virtualenvs/onlive-agent-PBcHY-hx-py3.12/lib/python3.12/site-packages/livekit/agents/llm/llm.py", line 148, in _main_task
    return await self._run()
           ^^^^^^^^^^^^^^^^^
  File "/home/vscode/.cache/pypoetry/virtualenvs/onlive-agent-PBcHY-hx-py3.12/lib/python3.12/site-packages/livekit/plugins/google/llm.py", line 398, in _run
    raise APIConnectionError(
livekit.agents._exceptions.APIConnectionError: gemini llm: error generating content 1 validation error for FunctionDeclaration
parameters.$schema
  Extra inputs are not permitted [type=extra_forbidden, input_value='http://json-schema.org/draft-07/schema#', input_type=str]
    For further information visit https://errors.pydantic.dev/2.11/v/extra_forbidden (body=None, retryable=True) {"llm": "livekit.plugins.google.llm.LLM", "attempt": 1, "pid": 33535, "job_id": "AJ_S7HyqxwqCjoH"}

Certainly! Here’s a professional English translation for your GitHub issue, including an introductory sentence:


A simple workaround just to check if this is the limitation would be something like the following example code:

def to_fnc_ctx(fncs: list[FunctionTool | RawFunctionTool]) -> list[types.FunctionDeclaration]:
    tools: list[types.FunctionDeclaration] = []
    for fnc in fncs:
        if is_raw_function_tool(fnc):
            info = get_raw_function_info(fnc)
            #########################################################################
            if "$schema" in info.raw_schema["parameters"]:                                                                                
                del info.raw_schema["parameters"]["$schema"]  # Remove $schema for Gemini compatibility   
            #########################################################################
            tools.append(types.FunctionDeclaration(**info.raw_schema))

        elif is_function_tool(fnc):
            tools.append(_build_gemini_fnc(fnc))

    return tools

If you need more details, please don't hesitate to ask.

Leandroglez39 avatar Jun 23 '25 09:06 Leandroglez39

https://github.com/livekit/agents/pull/2686 should fix the issue.

longcw avatar Jun 23 '25 13:06 longcw