Skip to content

Comments

feat: preserve JSON structure in MCP tool results#26

Merged
douglaz merged 2 commits intomasterfrom
feat/mcp-preserve-json-structure
Sep 1, 2025
Merged

feat: preserve JSON structure in MCP tool results#26
douglaz merged 2 commits intomasterfrom
feat/mcp-preserve-json-structure

Conversation

@douglaz
Copy link
Owner

@douglaz douglaz commented Sep 1, 2025

Summary

This PR enhances MCP tool result handling to preserve JSON structure when tools return structured data, complementing PR #25's smart truncation feature.

Problem

Previously, all tool results were flattened into a simplified format:

{
  "success": true,
  "content": "{\"files\": [...], \"stats\": {...}}"  // JSON as string
}

This lost the structure of complex tool outputs, making them harder to process and analyze.

Solution

The MCP client now:

  1. Attempts to parse tool text content as JSON
  2. If successful, returns the parsed JSON directly to preserve structure
  3. Only falls back to the simplified format for non-JSON content

Example

Before:

{
  "success": true,
  "content": "{\"files\": [\"test.py\", \"main.py\"], \"lines\": 500}"
}

After:

{
  "files": ["test.py", "main.py"],
  "lines": 500
}

Benefits

  • Preserves Structure: Complex tool outputs maintain their JSON structure
  • Better Integration: Works seamlessly with PR feat: enhance decision tracking beyond PR #23 with smart truncation #25's smart truncation
  • Backward Compatible: Non-JSON content still uses the simplified format
  • Cleaner Pipeline: Structured data flows cleanly from tools → MCP → decisions

Testing

Related

- Attempt to parse tool text content as JSON before wrapping
- If content is valid JSON, return it directly to preserve structure
- Only fall back to simplified format for non-JSON content
- Complements PR #25's smart truncation by ensuring structured data flows cleanly

This allows tools to return complex structured data like:
{"files": [...], "stats": {...}, "metadata": {...}}

Instead of flattening everything to:
{"success": true, "content": "...stringified JSON..."}

The combination of this change with PR #25's smart truncation ensures
that structured tool outputs are preserved and intelligently truncated
throughout the entire decision tracking pipeline.
Log a debug message when tool results fall back to simplified format,
showing a preview of the content. This helps developers understand:
- When tools are returning plain text vs structured data
- Why certain results aren't being preserved as JSON
- What the actual content looks like (first 100 chars)
@douglaz douglaz merged commit 4ef8824 into master Sep 1, 2025
4 checks passed
@douglaz douglaz deleted the feat/mcp-preserve-json-structure branch September 1, 2025 16:35
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant