diff --git a/backend/docs/MCP_SERVER.md b/backend/docs/MCP_SERVER.md index 8370676ded..2f8a454088 100644 --- a/backend/docs/MCP_SERVER.md +++ b/backend/docs/MCP_SERVER.md @@ -28,6 +28,14 @@ When the compatibility middleware rewrites history, the OpenAI Responses API request replays the projected messages. After a switch to a text-only model, this lets the provider see the placeholders and surrounding tool text. +## Structured-only stdio tool results + +When a stdio MCP tool returns `structuredContent` with an empty `content` list, +DeerFlow exposes the JSON result as model-visible text. File references in its +string values follow the same `/mnt/user-data/...` translation as text results. +The tool artifact retains the original JSON. Existing content blocks take +precedence over the fallback, and errors follow the usual error handling. + ## Stdio Working Directory Set `cwd` when a stdio server needs to resolve its entrypoint or data files diff --git a/backend/packages/harness/deerflow/mcp/tools.py b/backend/packages/harness/deerflow/mcp/tools.py index 6999b8cb64..898ba938f6 100644 --- a/backend/packages/harness/deerflow/mcp/tools.py +++ b/backend/packages/harness/deerflow/mcp/tools.py @@ -3,6 +3,7 @@ from __future__ import annotations import asyncio +import json import logging import re from collections.abc import Callable, Collection, Iterable, Mapping @@ -235,17 +236,16 @@ def _prepare_stdio_workspace(paths: Paths, *, thread_id: str, user_id: str) -> t def _result_has_text_content(call_tool_result: Any) -> bool: - """Return ``True`` when the MCP result carries any text content. + """Return ``True`` when text content can use the workspace snapshot. - The after-call snapshot diff only feeds bare-filename correlation in free - text. When the result has no text blocks there is nothing to rewrite, so the - caller can skip the second recursive walk entirely. + Include the JSON fallback for successful structured-only results. Other + non-text results can skip the second workspace walk. """ from mcp.types import EmbeddedResource, TextContent, TextResourceContents content = getattr(call_tool_result, "content", None) if not content: - return False + return not getattr(call_tool_result, "isError", False) and bool(getattr(call_tool_result, "structuredContent", None)) for item in content: if isinstance(item, TextContent): return True @@ -316,6 +316,8 @@ def _rewrite_unique_bare_filenames( """ candidates: dict[str, list[str]] = {} for path in changed_files: + if path.name not in text: + continue virtual_path = _local_uri_to_virtual_path( str(path), thread_id=thread_id, @@ -504,8 +506,8 @@ def _convert_call_tool_result( the private ``langchain_mcp_adapters.tools._convert_call_tool_result`` symbol. When ``thread_id`` and ``user_id`` are provided, local files referenced by - ``ResourceLink`` blocks or plain text (e.g. screenshots saved by Playwright - MCP) have their references translated from the host path to the + ``ResourceLink`` blocks, plain text, or string values in the JSON fallback + have their references translated from the host path to the ``/mnt/user-data/...`` virtual path so they can be resolved by the sandbox and artifact API. The files themselves are not copied — stdio servers run with their cwd/temp pinned inside the mounted tree, so they already live in @@ -543,6 +545,9 @@ def _convert_call_tool_result( # langgraph is optional; if unavailable, continue with standard MCP content conversion. pass + if changed_files is not None: + changed_files = tuple(changed_files) + def _resolve_link_url(uri: str) -> str: if thread_id is None or user_id is None: return uri @@ -563,6 +568,16 @@ def _convert_call_tool_result( changed_files=changed_files, ) + def _resolve_structured_paths(value: Any) -> Any: + # Resolve values before JSON encoding escapes Windows path separators. + if isinstance(value, str): + return _resolve_text(value) + if isinstance(value, list): + return [_resolve_structured_paths(item) for item in value] + if isinstance(value, dict): + return {key: _resolve_structured_paths(item) for key, item in value.items()} + return value + # Convert MCP content blocks to LangChain content blocks. lc_content = [] resource_links: list[dict[str, Any]] = [] @@ -666,7 +681,11 @@ def _convert_call_tool_result( artifact = None if call_tool_result.structuredContent is not None: - artifact = {"structured_content": call_tool_result.structuredContent} + structured_content = call_tool_result.structuredContent + artifact = {"structured_content": structured_content} + if not lc_content: + projected = _resolve_structured_paths(structured_content) if thread_id is not None and user_id is not None else structured_content + lc_content.append(create_text_block(text=json.dumps(projected, ensure_ascii=False))) if resource_links: if artifact is None: artifact = {} @@ -875,9 +894,8 @@ def _make_session_pool_tool( **domain_kwargs, ) - # The after-call snapshot diff only feeds bare-filename correlation in - # free text, so skip the second recursive walk when there is no text - # content to rewrite. Both the diff and the per-token path resolution + # The after-call snapshot diff correlates generated filenames in text, + # including the structured-result fallback. Both the diff and path resolution # inside _convert_call_tool_result touch the filesystem, so run them off # the event loop. changed_files: list[Path] | None = None diff --git a/backend/tests/test_mcp_artifact_capture.py b/backend/tests/test_mcp_artifact_capture.py index 5d2d10f131..bbdf0950a8 100644 --- a/backend/tests/test_mcp_artifact_capture.py +++ b/backend/tests/test_mcp_artifact_capture.py @@ -1,6 +1,8 @@ """MCP resource links must reach the persistent artifact registry through the graph.""" +import json from contextlib import asynccontextmanager +from copy import deepcopy import pytest import pytest_asyncio @@ -34,11 +36,25 @@ async def session_pool(): ("stdio", "application/pdf", "pdf"), ("stdio", "image/png", "png"), ("streamable_http", "image/png", "png"), + ("stdio", None, "result"), + ("stdio", None, "empty"), + ("stdio", None, "generated-file"), ], ) async def test_resource_link_captured_by_agent_graph(transport, mime, suffix, monkeypatch, tmp_path, session_pool): url = f"https://example.com/report.{suffix}" calls = [] + paths = Paths(tmp_path) + thread_id = "report-thread" + user_id = "report-owner" + generated_file = paths.sandbox_work_dir(thread_id, user_id=user_id) / "report folder" / "report.pdf" + structured = {"count": 3, "city": "杭州"} if suffix == "result" else {} + expected = structured + if suffix == "generated-file": + virtual_path = "/mnt/user-data/workspace/report folder/report.pdf" + structured = {"files": [{"path": str(generated_file), "relative": "report folder/report.pdf", "name": "report.pdf"}], "url": "https://example.com/report.pdf"} + expected = {**structured, "files": [{"path": virtual_path, "relative": virtual_path, "name": virtual_path}]} + original_artifact = {"structured_content": deepcopy(structured)} class Session: async def initialize(self): @@ -57,6 +73,11 @@ async def test_resource_link_captured_by_agent_graph(transport, mime, suffix, mo async def call_tool(self, name, arguments, **kwargs): calls.append((name, arguments)) + if mime is None: + if suffix == "generated-file": + generated_file.parent.mkdir(parents=True) + generated_file.write_bytes(b"report") + return CallToolResult(content=[], structuredContent=structured) return CallToolResult( content=[ ResourceLink( @@ -76,7 +97,7 @@ async def test_resource_link_captured_by_agent_graph(transport, mime, suffix, mo # Discovery, pooling/call protection, tool execution, and capture are real. monkeypatch.setattr("langchain_mcp_adapters.tools.create_session", fake_session) monkeypatch.setattr("langchain_mcp_adapters.sessions.create_session", fake_session) - monkeypatch.setattr("deerflow.mcp.tools.get_paths", lambda: Paths(tmp_path)) + monkeypatch.setattr("deerflow.mcp.tools.get_paths", lambda: paths) connection = {"transport": "stdio", "command": "offline-mcp-fixture"} if transport == "stdio" else {"transport": "streamable_http", "url": "https://example.com/mcp"} discovered = await load_mcp_tools( None, @@ -106,11 +127,15 @@ async def test_resource_link_captured_by_agent_graph(transport, mime, suffix, mo ) state = await graph.ainvoke( {"messages": [("user", "Export a report")]}, - context={"thread_id": "report-thread", "thread_incarnation": "fixture-incarnation"}, + context={"thread_id": thread_id, "user_id": user_id, "thread_incarnation": "fixture-incarnation"}, ) (message,) = [m for m in state["messages"] if isinstance(m, ToolMessage)] assert calls == [("export", {})] assert message.status == "success" + if mime is None: + assert json.loads(message.content[0]["text"]) == expected + assert message.artifact == original_artifact + return if mime.startswith("image/"): assert message.content[0]["type"] == "image" assert message.content[0]["url"] == url