[PLUGINS]: JSON response pruning plugin to reduce token usage
🧭 Type of Feature
Please select the most appropriate category:
- [ ] Enhancement to existing functionality
- [x] New feature or capability
- [ ] New MCP-compliant server
- [ ] New component or integration
- [ ] Developer tooling or test improvement
- [ ] Packaging, automation and deployment (ex: pypi, docker, quay.io, kubernetes, terraform)
- [ ] Other (please describe below)
🧭 Epic
Title: JSON pruning Goal: Eliminate unnecessary fields/values from API JSON responses Why now: Some APIs can be very "noisy" by providing information that is of no/little relevance to the llm. This wastes toke or might even confuse the llm
🙋♂️ User Story 1
As a: end user I want: eliminate unneccessary json fields/values So that: llm gets only provided required/helpful infomration
✅ Acceptance Criteria
Scenario: API-Call Original API response with all fields Only necessary/helpful fields get passed through (whitelist) Reduced Json response gets passed to llm
📐 Design Sketch (optional)
Please see encl. json_prune.py plugin that provides this functionality. It is based on the existing json_repair plugin. Maybe you chose to include this or a modified version of the plugin in future releases of Content Forge or make this even a functionality that you expose in the UI.
🔗 MCP Standards Check
- [ ] Change adheres to current MCP specifications
- [x] No breaking changes to existing MCP-compliant integrations
- [ ] If deviations exist, please describe them below:
🔄 Alternatives Considered
none
📓 Additional Context
@crivetimihai this is a follow-up to our discussion https://github.com/IBM/mcp-context-forge/discussions/2511. Please find encl. my suggestion for json_prune.py. It works for my use-case but I am sure that it can be improved. Is this the right approach? Let me know what you think.
Here is my suggestion for this functionality: json_prune.py (based on json_repair.py)
# -*- coding: utf-8 -*-
"""Location: ./plugins/json_prune/json_prune.py
Copyright 2025
SPDX-License-Identifier: Apache-2.0
Authors: Mihai Criveti, Alexander Wiegand
JSON Prune Plugin.
"""
from __future__ import annotations
import orjson
from mcpgateway.plugins.framework import (
Plugin, PluginConfig, PluginContext, ToolPostInvokePayload, ToolPostInvokeResult,
)
def _get_pruned(data: any, whitelist: list[str]) -> any:
"""Recursively build a new object, merging whitelisted fields."""
if isinstance(data, list):
return [_get_pruned(item, whitelist) for item in data]
if not isinstance(data, dict):
return data
pruned = {}
for path in whitelist:
parts = path.split('.')
src, dst = data, pruned
for i, part in enumerate(parts):
if isinstance(src, dict) and part in src:
if i == len(parts) - 1:
dst[part] = src[part]
elif isinstance(src[part], list):
if part not in dst: dst[part] = [{} for _ in src[part]]
res = _get_pruned(src[part], [".".join(parts[i+1:])])
for idx, item in enumerate(res):
if idx < len(dst[part]) and isinstance(item, dict):
dst[part][idx].update(item)
break
else:
dst = dst.setdefault(part, {})
src = src[part]
else:
break
return pruned
class JSONPrunePlugin(Plugin):
def __init__(self, config: PluginConfig) -> None:
super().__init__(config)
self.debug = self.config.config.get("debug", False)
self.webhooks = self.config.config.get("webhooks", [])
async def tool_post_invoke(self, payload: ToolPostInvokePayload, context: PluginContext) -> ToolPostInvokeResult:
# Match against 'name' field in config.yaml
target_config = next((i for i in self.webhooks if i.get("name") == payload.name), None)
if not target_config:
return ToolPostInvokeResult(continue_processing=True)
try:
content = payload.result.get("content", [])
if not (content and "text" in content[0]):
return ToolPostInvokeResult(continue_processing=True)
raw_text = content[0]["text"]
if self.debug:
print(f"--- [JSONPrunePlugin] Tool: {payload.name} ---")
print(f"Original Raw:\n{raw_text}")
data_dict = orjson.loads(raw_text)
pruned_dict = _get_pruned(data_dict, target_config.get("fields", []))
if self.debug:
print(f"Pruned Dict: {pruned_dict}")
# Re-serialize with Pretty Print (OPT_INDENT_2)
new_raw = orjson.dumps(pruned_dict, option=orjson.OPT_INDENT_2).decode("utf-8")
content[0]["text"] = new_raw
if self.debug:
print(f"New Raw Output:\n{new_raw}")
print("--- [JSONPrunePlugin] End ---\n")
return ToolPostInvokeResult(modified_payload=payload, metadata={"pruned": True})
except Exception as e:
if self.debug: print(f"[JSONPrunePlugin] Error: {e}")
return ToolPostInvokeResult(continue_processing=True)
The config.yaml looks like this:
# JSON prune
- name: "JSONPrunePlugin"
kind: "plugins.json_prune.json_prune.JSONPrunePlugin"
description: "Attempts to prune JSON outputs to save tokens"
version: "0.1.0"
author: "Mihai Criveti"
hooks: ["tool_post_invoke"]
tags: ["json", "prune"]
mode: "permissive"
priority: 49
conditions: []
config:
debug: true
webhooks:
# Webhook.site for testing - UPDATE WITH YOUR UNIQUE URL
- name: "get-time"
fields: ["query", "results.datetime", "results.timezone"]
- name: "get-location"
fields: ["query", "results.location", "results.timezone", "results.coordinates"]
- name: "web-search"
fields: ["query", "results.url", "results.title", "results.content","results.publishedDate","results.score","results.category","infoboxes.id","infoboxes.content","infoboxes.urls","infoboxes.attributes","suggestions"]
Heey! I'd like to work on this;))
Thanks @alex9434. Stripping noisy fields before passing API responses to the LLM would save tokens and reduce confusion. The existing json_repair plugin is a good reference, and the json_prune.py implementation you included could be a starting point.
Hi @jonpspri, why is this set to "not planned"? Could you kindly elaborate? Since the implementation is already there why not include it?