python-sdk icon indicating copy to clipboard operation
python-sdk copied to clipboard

Prompt handlers returning UserList are rendered as one text message

Open pasmud opened this issue 1 month ago • 3 comments

Initial Checks

  • [x] Reproduced with mcp 2.3.0, the latest release when checked.
  • [x] Searched the issue tracker for an existing report.

Release line

2.x (current stable)

Description

A prompt handler returning a collections.UserList of messages produces one user message containing a quoted Python representation of the collection. The individual messages and their roles are lost. Returning the same messages in a list or tuple works correctly.

The example below should return a user message containing Question followed by an assistant message containing Answer.

SyncPromptResult accepts Sequence returns, but Prompt.render() only treats lists and tuples as message collections. An empty UserList also returns one text message containing "[]" instead of no messages.

A local fix and regression tests are ready for a PR. The fix handles collections.abc.Sequence while keeping strings as single messages. Eight regression cases cover sync and async handlers, lists, tuples, UserList, and empty UserList results. Four cases fail before the fix; all eight pass afterwards. The full suite passes on Windows and Linux with 100% statement and branch coverage.

I'd like to contribute the fix if you're open to an outside PR.

Example Code

from collections import UserList
from collections.abc import Sequence

import anyio

from mcp import Client
from mcp.server.mcpserver import AssistantMessage, MCPServer, Message, UserMessage

server = MCPServer()


@server.prompt()
def conversation() -> Sequence[Message]:
    return UserList([UserMessage("Question"), AssistantMessage("Answer")])


async def main() -> None:
    async with Client(server) as client:
        result = await client.get_prompt("conversation")
        print([(message.role, message.content.model_dump()) for message in result.messages])


anyio.run(main)

Python & MCP Python SDK

Python 3.11.15 on Windows, mcp 2.3.0 installed from PyPI.
Also reproduced at main/v2.3.0 commit 2118f14f8a19bc158d8a1cf90af58d85d187f849.

We used AI to test and validate the issue.

pasmud avatar Oct 05 '26 09:10 pasmud

The contract mismatch here is worth naming precisely, because it decides the fix: SyncPromptResult accepts any Sequence, but Prompt.render() only treats list and tuple as message collections. UserList is a MutableSequence wrapper, not a list subclass, so it takes the single-message path and gets stringified. The direction you describe (handle collections.abc.Sequence, keep strings as single messages) is the right one; a few details to watch when it lands:

  • str, bytes, and bytearray are Sequence instances. The check needs to exclude them explicitly (and consider collections.UserString), or a string prompt result will start being iterated character by character. Keep str and a UserString case in the permanent regression matrix.
  • Normalize through the same element coercion the list path uses (each item through the Message validation), rather than trusting the sequence's element types. That makes tuples, UserList, and future sequence types behave identically.
  • Empty sequence: returning an empty messages list is the correct mapping. Emitting a placeholder message containing "[]" is the same bug in miniature, so a direct assertion for it in the tests is worth having.

One more case to consider adding to the eight: a sequence subclass that changes iteration behavior lazily. It is cheap to cover and protects the normalization step from being bypassed later.

The sync and async matrix plus coverage counts in your report make this an easy review.

Ben-Home avatar Oct 05 '26 12:10 Ben-Home

Hi! I reproduced this: Prompt.render() only treats list/tuple as a list of messages, so a UserList (or any other non-str Sequence) gets wrapped and JSON-dumped into a single message, and an empty UserList renders as one "[]" message.

I have a small fix ready: use a collections.abc.Sequence check that excludes str/bytes, plus tests for sync/async UserList results and the empty case. The full suite passes at 100% coverage, and ruff and pyright are clean. Could I be assigned to open the PR? Happy to defer if the reporter would rather submit theirs.

(I worked on this with help from Cursor and Grok Bot.)

ajay206 avatar Oct 12 '26 09:10 ajay206

A pinned standalone regression test is available for the empty UserList case already described here. It fails on latest stable 2.3.0 (2118f14f8a19bc158d8a1cf90af58d85d187f849) and current main 754254c08fe1c3eda18b69da3d336106fe8d72d6: rendering UserList([]) produces one message containing "[]" instead of no messages.

Test: standalone failing reproduction, branch repro/prompt-sequence-return (diff).

From that branch, after installing its development dependencies:

uv run --frozen pytest tests/server/mcpserver/prompts/test_base.py::test_prompt_render_accepts_user_list_as_a_sequence_result -q

Python 3.14.7 / Pydantic 2.12.5. Existing list-of-strings and multiple-message controls pass alongside the intentional failure on both versions. The branch contains only the test and its imports.

AI-assisted investigation and test reproduction, with a human in the loop.

inanna-malick avatar Oct 14 '26 22:10 inanna-malick