GitLab MCP: Safe JSON Parsing in API Service
Context
GitLab’s MCP (Model Context Protocol) server includes internal tools that communicate with GitLab APIs and process JSON responses. These components must safely handle external data while remaining fully compatible with expected API payloads.
A RuboCop rule was introduced to flag unsafe JSON parsing and enforce the use of GitLab’s hardened parsing utilities.
Problem
The MCP API service was using
Gitlab::Json.parse to parse HTTP responses.
While functional, this method does not enforce limits on JSON
size or nesting depth.
This triggered RuboCop violations and introduced potential risk when handling unexpectedly large or deeply nested JSON payloads.
My Contribution
I replaced Gitlab::Json.parse with
Gitlab::Json.safe_parse in the MCP API service,
aligning the implementation with GitLab’s secure parsing
guidelines.
In addition, I extended the rescue clause to handle
Gitlab::Json::ParserError, ensuring consistent
error handling for size and depth limit violations introduced
by safe_parse.
The change is intentionally minimal and preserves the existing request/response flow while adding built-in protections against malformed or excessively complex JSON input.
Example Code Change
// Before
parsed_response = Gitlab::Json.parse(response.body)
// After
parsed_response = Gitlab::Json.safe_parse(response.body)
rescue JSON::ParserError, Gitlab::Json::ParserError => e
Only the parsing mechanism and rescue clause were updated. The surrounding logic and error response structure remain unchanged.
Process Notes
The initial merge request branch eventually fell significantly
behind master, which led to merge conflicts and
pipeline instability.
To resolve this cleanly, I rebuilt the change on top of the latest
master in a fresh branch and opened an updated merge
request:
!225533.
This updated MR supersedes the earlier !222565 and ensures a clean diff, accurate CI results, and minimal history noise.
Current Status
The updated merge request is based on the latest master
and is currently under review.
This contribution addresses a scoped backend maintenance task and improves the robustness and security posture of the MCP server.
Reflection
This contribution demonstrates how small, targeted backend refactors can improve security and code quality without altering application behavior.
It also provided practical experience working within a large monorepo, handling branch drift, resolving CI pipeline issues, and maintaining clean contribution history in a production-scale open-source project.