MCP: Model Context ProtocolBeginnerModule 03 — MCP messages and JSON-RPC
How does an MCP implementation validate incoming messages?
Question 27 of 43 · Updated
On this page
- Direct answer
- 1. Understand the complete inbound boundary
- 2. Validate the transport before the application message
- STDIO
- Streamable HTTP
- 3. Bounded and unambiguous JSON parsing
- 4. Classify messages before routing them
- 5. Validate the envelope and then the method-specific contract
- 6. Lifecycle, direction and capability checks
- 7. Validate response association before state mutation
- 8. Authentication and business authorization are independent
- 9. Resource limits and failure handling
- 10. Tested practical implementation: a layered validation fixture
- Walk through the validation stages
- Test coverage
- Deliberate limitations
- 11. Practical production acceptance criteria
- Interview-ready answer
Direct answer#
An MCP implementation validates incoming messages in layers, beginning with the transport and ending with the operation's actual application contract. It must establish message boundaries, decode the permitted encoding, parse bounded JSON, classify the message as a request, notification or response, validate the appropriate revision-specific schema, and then enforce session state, capability, correlation and authorization requirements before allowing the message to affect application state.
Parsing JSON successfully is not enough. A syntactically valid request may have an invalid identifier, unsupported method, malformed arguments or insufficient permission. A well-formed response may belong to a different outstanding request. A valid notification may be unexpected in the current lifecycle. Even a fully valid tool result can contain untrusted content.
The central design principle is to validate before dispatch, state mutation, privileged work or disclosure. Each boundary should report a meaningful failure category without exposing sensitive data or confusing protocol failures with business outcomes.
Learning continuity: Q26–31 developed individual request, response, notification, ID, method and error contracts. Q32 separated envelope, representation and domain schemas. Q33 assembles those contracts into an inbound validation architecture covering all three message categories, including framing, bounded parsing and safe rejection. Q34 develops concurrent correlation; Q36–41 cover lifecycle and capabilities; Q102 covers tool argument validation; Q165–174 cover detailed failure handling; Q185–194 and Q198–202 cover security and compliance testing.
Verification scope: Prepared using the authorized offline research and changelog exceptions, with MCP 2025-06-18 as a historical reference baseline rather than a claim about the latest revision. Official links were not checked live. The standard-library Python fixture was syntax-compiled and executed locally on Python 3.13.5: all 25 checks passed (4 accepted, 21 rejected). It validates selected incoming message types over a simulated newline-delimited frame, not a complete MCP SDK or transport implementation. The MCP SDK and Mermaid CLI were unavailable locally. Actual interoperability, Mermaid parsing and website rendering remain unverified.
1. Understand the complete inbound boundary#
Imagine a retail support host communicating with an inventory server. Both participants may receive supported protocol messages. The server can receive a resource request; the client can receive a tool-list change notification; either participant can receive a response to a previously issued request.
A receiver should not send all incoming JSON objects directly into a tool handler. The handler is only one destination within a larger message-processing pipeline.
This is a logical architecture rather than a mandatory universal ordering. Authentication at an HTTP endpoint, for example, can occur before accepting an entire body. Cheap limits and state checks may be applied early. An implementation may combine classification and schema parsing in one SDK operation.
The essential property is that every branch establishes the relevant invariants before executing its privileged handler or accepting an outcome.
2. Validate the transport before the application message#
The selected transport determines how to obtain a complete message. MCP's historical 2025-06-18 transports include stdio and Streamable HTTP.
STDIO#
The historical stdio contract uses newline-delimited JSON messages encoded in UTF-8. Standard output carries MCP messages; ordinary server logs should go to standard error. A receiver must distinguish an incomplete line, a complete line and process termination.
Reading one operating-system chunk is not equivalent to reading one protocol message. A chunk may contain part of a line or several lines. An implementation should accumulate bytes within a bounded buffer, extract complete frames and retain any partial remainder. It should enforce a maximum frame size while accumulating, rather than read indefinitely until a newline appears.
A physical newline separates messages. An escaped newline inside a JSON string is part of that serialized string, not a new frame.
For instance, the following is one serialized JSON object followed by a frame delimiter, not two messages:
JSON{"jsonrpc":"2.0","id":1,"method":"ping"}
A debug line such as Starting server... on stdout is not an MCP message. It may cause the client to reject the frame or close an unusable connection, according to its transport policy.
Streamable HTTP#
In the historical Streamable HTTP contract, check the applicable endpoint, HTTP method, content negotiation, request body encoding, session information, protocol version header when required, and transport security rules. Supported responses can involve JSON or server-sent events, depending on the interaction.
An HTTP stream can split one message across network chunks. An SSE event can contain framing fields that are not members of the JSON-RPC object. Use the appropriate transport and SSE parser rather than pass raw HTTP chunks to a JSON decoder.
Authentication, origin validation and session handling belong at the relevant boundary. A valid JSON body does not bypass an HTTP access failure. Conversely, an HTTP 202 response acknowledging an accepted notification is not a JSON-RPC result.
Transport-specific implementation details are reserved for the dedicated stdio and HTTP modules.
3. Bounded and unambiguous JSON parsing#
Once a message has been framed, the receiver decodes and parses it according to the applicable contract. The historical MCP base protocol requires UTF-8 encoded messages.
Important defensive considerations include:
- Reject malformed encodings instead of silently replacing invalid bytes in a protocol message.
- Bound encoded bytes, buffered data, nesting and processing cost.
- Handle invalid JSON syntax without exposing raw parser exceptions or private payloads.
- Adopt an explicit policy for duplicate object members, which can otherwise produce inconsistent interpretations.
- Reject nonstandard literals such as NaN and Infinity, and handle numeric ranges and precision according to supported schemas and local interoperability policy.
RFC 8259 recommends unique object member names for interoperability. Not every parser rejects duplicates by default. For example:
JSON{"jsonrpc":"2.0","id":1,"method":"ping","method":"tools/call"}
One parser may retain the last method, another may retain the first, and another may reject the message. Rejecting ambiguous duplicates is a sound defensive implementation policy, not a claim that JSON syntax universally prohibits duplicate names.
Numeric limits also matter. A valid JSON exponent such as 1e999 may overflow a floating-point parser. It is different from an outright nonstandard NaN literal. The receiver should not silently treat an overflow as an acceptable finite business number. A lossless decimal parser may instead represent the value exactly and apply the relevant schema and range constraints.
The historical 2025-06-18 MCP revision does not support JSON-RPC batching. An array of request objects therefore cannot be accepted as an ordinary batch merely because generic JSON-RPC defines batch behavior.
4. Classify messages before routing them#
Do not assume that every incoming object is a request. MCP supports messages initiated by either participant according to applicable direction and capability rules.
| Category | Important discriminator | Next validation |
|---|---|---|
| Request | A method and a valid request ID | Supported operation and parameter contract |
| Notification | A supported method without a top-level ID | Event schema, direction and lifecycle |
| Result response | Matching ID and result branch | Expected method's result schema |
| Error response | Matching ID and error branch | Error object and request association |
For example, a method-bearing object with an ID of zero is not a notification. Checking the truthiness of the ID is incorrect. A response containing both result and error is invalid. A message combining a method and a result should not be routed opportunistically to either branch.
This decision tree is a teaching model for the usual historical message categories, not a complete schema grammar. In particular, generic JSON-RPC null-ID diagnostics for unidentifiable errors must be distinguished from ordinary historical MCP correlated errors, as Q31 explained.
Use the selected SDK's discriminated unions or equivalent explicit schema validation. Do not let a catch-all dictionary handler guess which message category a malformed object belongs to.
5. Validate the envelope and then the method-specific contract#
The protocol envelope establishes basic communication validity. The method contract establishes what its particular operation requires.
Consider the following resource request:
JSON{ "jsonrpc": "2.0", "id": 0, "method": "resources/read", "params": {"uri": "policy://returns"} }
The envelope has the exact version marker, a valid integer ID and a method string. The receiver must still determine whether resources/read is supported, whether its parameters meet the method schema, and whether the resource URI is authorized.
For comparison:
JSON{"jsonrpc":"2.0","id":0,"method":"resources/read","params":{"uri":42}}
This is valid JSON, but the URI member does not meet the expected string contract.
A tool call adds another layer: the tools/call method identifies the selected tool and argument object, while the tool's advertised input schema governs its business arguments. If a tool requires a SKU, the application must validate that requirement and enforce ownership or other business constraints. Do not widen the business schema to permit unrelated protocol metadata.
A client must also validate incoming results. A response to resources/read is not expected to carry the same result fields as tools/list or tools/call. Validate against the method associated with the original request, not whichever method seems to fit the returned JSON.
Use schema-aware handling for optional members, null values, types, permitted extensions and unknown fields. Avoid silently coercing strings to integers or booleans into IDs. Conversely, do not invent a universal closed-field policy that rejects legitimate revision-specific extension members. Local hardening choices need to be distinguished from the actual protocol contract.
6. Lifecycle, direction and capability checks#
A method may exist in the specification but still be inappropriate for the current peer or state.
For a historical session-oriented MCP connection, initialize, the initialization response and notifications/initialized establish the applicable lifecycle. Some operations, such as ping, have specific lifecycle allowances. Ordinary resource discovery and invocation should not be treated as universally available before compatibility and readiness are established.
| Incoming situation | Relevant check |
|---|---|
| Ordinary resource read | Server's supported resource feature and applicable lifecycle |
| Tool-list change notification | Server-to-client direction and applicable advertised listChanged support |
| Resource update notification | Applicable subscription and update contract |
| Sampling request | Supported client capability and host policy |
| Cancellation notification | Correct originating request and applicable cancellation rules |
| Response | Trusted session and expected request context |
Capabilities describe supported protocol behavior. They are not permission grants. An inventory server can advertise tools while restricting the actual operations available to a particular actor. A server must not assume that a client permits sampling merely because the client can parse the corresponding JSON-RPC method string.
Capability information should come from the actual negotiated relationship, not from claims inside arbitrary incoming parameters. Likewise, lifecycle state is maintained by the protocol implementation rather than selected by an untrusted message's ready flag.
7. Validate response association before state mutation#
For a response, validate its ID type and value against the expected outstanding request in the correct connection and direction scope. The historical MCP ID non-reuse rule applies to the same requestor within a session.
A malformed or unmatched response must not complete an arbitrary pending operation. An error response is a legitimate outcome only when it is properly classified and associated with the appropriate request.
For example, a client waiting for a ping result with ID p1 should not interpret a response with ID p2 as success. It should also reject an invalid result representation according to the applicable method schema.
In a production dispatcher, the response association check and terminal state transition must be coordinated so that races cannot resolve a request twice. Preserve invalid-message diagnostics separately from accepted outcomes. Q34 develops the concurrent pending-request algorithm in depth.
Notifications are different: a valid notification does not create a JSON-RPC response exchange. It can update authorized event state, but a progress message does not complete the original pending operation and a catalog change does not automatically authorize new tools.
8. Authentication and business authorization are independent#
A valid request envelope and correct parameters establish that a peer has expressed a recognizable operation. They do not establish that the authenticated actor is permitted to execute it.
Suppose an inventory server exposes a public returns policy and a private customer policy. Both identifiers may be well-formed strings. A receiver must determine whether the current actor can read the requested resource.
JSON{ "jsonrpc": "2.0", "id": 18, "method": "resources/read", "params": {"uri": "policy://private"} }
The URI might be structurally valid, yet the operation may be denied by the application's access policy. A schema cannot establish ownership, tenant membership, approval or current business state.
A server should derive identity from trusted authentication context and enforce resource-level permission independently. A host should enforce its own consent and destination-specific disclosure rules. Resource identifiers, tool names and content metadata are untrusted input, not credentials.
Even a validated response is not automatically safe to forward to a model or another service. Check business meaning, expected resource identity, content size, source provenance and authorized disclosure. Validity is not the same as truth or trust.
The advanced security lessons develop authentication, token handling, consent, isolation and threat modeling. This lesson's boundary is where those independent decisions fit into message validation.
9. Resource limits and failure handling#
Validation itself consumes resources. A malicious or defective peer can send a large body, an unterminated stdio line, deeply nested JSON, huge encoded media or many notifications. A validator should not rely only on the final schema check to protect memory and CPU.
Use limits appropriate to the transport and deployment. The following values are illustrative local decisions, not protocol-mandated defaults.
| Boundary | Example defensive control |
|---|---|
| Stream reader | Maximum buffered bytes and idle deadline |
| HTTP body | Maximum decompressed body size |
| JSON decoder | Bounded nesting, numeric representations and parser cost |
| Method parameters | Length and collection-size constraints |
| Media content | Encoded and decoded size, media-type verification |
| Dispatcher | Bounded queues and concurrent handlers |
| Session | Pending-work limits, cleanup and rate controls |
| Logging | Sanitized bounded diagnostic data |
For a simple size calculation, if a server permits at most 4 KiB of buffered input for each of 200 independent connections, those input buffers alone may occupy roughly 800 KiB when full. That excludes object allocation, network buffers, TLS, runtime overhead and queued operations. This is an illustration of capacity reasoning, not a recommended universal frame limit.
A peer should not be allowed to hold an unlimited buffer open waiting for a missing frame delimiter. Apply deadlines and limits while reading. If a boundary is exceeded, stop reading or reject the interaction according to the appropriate transport policy; do not continue allocating until a complete payload arrives.
Error handling must preserve the stage of failure:
| Detected failure | Appropriate category or consideration |
|---|---|
| Broken framing or invalid transport request | Transport/framing failure |
| Invalid JSON | Parse failure; generic JSON-RPC defines -32700 |
| Invalid Request object | Generic JSON-RPC defines -32600 |
| Unrecognized RPC method | Generic JSON-RPC defines -32601 |
| Invalid method parameters | Generic JSON-RPC defines -32602 |
| Resource permission denial | Applicable authorization or method-specific failure |
| Invalid/unmatched incoming response | Local response rejection; do not send a response to a response |
| Valid notification with handler failure | Local handling under the applicable contract, without a JSON-RPC reply |
| Valid tool failure | Method-specific result, such as isError true where appropriate |
The codes are generic JSON-RPC categories, not a complete MCP error-mapping table. In historical MCP, the typed ordinary error response ID is a string or integer. Unidentifiable or malformed messages must be handled according to the actual revision, SDK and transport; do not invent a request ID or indiscriminately emit a generic null-ID diagnostic.
Keep errors concise and safe. Record a stable stage/category in local diagnostics without unnecessarily recording raw message contents, secrets or private data. Where an error response is appropriate, use a documented external message and safe details. Do not expose a traceback to the peer.
10. Tested practical implementation: a layered validation fixture#
This dependency-free Python example accepts an already isolated, newline-terminated byte frame. It applies a small 4 KiB local limit, strict UTF-8 decoding, duplicate-key rejection, JSON numeric checks, message classification, limited method and result validation, state and feature checks, a fictional resource permission, and matching of a single expected ping response.
The Context represents trusted state for this synthetic mixed-role exercise. The resource-read request and catalog notification model different receiving roles; an actual implementation must enforce direction using its real connection role. The code returns a classification label and never executes a resource read, emits a reply or mutates a pending map.
Save as mcp_q33.py:
PYTHONimport json import math from dataclasses import dataclass class Rejected(ValueError): pass def require(condition, stage): if not condition: raise Rejected(stage) def pairs(items): obj = {} for key, value in items: require(key not in obj, 'duplicate_key') obj[key] = value return obj def constant(value): raise Rejected('json_number') def finite_float(value): number = float(value) require(math.isfinite(number), 'json_number') return number def decode(raw): require(type(raw) is bytes and len(raw) <= 4096, 'size') require(raw.endswith(b'\n') and raw.count(b'\n') == 1, 'frame') try: text = raw[:-1].decode('utf-8', errors='strict') except UnicodeError as exc: raise Rejected('encoding') from exc try: msg = json.loads(text, object_pairs_hook=pairs, parse_constant=constant, parse_float=finite_float) except (json.JSONDecodeError, RecursionError) as exc: raise Rejected('json') from exc require(type(msg) is dict and msg.get('jsonrpc') == '2.0', 'envelope') return msg def valid_id(value): return type(value) is str or type(value) is int @dataclass(frozen=True) class Context: ready: bool = True resources: bool = True list_changed: bool = True allowed_uri: str = 'policy://returns' expected_ping_id: str = 'p1' def validate(raw, ctx): msg = decode(raw) if 'method' in msg: require(type(msg['method']) is str and not ({'result', 'error'} & msg.keys()), 'envelope') params = msg.get('params', {}) require(type(params) is dict, 'params') method = msg['method'] if 'id' not in msg: require(method == 'notifications/tools/list_changed', 'notification') require(ctx.ready and ctx.list_changed, 'state') require(not params, 'params') return 'notification' require(valid_id(msg['id']), 'id') require(method == 'resources/read', 'method') require(ctx.ready and ctx.resources, 'state') require(set(params) == {'uri'} and type(params['uri']) is str, 'params') require(params['uri'] == ctx.allowed_uri, 'authorization') return 'request' require('id' in msg and valid_id(msg['id']) and 'params' not in msg and ('result' in msg) != ('error' in msg), 'envelope') require(type(msg['id']) is type(ctx.expected_ping_id) and msg['id'] == ctx.expected_ping_id, 'correlation') if 'error' in msg: err = msg['error'] require(type(err) is dict and type(err.get('code')) is int and type(err.get('message')) is str, 'error_schema') return 'error_response' require(msg['result'] == {}, 'result_schema') return 'response' def frame(obj): return (json.dumps(obj, allow_nan=False) + '\n').encode('utf-8') if __name__ == '__main__': ctx = Context() req = {'jsonrpc': '2.0', 'id': 0, 'method': 'resources/read', 'params': {'uri': 'policy://returns'}} notice = {'jsonrpc': '2.0', 'method': 'notifications/tools/list_changed'} reply = {'jsonrpc': '2.0', 'id': 'p1', 'result': {}} err = {'jsonrpc': '2.0', 'id': 'p1', 'error': {'code': -32603, 'message': 'Internal error'}} for obj, category in [(req, 'request'), (notice, 'notification'), (reply, 'response'), (err, 'error_response')]: assert validate(frame(obj), ctx) == category bad = [ (b'x' * 4097, ctx, 'size'), (b'{}', ctx, 'frame'), (b'{}\n{}\n', ctx, 'frame'), (b'\xff\n', ctx, 'encoding'), (b'{\n', ctx, 'json'), (b'{"jsonrpc":"2.0","jsonrpc":"1.0"}\n', ctx, 'duplicate_key'), (b'{"n":NaN}\n', ctx, 'json_number'), (b'{"n":1e999}\n', ctx, 'json_number'), (frame([req]), ctx, 'envelope'), (frame({**req, 'result': {}}), ctx, 'envelope'), (frame({**req, 'id': True}), ctx, 'id'), (frame({**req, 'method': 'resources/reed'}), ctx, 'method'), (frame(req), Context(ready=False), 'state'), (frame(req), Context(resources=False), 'state'), (frame({**req, 'params': {'uri': 5}}), ctx, 'params'), (frame({**req, 'params': {'uri': 'policy://private'}}), ctx, 'authorization'), (frame(notice), Context(list_changed=False), 'state'), (frame({**reply, 'id': 'p2'}), ctx, 'correlation'), (frame({**reply, 'error': err['error']}), ctx, 'envelope'), (frame({**err, 'error': {'code': True, 'message': 'bad'}}), ctx, 'error_schema'), (frame({**reply, 'result': []}), ctx, 'result_schema'), ] for raw, state, stage in bad: try: validate(raw, state) except Rejected as exc: assert str(exc) == stage, (str(exc), stage) else: raise AssertionError(f'Accepted invalid fixture: {stage}') print(f'{4 + len(bad)} validation checks passed (4 accepted, {len(bad)} rejected)')
Run:
BASHpython -m py_compile mcp_q33.py python mcp_q33.py
Actual local output on Python 3.13.5:
25 validation checks passed (4 accepted, 21 rejected)Walk through the validation stages#
The decoder checks the frame length before decoding. Its input is one isolated frame; a real stream reader must apply the bound during frame accumulation. The UTF-8 decoder rejects invalid bytes. The JSON object-pairs hook rejects duplicate members rather than allowing the default parser to collapse them. The numeric hooks reject nonstandard constants and floating-point overflow as local interoperability policies.
The validator classifies method-bearing messages separately from responses. Presence of an ID determines the request branch, subject to identifier validation. The restricted resource request checks method, readiness, capability, parameter shape and permitted URI. The notification checks its event contract and supported state. The response branch validates association and either the basic error schema or the expected empty ping result.
The Rejected exception contains only a fixed internal stage name. The test loop asserts the precise failure category, rather than count any exception as a passing rejection. This helps detect accidental regressions in where a message is rejected.
Test coverage#
| Checks | Coverage |
|---|---|
| 4 accepted | Resource request, catalog notification, ping result and RPC error response |
| 8 rejected | Oversize, incomplete frame, two frames, invalid UTF-8, broken JSON, duplicate key, NaN and floating-point overflow |
| 4 rejected | Array envelope, method/result mixture, boolean ID and unknown fixture method |
| 5 rejected | Unready state, unavailable resource feature, wrong URI type, denied URI and unsupported catalog event |
| 4 rejected | Wrong response ID, simultaneous result/error, boolean error code and wrong result shape |
The example demonstrates the separation of transport parsing, message category, state, domain permission and result validation. No handler runs and no pending state changes during validation.
Deliberate limitations#
The example is not an MCP server, client, SDK replacement or complete generic JSON-RPC implementation. It assumes one pre-buffered frame, does not implement network reads or streaming assembly, and cannot prevent allocation of a giant input before decode is called. Its 4 KiB limit is an arbitrary fixture policy. It handles only a resource read, catalog notification and ping response. It uses a synthetic mixed-role Context rather than real negotiated direction and session state.
It does not enforce a dedicated JSON depth limit, strict numeric precision for all values, all Unicode constraints, all allowed and forbidden envelope members, extension metadata, request ID uniqueness, real response-origin authentication, concurrency, actual authorization or downstream resource access. The fixture's empty parameter and ping-result restrictions are narrower than full historical MCP, which may permit applicable metadata. The result check is a local exact-empty-object requirement.
It returns local rejection categories rather than wire errors. Valid error responses are accepted classifications, not successful business outcomes. It neither sends responses to notifications nor tests actual transport behavior. Use the revision-compatible official SDK for real protocol schemas and dispatch, combined with bounded transport parsing and independently enforced application policies.
11. Practical production acceptance criteria#
For an actual MCP gateway or support assistant, separate the validation interface from the operation handlers. The transport adapter receives bounded frames. The protocol implementation parses and classifies messages using the selected revision. The session layer supplies trusted state. The handler receives validated inputs plus authenticated context, not an arbitrary decoded message with a user-supplied identity.
Before deploying, verify that invalid requests do not invoke privileged handlers, invalid responses do not resolve unrelated pending operations, and unexpected notifications do not update another session's state. Confirm that valid failure outcomes remain distinguishable from malformed messages.
Include integration tests using the actual client and server SDK versions and chosen transport. Test partial and combined transport reads, reconnection, malformed messages, invalid schemas, unsupported capabilities and permissions. Record observed behavior rather than assume that a local unit test establishes protocol compliance.
For observability, track bounded counts of frame rejection, JSON parse failure, invalid envelope, invalid parameters, unsupported operation, authorization denial and unexpected response. Keep these distinct from successful responses that report business rejection or tool errors.
Interview-ready answer#
An MCP implementation validates incoming messages by first establishing safe transport framing and encoding, parsing bounded JSON, classifying the message into request, notification or response, and applying the relevant protocol and method-specific schemas. It then checks the trusted session, lifecycle, direction and negotiated capabilities. Requests require independent authorization and domain validation before execution; notifications require appropriate event handling without a JSON-RPC reply; responses must match the expected request and result contract before resolving state. Defensive implementations enforce resource limits and produce safe stage-specific diagnostics. Valid JSON, valid schema, authorization and business success are different guarantees.
Next lesson: Q34 examines how concurrent requests are associated with their responses using scoped identifiers, pending work, out-of-order completion and safe cleanup.
References
- 1.JSON-RPC 2.0 specificationjsonrpc.org
- 2.RFC 8259rfc-editor.org
- 3.MCP historical specification (2025-06-18)modelcontextprotocol.io
- 4.MCP base protocolmodelcontextprotocol.io
- 5.MCP transportsmodelcontextprotocol.io
- 6.MCP lifecyclemodelcontextprotocol.io
- 7.MCP toolsmodelcontextprotocol.io
- 8.Official MCP Python SDKgithub.com
- 9.Python json documentationdocs.python.org
- 10.OWASP Input Validation Cheat Sheetcheatsheetseries.owasp.org
Related questions
Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation