dify icon indicating copy to clipboard operation
dify copied to clipboard

[Bug] Agent V2 converts multiple-select tool arrays into Python repr strings

Open Wang-Zephyr opened this issue 2 weeks ago • 1 comments

What happens

Agent V2 advertises a multiple-select plugin parameter as an array, but sends a Python repr string to the plugin daemon after the model supplies that array. For example:

{"regions": "['apac,east', 'emea']"}

The plugin should receive:

{"regions": ["apac,east", "emea"]}

This affects both select and dynamic-select, including model arguments, hidden runtime values, and defaults. Plugins expecting a list receive the wrong type and cannot reliably interpret the selected values, especially when an option itself contains a comma.

Reproduction and cause

  1. Prepare an Agent V2 plugin tool parameter with type: select, multiple: true, and an array JSON schema, as the existing API tool builder does.
  2. Invoke the native tool with regions=["apac,east", "emea"], or configure that list as a hidden/default parameter.
  3. Inspect the serialized /plugin/<tenant>/dispatch/tool/invoke request's data.tool_parameters.

DifyToolsBuilder._prepared_parameters() validates API ToolParameter dumps through the standalone Agent DTO. That DTO currently ignores multiple; invocation then chooses scalar select coercion and applies str() to the list. The API schema already correctly describes a multiple select as an array, so changing the model input cannot fix this mismatch.

Reproduced against the standalone Agent sources in ff7ee47f9dcdf9020f3a8151eae0aac24ac63a5c; those sources are unchanged at the subsequently observed f371979eba14a457f6c76785f174138957da7713.

This is separate from #45672 / #45676, which concern Tool-node constants being stringified by the workflow engine before API parameter validation. Here an already valid array is corrupted during Agent V2's native tool invocation; that PR does not touch this path.

Verification

  • Six native-dispatch regressions fail on the base: select/dynamic-select × model/runtime/default values. The tests use the real Pydantic AI Agent and toolset, and inspect the actual HTTPX request JSON at a local mock-daemon boundary. A single-select parameter remains a string in every case.
  • After retaining the prepared multiple field and reusing existing array coercion, all 56 tests in the plugin-layer directory pass.
  • A standalone collector below reproduces the wire-type change without importing test helpers. It uses a local FunctionModel and HTTPX MockTransport; it does not contact an external LLM or real plugin daemon.
  • Windows, Python 3.13.18. Full backend/API suites were not run.
Standalone collector

Save as repro.py and run from a source checkout using PYTHONPATH=dify-agent/src uv run --project dify-agent python repro.py.

import asyncio
import json

import httpx
from pydantic_ai import Agent
from pydantic_ai.messages import ModelRequest, ModelResponse, TextPart, ToolCallPart, ToolReturnPart
from pydantic_ai.models.function import FunctionModel

from dify_agent.layers.dify_plugin import tools_layer
from dify_agent.runtime.context import Deps, Services


async def main():
    selected = ["apac,east", "emea"]
    config = tools_layer.Config(tools=[{
        "plugin_id": "search", "provider": "search", "tool_name": "search",
        "credential_type": "unauthorized",
        "parameters": [{"name": "regions", "type": "select", "form": "llm", "multiple": True}],
        "parameters_json_schema": {
            "type": "object", "properties": {"regions": {"type": "array", "items": {"type": "string"}}},
        },
    }])
    wire = []

    def daemon(request):
        wire.append(json.loads(request.content)["data"]["tool_parameters"])
        return httpx.Response(200, text='data: {"code":0,"message":"","data":{"type":"text","message":{"text":"ok"}}}\n')

    async def model(messages, _info):
        returns = [part for message in messages if isinstance(message, ModelRequest)
                   for part in message.parts if isinstance(part, ToolReturnPart)]
        return ModelResponse(parts=[TextPart("done")] if returns else [
            ToolCallPart("search", {"regions": selected}, tool_call_id="call"),
        ])

    async with httpx.AsyncClient(transport=httpx.MockTransport(daemon)) as client:
        deps = Deps(
            layers={
                "tools": {"config": config.model_dump(mode="json"), "state": {}},
                "execution_context": {"config": {
                    "tenant_id": "tenant", "user_id": "user", "user_from": "account",
                    "app_id": "app", "agent_mode": "agent_app", "invoke_from": "web-app",
                }, "state": {}},
            },
            services=Services(client, client, plugin_daemon_api_key="fixture-token"), run_id="test",
        )
        await Agent(FunctionModel(model), deps_type=Deps, toolsets=[tools_layer.Toolset("tools")]).run("Search", deps=deps)
    print(json.dumps(wire))


asyncio.run(main())

Wang-Zephyr avatar Nov 20 '26 08:11 Wang-Zephyr

If you've already got the DTO patch sorted and those 6 regression tests passing against MockTransport, honestly just open a PR directly against dify-agent. Throw the standalone collector in with the plugin-layer tests and it should be an easy review for the maintainers to merge.

grinem avatar Nov 20 '26 10:11 grinem