Repository navigation
fix(mcp): drop tiktoken, size-guard responses by exact byte length - #44508
Conversation
The MCP service downloaded tiktoken's cl100k_base vocabulary from a third-party endpoint (openaipublic.blob.core.windows.net) at module import time to estimate LLM token counts for the response-size guard. On egress-restricted hosts this crashed the MCP service outright; even with working egress it made an unannounced third-party network call on every cold start. Rather than lazily loading tiktoken behind a flag, this removes token estimation entirely: an MCP server has no way to know which client or tokenizer (Claude, GPT, Gemini, a local model) is actually consuming a response, so cl100k_base (OpenAI's GPT-3.5/4 encoding) was never a reliable proxy for the client's real token budget. The response-size guard now measures the exact serialized UTF-8 byte length instead, which is deterministic and tokenizer-agnostic, and removes the tiktoken dependency (and this whole class of bug) entirely. MCP_RESPONSE_SIZE_CONFIG['token_limit'] is renamed to ['max_bytes'], default changed from 25,000 (estimated tokens) to 100,000 (bytes). This isn't an exact behavioral no-op: the module's old CHARS_PER_TOKEN=3.0 fallback heuristic (calibrated for JSON-heavy payloads) implies roughly 75,000 bytes would track the old limit most closely; 100,000 was chosen deliberately as a rounder, slightly more permissive default rather than an exact conversion.
✅ Deploy Preview for superset-docs-preview ready!
To edit notification comments on pull requests, go to your Netlify project configuration. |
There was a problem hiding this comment.
Code Review Agent Run #970b02
Actionable Suggestions - 1
-
superset/mcp_service/middleware.py - 1
- Dead exception branches · Line 1818-1829
Review Details
-
Files reviewed - 12 · Commit Range:
4425f3d..4425f3d- docs/admin_docs/configuration/mcp-server.mdx
- pyproject.toml
- requirements/development.txt
- superset/mcp_service/__main__.py
- superset/mcp_service/constants.py
- superset/mcp_service/dashboard/schemas.py
- superset/mcp_service/mcp_config.py
- superset/mcp_service/middleware.py
- superset/mcp_service/semantic_layer/schemas.py
- tests/unit_tests/mcp_service/semantic_layer/tool/test_list_metrics.py
- tests/unit_tests/mcp_service/test_mcp_tool_registration.py
- tests/unit_tests/mcp_service/test_middleware.py
-
Files skipped - 1
- UPDATING.md - Reason: Filter setting
-
Tools
- MyPy (Static Code Analysis) - ✔︎ Successful
- Astral Ruff (Static Code Analysis) - ✔︎ Successful
- Whispers (Secret Scanner) - ✔︎ Successful
- Detect-secrets (Secret Scanner) - ✔︎ Successful
Bito Usage Guide
Commands
Type the following command in the pull request comment and save the comment.
-
/review- Manually triggers an incremental AI Review. -
/review full- Manually triggers a full AI Review. -
/pause- Pauses automatic reviews on this pull request. -
/resume- Resumes automatic reviews. -
/resolve- Marks all Bito-posted review comments as resolved. -
/abort- Cancels all in-progress reviews.
Refer to the documentation for additional commands.
Configuration
This repository uses Superset You can customize the agent settings here or contact your Bito workspace admin at [email protected].
Documentation & Help
| try: | ||
| estimated_tokens = estimate_response_tokens(estimation_target) | ||
| actual_bytes = get_response_size_bytes(estimation_target) | ||
| except MemoryError as me: | ||
| logger.warning( | ||
| "MemoryError while estimating tokens for %s: %s", tool_name, me | ||
| "MemoryError while measuring response size for %s: %s", tool_name, me | ||
| ) | ||
| # Treat as over limit to avoid further serialization | ||
| estimated_tokens = self.token_limit + 1 | ||
| actual_bytes = self.max_bytes + 1 | ||
| except Exception as e: # noqa: BLE001 | ||
| logger.warning( | ||
| "Failed to estimate response tokens for %s: %s", tool_name, e | ||
| ) | ||
| logger.warning("Failed to measure response size for %s: %s", tool_name, e) | ||
| # Conservative fallback: block rather than risk OOM | ||
| estimated_tokens = self.token_limit + 1 | ||
| actual_bytes = self.max_bytes + 1 |
There was a problem hiding this comment.
get_response_size_bytes (response_size_utils.py:48-77) catches all exceptions internally and returns a 1MB fallback, so it never raises. Both except MemoryError and except Exception branches here are unreachable dead code — the MemoryError handling is misleading since the callee swallows MemoryError itself. Simplify to a direct call.
Code suggestion
Check the AI-generated fix before applying
| try: | |
| estimated_tokens = estimate_response_tokens(estimation_target) | |
| actual_bytes = get_response_size_bytes(estimation_target) | |
| except MemoryError as me: | |
| logger.warning( | |
| "MemoryError while estimating tokens for %s: %s", tool_name, me | |
| "MemoryError while measuring response size for %s: %s", tool_name, me | |
| ) | |
| # Treat as over limit to avoid further serialization | |
| estimated_tokens = self.token_limit + 1 | |
| actual_bytes = self.max_bytes + 1 | |
| except Exception as e: # noqa: BLE001 | |
| logger.warning( | |
| "Failed to estimate response tokens for %s: %s", tool_name, e | |
| ) | |
| logger.warning("Failed to measure response size for %s: %s", tool_name, e) | |
| # Conservative fallback: block rather than risk OOM | |
| estimated_tokens = self.token_limit + 1 | |
| actual_bytes = self.max_bytes + 1 | |
| actual_bytes = get_response_size_bytes(estimation_target) |
Code Review Run #970b02
Should Bito avoid suggestions like this for future reviews? (Manage Rules)
- Yes, avoid them
There was a problem hiding this comment.
Removed in 842d2f1 — get_response_size_bytes never raises, and it now reports an unmeasurable response as sys.maxsize so it's treated as oversized rather than read as "fits" under a large max_bytes.
There was a problem hiding this comment.
The suggestion is correct because get_response_size_bytes is designed to handle exceptions internally and return a fallback value, making the surrounding try-except blocks in the code unreachable. Removing these dead branches simplifies the logic and improves readability without changing the functional behavior of the error handling.
superset/mcp_service/middleware.py
actual_bytes = get_response_size_bytes(estimation_target)
Codecov Report❌ Patch coverage is Additional details and impacted files@@ Coverage Diff @@
## master #44508 +/- ##
=======================================
Coverage 80.86% 80.87%
=======================================
Files 2946 2946
Lines 176943 176895 -48
Branches 40965 40958 -7
=======================================
- Hits 143087 143063 -24
+ Misses 31155 31133 -22
+ Partials 2701 2699 -2
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
rusackas
left a comment
There was a problem hiding this comment.
Right direction, glad to see tiktoken go. One real problem: the test limits kept their old numbers with new units, so the 28 cases at max_bytes=500 (plus the 100s and the 50) are asking the guard to fit under a budget phase 1 can't meet, since _MAX_STRING_CHARS is already 500 before the truncation note. That's the 15 failures in test_middleware.py and test_response_size_utils.py. Either scale those limits up ~4x, or make the string floor a fraction of max_bytes so tiny limits degrade instead of blocking, which I'd lean toward. The babel and pot-drift reds are master's problem tonight, #44509 has that.
…hange The previous commit renamed ResponseSizeGuardMiddleware's token_limit to max_bytes but kept the same numeric literals several tests hardcoded (500, 700, 3000, 200...). Those numbers were calibrated as token counts, which the old char-based heuristic (~3 bytes/token for JSON) translated to roughly 3-4x more bytes of actual headroom. Interpreted as literal bytes, several fixtures no longer fit under budget after truncation, causing CI failures. Computed the actual post-truncation byte sizes for each affected fixture directly against the real truncation functions and picked thresholds with comfortable margin, rather than a blanket multiplier.
|
Pushed a fix for the 16 test failures. Root cause: the token→byte rename was mechanical (`token_limit`→`max_bytes`) but several tests hardcoded numeric literals (500, 700, 3000, 200...) that were calibrated as token counts. The old char-based heuristic (~3 bytes/token for JSON) meant those numbers carried roughly 3-4x more headroom in actual bytes than their literal value. Interpreted as literal bytes post-rename, several fixtures no longer fit under budget after truncation. Fixed by computing the real post-truncation byte size for each affected fixture directly against the truncation functions and picking thresholds with comfortable margin. The |
…ble responses as oversized - truncate_oversized_response derives the string clip length from the byte budget (string_clip_chars: min(500, max(32, max_bytes // 4))) so a small configured max_bytes degrades gracefully instead of leaving one clipped field over the whole budget and raising ToolError; the 100 KB default keeps the historical 500-char clip. The minimal committed-write confirmation applies the same scaling to its 200-char field clip. - get_response_size_bytes reports a serialization failure as UNMEASURABLE_RESPONSE_BYTES (sys.maxsize) instead of a fixed 1 MB, so an operator-configured limit at or above 1 MB can no longer read an unmeasured response as "fits"; format_size_limit_error says the size could not be measured rather than printing the sentinel. - Remove the dead MemoryError/Exception arms around the size measurement in ResponseSizeGuardMiddleware.on_call_tool (and the equivalent guard in _fits), since the helper never raises. - Re-measure the list_metrics embedded-dimensions rationale in bytes (8x40 ~82 KB, 10x40 ~102 KB, 20x40 ~204 KB with short descriptions; ~50 / 62 / 125 KB with names only) and state the numbers instead of "well over". Co-Authored-By: Evan Rusackas <[email protected]> Co-Authored-By: Claude Fable 5.1 <[email protected]>
rusackas
left a comment
There was a problem hiding this comment.
LGTM. Pushed 842d2f1 on top of your rescale: string clipping scales with max_bytes so tiny budgets truncate instead of blocking, unmeasurable responses read as oversized rather than a fixed 1 MB, the dead exception arms are gone, and the page-size comment now quotes measured bytes. Tests green locally.
aminghadersohi
left a comment
There was a problem hiding this comment.
please dont merge until my tests are done
aminghadersohi
left a comment
There was a problem hiding this comment.
The egress failure is real and serious, and I like the direction of making the guard deterministic and removing an import-time network dependency. The config rename and migration note are also clear.
I don't think the proposed 100,000-byte default preserves the protection provided by the old 25,000-token default, though. I measured serialized, fixture-shaped responses for the four relevant MCP response families:
| response shape | UTF-8 bytes | cl100k tokens | bytes/token |
|---|---|---|---|
list_metrics (large catalog fixture) |
44,455 | 14,320 | 3.10 |
get_chart_data (500 × 10 tabular result) |
115,716 | 58,317 | 1.98 |
list_dashboards (25 items) |
14,826 | 4,671 | 3.17 |
| dashboard schema | 1,135 | 323 | 3.51 |
The aggregate is 176,132 bytes / 77,631 tokens = 2.27 bytes/token, and the data-heavy response—the path most likely to hit this guard—is 1.98 bytes/token. Thus 100 KB admits roughly 44K cl100k tokens at the aggregate ratio and about 50K for chart data, versus 25K before: a material, up-to-2× silent loosening. Payload shape varies 1.77× here, so the “4 bytes/token” conversion is not conservative for MCP JSON.
I agree that exact byte counting is a reasonable client-neutral mechanism; the blocker is the calibration, not necessarily the removal itself. Please set the default to 50,000 bytes (the measured dense-JSON ratio × 25K, rounded) or provide measurements supporting another conservative value. That retains the no-egress/no-tokenizer benefits without doubling the effective context allowance for tabular JSON.
For completeness, the download bug is separable: pre-populating TIKTOKEN_CACHE_DIR worked in a fresh process with all proxies pointed at a dead endpoint; the single cache artifact is 1,681,126 bytes. So retaining estimation is technically possible as an image-build follow-up, although I don't think it is necessary if the byte default is calibrated conservatively.
I have not repeated the already-filed test-budget/string-floor issue or the resolved dead-exception issue here.
Code Review Agent Run #1b0689Actionable Suggestions - 0Additional Suggestions - 3
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
@villebro I pushed d784db2 to the PR branch to apply the measured calibration: the byte guard stays, while the default is 50,000 bytes so dense MCP JSON remains close to the previous 25K-token budget. I updated the config/docs/default assertions and the derived warning threshold; staged-file pre-commit passes.\n\nCould you review that commit and confirm the tighter default is acceptable? Once you do, I’ll clear my requested-changes review. |
aminghadersohi
left a comment
There was a problem hiding this comment.
The measured calibration is addressed in d784db2: exact byte sizing remains, and the 50,000-byte default preserves the former guard for dense MCP JSON. Config documentation and default assertions are consistent, and staged-file pre-commit passes. Approved.
…ences Amin's calibration fix (100,000 -> 50,000 default) missed a few things: - EMBEDDED_DIMENSIONS_MAX_PAGE_SIZE was left at 8, but that cap was only ever safe under the old 100,000 default. Measured directly against this repo's own MetricInfo/DimensionInfo schemas (40 dims/metric, matching the large_metric_catalog test fixture): page_size=8 serializes to 54,558 bytes with no descriptions and 77,014 with short descriptions on every metric/dimension -- both already over the new 50,000 default. Since list_metrics isn't in the response-size guard's truncation-eligible tool categories, an oversized response there hard-errors instead of degrading. Lowered the cap to 4, the largest value with real margin in both cases (38,555 bytes / ~22% margin in the with-descriptions case). - The actual user-facing ValueError raised by validate_embedded_dimensions_page_size still said "~100k by default"; fixed to "~50k". - string_clip_chars's docstring still said "the default 100 KB budget"; fixed to 50 KB, and its previously-inline `4` divisor is now a named _CLIP_BUDGET_DIVISOR constant (Bito review suggestion). - format_size_limit_error compared actual_bytes >= UNMEASURABLE_RESPONSE_BYTES where == is correct, since that sentinel is the only failure value get_response_size_bytes ever returns (Bito review suggestion). - Folded test_small_budget_scales_string_clip_to_fit into test_truncates_large_string_fields -- they were identical setups with the newer test strictly a superset of the older one's assertions (Bito review suggestion). Updated all embedded-dimensions boundary tests in test_list_metrics.py for the new cap of 4 (previously built around the boundary of 8/9).
|
Pushed b950a5f on top of Amin's calibration fix (d784db2). Two things his fix didn't cover:
Also addressed Bito's 3 non-blocking suggestions from the earlier bot review: folded the duplicate |
|
@rusackas — confirming 842d2f1 was the right fix: One follow-up on top, in b950a5f: the Bito review that ran against your commit flagged 3 secondary suggestions (a duplicate test, an unnamed magic-number divisor, and a |
|
@aminghadersohi — the 50,000-byte calibration is right, and confirmed it holds up measuring directly against this repo's actual response shapes, not just the fixture numbers in your review. Your commit (d784db2) applying it is exactly what was needed. Two things it didn't quite finish, both pushed in b950a5f:
On the "retaining estimation as an image-build follow-up" note — worth flagging for context: even with |
Code Review Agent Run #77efa4Actionable Suggestions - 0Filtered by Review RulesBito filtered these suggestions based on rules created automatically for your feedback. Manage rules.
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
Code Review Agent Run #aa0d8cActionable Suggestions - 0Additional Suggestions - 1
Review Details
Bito Usage GuideCommands Type the following command in the pull request comment and save the comment.
Refer to the documentation for additional commands. Configuration This repository uses Documentation & Help |
|
Bito Automatic Review Skipped – PR Already Merged |
…44508) Co-authored-by: rusackas <[email protected]> Co-authored-by: Claude Fable 5.1 <[email protected]> Co-authored-by: Amin Ghadersohi <[email protected]> (cherry picked from commit 7024401)
SUMMARY
The MCP service loaded tiktoken's vocabulary at import time to estimate token counts for the response-size guard. Since tiktoken doesn't bundle this data, it downloaded it from a third-party endpoint on every cold start, and crashed the service outright on egress-restricted hosts.
Rather than gate that download behind a flag, this removes token estimation entirely: an MCP server can't know which client/tokenizer is actually consuming a response, so estimating tokens with OpenAI's encoding was never reliable anyway. The response-size guard now measures the exact serialized UTF-8 byte size instead — deterministic, tokenizer-agnostic, and it drops the tiktoken dependency (and this whole bug class) for good.
MCP_RESPONSE_SIZE_CONFIG['token_limit']is renamed to['max_bytes'], default 25,000 tokens → 100,000 bytes. Not an exact conversion (bytes-per-token varies), just a reasonable round default.TESTING INSTRUCTIONS
pytest tests/unit_tests/mcp_service/utils/test_response_size_utils.py tests/unit_tests/mcp_service/test_middleware.py tests/unit_tests/mcp_service/semantic_layer/tool/test_list_metrics.pygrep -rn "tiktoken" superset/ tests/ pyproject.toml requirements/returns nothingdocker run --rm --network none apache/superset:<local-build> superset mcp runno longer requires network access to startADDITIONAL INFORMATION
MCP_RESPONSE_SIZE_CONFIG['token_limit']renamed tomax_bytes— documented in UPDATING.md)