Something went wrong. Try again.
MCP based ACP agent
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204"""Phase 1 — `task` tool schema prototype (FastMCP experiment, PLAN 1.1–1.3).
Prove the tool shape BEFORE any plumbing. The single `task` tool takes``updates: list[PromptItem | CancelTurnItem]`` (no task_create, notask_read — read is query_session on the session_id).
The two item types have OVERLAPPING fields — each carries the other'spayload as an optional — so a naive union is ambiguous: one wire dict canbe both "prompt an existing session" and "cancel, then re-prompt". Theexperiment demonstrates the ambiguity, then proves the discriminatedvariant yields a schema a model can follow and round-trips through realFastMCP argument parsing (in-process client path, no mocks)."""
from typing import Annotated, Literal, Union
import pytestfrom fastmcp import FastMCPfrom pydantic import BaseModel, Field, TypeAdapter
# ------------------------------------------------------------- naive union
class PromptItemNaive(BaseModel): prompt: str session_id: str | None = None
class CancelTurnNaive(BaseModel): session_id: str prompt: str | None = None
NAIVE_LIST = TypeAdapter(list[Union[PromptItemNaive, CancelTurnNaive]])
# ------------------------------------------------------- discriminated union
class PromptItem(BaseModel): """Send a prompt to a session. session_id omitted/None launches a NEW subagent; with session_id it re-prompts an existing (paused/cancelled/ ended) session, resuming it if it is not live."""
action: Literal["prompt"] = "prompt" prompt: str session_id: str | None = None priority: Literal["high", "low"] = "low" model: str | None = None
class CancelTurn(BaseModel): """session/cancel a running session mid-turn. No follow-up argument — redirecting is TWO updates: cancel, then a prompt with the same session_id."""
action: Literal["cancel"] = "cancel" session_id: str
TaskUpdate = Annotated[Union[PromptItem, CancelTurn], Field(discriminator="action")]DISCRIMINATED_LIST = TypeAdapter(list[TaskUpdate])
@pytest.fixturedef task_mcp(): mcp = FastMCP("task-proto")
@mcp.tool async def task(updates: list[TaskUpdate]) -> str: """Create, re-prompt or cancel subagent sessions.
updates is a list of items, each either: - {"action": "prompt", "prompt": ..., "session_id": null} launch - {"action": "prompt", "prompt": ..., "session_id": "..."} re-prompt - {"action": "cancel", "session_id": "..."} cancel """ return repr(updates)
return mcp
# ------------------------------------------------------------------ the flaw
class TestNaiveUnionIsAmbiguous: """The same wire dict validates as BOTH item types — intent is unrecoverable without a discriminator."""
AMBIGUOUS = {"prompt": "fix the bug", "session_id": "swift-fox"}
def test_both_variants_accept_the_same_payload(self): as_prompt = PromptItemNaive.model_validate(self.AMBIGUOUS) as_cancel = CancelTurnNaive.model_validate(self.AMBIGUOUS) assert as_prompt.prompt == as_cancel.prompt == "fix the bug" assert as_prompt.session_id == as_cancel.session_id == "swift-fox"
def test_smart_union_silently_picks_one(self): parsed = NAIVE_LIST.validate_python([self.AMBIGUOUS]) assert len(parsed) == 1 # Whichever it picked, the OTHER reading was equally valid — the # model's intent ("re-prompt it" vs "cancel then re-prompt") is # lost. That is the flaw the discriminator fixes. assert isinstance(parsed[0], (PromptItemNaive, CancelTurnNaive))
# ------------------------------------------------------------- the fix
class TestDiscriminatedUnion: LAUNCH = {"action": "prompt", "prompt": "investigate crow-cli"} RE_PROMPT = { "action": "prompt", "prompt": "you went off course, do X instead", "session_id": "swift-fox", "priority": "high", } CANCEL = {"action": "cancel", "session_id": "swift-fox"}
def test_all_three_shapes_parse(self): parsed = DISCRIMINATED_LIST.validate_python( [self.LAUNCH, self.RE_PROMPT, self.CANCEL] ) launch, re_prompt, cancel = parsed assert isinstance(launch, PromptItem) and launch.session_id is None assert launch.priority == "low" # default assert isinstance(re_prompt, PromptItem) assert re_prompt.session_id == "swift-fox" assert re_prompt.priority == "high" assert isinstance(cancel, CancelTurn) assert cancel.session_id == "swift-fox"
def test_redirect_is_two_updates(self): """The redirect workflow: cancel + a prompt to the SAME session. Both parse, in order, as distinct variants.""" parsed = DISCRIMINATED_LIST.validate_python( [self.CANCEL, self.RE_PROMPT] ) assert isinstance(parsed[0], CancelTurn) assert isinstance(parsed[1], PromptItem) assert parsed[0].session_id == parsed[1].session_id
def test_overlapping_payload_is_no_longer_ambiguous(self): """The ambiguous dict now REQUIRES a verdict via action.""" with pytest.raises(Exception): DISCRIMINATED_LIST.validate_python( [{"prompt": "fix the bug", "session_id": "swift-fox"}] )
class TestSchemaTheModelSees: async def test_parameters_name_both_variants_and_the_discriminator( self, task_mcp ): tool = await task_mcp.get_tool("task") schema = tool.parameters blob = __import__("json").dumps(schema)
# Both variants reachable from the updates parameter assert "PromptItem" in blob assert "CancelTurn" in blob # The discriminator is visible to the model assert '"action"' in blob assert '"prompt"' in blob and '"cancel"' in blob # Priority is plumbed day one assert '"high"' in blob and '"low"' in blob
def test_json_schema_marks_action_const_per_variant(self): schema = PromptItem.model_json_schema() assert schema["properties"]["action"]["const"] == "prompt" schema = CancelTurn.model_json_schema() assert schema["properties"]["action"]["const"] == "cancel"
class TestFastMcpRoundTrip: """Through the real FastMCP call path (argument parsing included)."""
async def test_mixed_batch_round_trips(self, task_mcp): result = await task_mcp.call_tool( "task", { "updates": [ {"action": "prompt", "prompt": "launch me"}, {"action": "cancel", "session_id": "swift-fox"}, { "action": "prompt", "prompt": "actually do this instead", "session_id": "swift-fox", }, ] }, ) text = str(result.data if hasattr(result, "data") else result) assert "PromptItem" in text assert "CancelTurn" in text assert "launch me" in text assert "actually do this instead" in text
async def test_bad_action_is_rejected_not_guessed(self, task_mcp): with pytest.raises(Exception): await task_mcp.call_tool( "task", {"updates": [{"action": "yeet", "session_id": "x"}]}, )