MCP: Model Context ProtocolBeginnerModule 03 — MCP messages and JSON-RPC
How are JSON-RPC errors represented?
Question 25 of 43 · Updated
On this page
- Direct answer
- 1. Anatomy of an error response
- Example: a safe parameter diagnostic
- 2. The five standard JSON-RPC error codes
- 3. Parse error versus invalid request
- Parse error: -32700
- Invalid Request: -32600
- 4. Method not found versus invalid parameters
- Method not found: -32601
- Invalid params: -32602
- 5. Internal errors and reserved code ranges
- 6. Correlation and the null-ID nuance
- What about notifications?
- 7. Keep the error layer explicit
- Tool execution error example
- 8. Safe error disclosure
- 9. Tested practical example: construct and classify errors
- What was tested
- Deliberate limitations
- 10. Diagnose before retrying
- 11. Common implementation mistakes
- Interview-ready answer
Direct answer#
JSON-RPC 2.0 represents a protocol error using an error object in a response envelope. The error object has a required integer code, a required string message and an optional data member carrying additional information. For a response to an identifiable request, the envelope repeats the original request ID and contains error rather than result.
For example, if an initialized MCP peer receives an unsupported RPC method, it may return:
JSON{ "jsonrpc": "2.0", "id": "request-21", "error": { "code": -32601, "message": "Method not found" } }
The numeric code provides a machine-readable failure category; the message provides a short human-readable explanation. Optional data can supply safe, structured details when the applicable contract defines their meaning.
A JSON-RPC error is distinct from an HTTP failure, an MCP tool result with isError set to true, and a valid business result reporting that an operation was rejected.
Learning continuity: Q27 introduced the two response branches and Q29 explained identifiers. Q30 covered method and parameter dispatch. Q31 concentrates on the error object, standardized codes and failure classification. Q32 covers envelope versus payload boundaries, Q33 comprehensive message validation, and Q165–174 detailed error handling, retry decisions, tool-error mapping and actionable errors.
Verification scope: Prepared under authorized offline research and changelog exceptions, using the historical MCP 2025-06-18 specification as a reference baseline rather than claiming it is the latest revision. Official references were not checked live. The Python 3.13.5 standard-library teaching example was syntax-compiled and executed locally: all 14 error-representation checks passed. It demonstrates a deliberately restricted generic JSON-RPC request handler with an MCP-shaped resource operation, not a conformant MCP server. The MCP SDK and Mermaid CLI were unavailable locally; actual SDK/transport interoperability and Mermaid parsing/frontend rendering remain unverified.
1. Anatomy of an error response#
The diagram illustrates the generic error response structure. For ordinary correlated MCP responses, use a valid matching identifier as required by the selected MCP revision.
| Field | Required? | Meaning |
|---|---|---|
| jsonrpc | Yes | Exact string "2.0" |
| id | Yes in the generic error response | Original request ID when known; generic JSON-RPC specifies null when it cannot be determined |
| error | Yes for the error branch | Object describing the error |
| error.code | Yes | Integer identifying the failure category |
| error.message | Yes | Short string describing the error |
| error.data | No | Additional information defined by the sender or applicable contract |
Generic JSON-RPC permits any JSON value for error.data, including a primitive or a structured object. A higher-level protocol or application may constrain its meaning or shape. Do not assume that every data object has a standardized set of fields.
A response cannot contain both result and error. An empty result is not an alternative representation of a failure, and an empty error object is not sufficient because its required members are absent.
Example: a safe parameter diagnostic#
JSON{ "jsonrpc": "2.0", "id": 12, "error": { "code": -32602, "message": "Invalid params", "data": { "field": "uri" } } }
Here the field member is an illustrative application-defined diagnostic, not a universal JSON-RPC or MCP field. It helps the caller identify the failing parameter without echoing confidential values.
Clients should use the code and documented structured data rather than parse arbitrary words in the message. Messages can be localized or changed for clarity. The code's meaning should remain stable.
2. The five standard JSON-RPC error codes#
| Code | Standard message | Meaning |
|---|---|---|
| -32700 | Parse error | The receiver could not parse the supplied JSON |
| -32600 | Invalid Request | The JSON value is not a valid Request object |
| -32601 | Method not found | The RPC method does not exist or is unavailable |
| -32602 | Invalid params | Parameters for the requested method are invalid |
| -32603 | Internal error | An internal JSON-RPC error occurred |
These are generic JSON-RPC 2.0 error categories. MCP uses the underlying framework together with its own schemas, method rules and additional defined errors where applicable.
The distinctions help diagnose the failure. A parser cannot validate method parameters if it cannot first decode the JSON. A valid JSON object can still fail the RPC envelope contract. An acceptable envelope can identify a nonexistent method, and a known method can receive invalid parameters.
The error code describes the detected failure category. It does not, by itself, establish whether an underlying side effect occurred or whether retrying is safe.
3. Parse error versus invalid request#
Parse error: -32700#
Suppose the incoming message is truncated:
{"jsonrpc":"2.0","id":1,"method":It is not valid JSON. Generic JSON-RPC represents a parse error using:
JSON{ "jsonrpc": "2.0", "id": null, "error": { "code": -32700, "message": "Parse error" } }
The receiver cannot safely infer the original identifier from a partially parsed fragment. Even if the characters appear to include id 1, the message was not successfully decoded.
This example is a generic JSON-RPC diagnostic. It must not be treated as a normal correlated MCP response. See section 6 for the historical MCP schema boundary.
Invalid Request: -32600#
Now suppose the incoming value is syntactically valid JSON but does not constitute a JSON-RPC Request object:
JSON{"action":"lookup","sku":"A12"}
A generic JSON-RPC implementation can classify this as Invalid Request. If an identifier cannot be determined, the generic error response uses null.
JSON{ "jsonrpc": "2.0", "id": null, "error": { "code": -32600, "message": "Invalid Request" } }
The first problem occurs at JSON decoding; the second at message validation. Do not label every malformed envelope a parse error.
An MCP-specific receiver must also distinguish ordinary requests from valid notifications and responses. Receiving a valid response is not the same as receiving an invalid request merely because the message has no method. Q33 develops full message classification.
4. Method not found versus invalid parameters#
Assume an initialized MCP server exposes resources.
Method not found: -32601#
The client sends a request with a misspelled method:
JSON{ "jsonrpc": "2.0", "id": "r-4", "method": "resources/reed", "params": {"uri": "policy://returns"} }
The receiver recognizes the envelope but cannot dispatch the unsupported method. An illustrative correlated error is:
JSON{ "jsonrpc": "2.0", "id": "r-4", "error": {"code": -32601, "message": "Method not found"} }
Fixing the spelling or using a compatible supported operation is more useful than blindly retrying the same method.
Invalid params: -32602#
Now the method is correct, but the required resource URI has the wrong type:
JSON{ "jsonrpc": "2.0", "id": "r-5", "method": "resources/read", "params": {"uri": 123} }
The method's parameter contract requires a URI string. An illustrative error is:
JSON{ "jsonrpc": "2.0", "id": "r-5", "error": { "code": -32602, "message": "Invalid params", "data": {"field": "uri"} } }
There is an important MCP-specific nuance for tools. A missing or malformed protocol parameter is different from invalid business input supplied to an otherwise recognized tool. The historical tools specification distinguishes protocol errors such as unsupported methods or unavailable tool names from tool-originated errors reported within a tool result. Tool-specific input validation may be represented as a tool execution error to support useful correction by the host or model. Apply the relevant method-specific specification and SDK behavior instead of mapping every bad argument mechanically to -32602.
Likewise, a missing resource can have a method-specific error representation. Do not infer that every unavailable resource is a missing RPC method.
5. Internal errors and reserved code ranges#
The generic JSON-RPC 2.0 specification reserves the inclusive range -32768 through -32000 for predefined errors. This range includes the five standard codes.
Within that reserved interval, -32099 through -32000 is designated for implementation-defined server errors. A deployment may define codes in that subrange, subject to applicable higher-level protocol constraints. The remaining codes outside the reserved interval are available for application-defined errors under generic JSON-RPC.
| Range | Generic JSON-RPC meaning |
|---|---|
| -32768 through -32000 | Reserved range; do not freely assign arbitrary application errors throughout it |
| -32099 through -32000 | Implementation-defined server errors |
| Outside -32768 through -32000 | Available for application-defined errors, subject to higher-level contracts |
For example, an illustrative server might document -32010 as Service unavailable for one dependency failure:
JSON{ "jsonrpc": "2.0", "id": "r-6", "error": { "code": -32010, "message": "Service unavailable" } }
This code's meaning is invented for the example. It is not a claim that MCP universally standardizes -32010 or that every SDK interprets it identically. Before adopting a code, check the applicable protocol revision, any already assigned codes and the integration contract. A shared registry of codes is useful for independent implementations.
The standard -32603 Internal error category can represent an unexpected internal RPC failure. It is not an instruction to serialize the exception object. A safe response should not expose database credentials, filesystem paths, SQL statements, stack traces or private dependency responses.
Avoid using Internal error for all predictable failures. It loses useful distinctions, makes diagnosis harder and can encourage unnecessary retries.
6. Correlation and the null-ID nuance#
For ordinary responses to identifiable requests, the error response must repeat the original request ID. The receiving requestor associates the response with its actual pending operation, just as for the result branch.
A response with integer ID zero must not be mistaken for an uncorrelated message. A response with string "0" must not be silently matched to integer 0.
Generic JSON-RPC 2.0 says that an error response must use null when the server cannot detect the request ID, such as certain parse and Invalid Request failures. This is an important generic rule, but it is not sufficient to establish valid MCP wire behavior.
The historical MCP 2025-06-18 schema defines request IDs as strings or integers, including in its typed JSON-RPC error envelope. Thus the generic null-ID examples above illustrate JSON-RPC's diagnostic convention, not a valid ordinary correlated MCP error under that schema. Actual MCP handling of malformed or unidentifiable messages must follow the applicable transport, SDK and revision rules. For example, an invalid HTTP request may be rejected at the transport boundary.
A client should never resolve an arbitrary pending request when it receives an uncorrelatable diagnostic. Nor should it invent a numeric ID to make the diagnostic match something. The connection and message classification must remain trustworthy.
What about notifications?#
A valid JSON-RPC notification does not receive a JSON-RPC response, even when the notified method cannot be processed successfully. Local logging and applicable transport behavior are separate matters. A malformed value that cannot be recognized as a valid notification is a different problem and must be classified appropriately.
A notification with no ID is not an ordinary request using null. Q28 covers this distinction in detail.
7. Keep the error layer explicit#
A retail support assistant might request current stock and encounter several different failure types. The correct representation depends on where the failure occurred and what the selected operation promises.
The diagram is an application-oriented classification of received outcomes. A real implementation may detect failures earlier or classify other message types separately.
| Scenario | Appropriate interpretation |
|---|---|
| HTTP connection cannot be established | Transport failure; no usable RPC result |
| Unsupported RPC method yields error -32601 | Protocol error |
| Tool result contains isError true | Tool execution error, not an error envelope |
| Valid stock result reports zero units | Successful observation of zero stock |
| Valid reservation outcome reports insufficient stock | Business rejection according to its contract |
| Response lost after a possible reservation | Uncertain business state; reconciliation may be necessary |
An HTTP status and a JSON-RPC error code belong to different layers. A 401 or 403 can reject an unauthorized HTTP interaction before ordinary RPC execution; there may be no correlated JSON-RPC error body. Do not assume that every HTTP success status implies a successful tool execution.
Tool execution error example#
JSON{ "jsonrpc": "2.0", "id": "stock-17", "result": { "content": [ {"type": "text", "text": "Inventory service unavailable."} ], "isError": true } }
This is an illustrative historical MCP tools/call result. It contains result rather than error. The tool result reports that execution failed, despite the use of the JSON-RPC result branch.
In contrast, the following is an application-level fictional structured business observation:
JSON{"sku":"A12","available_units":0}
Zero is a meaningful observation, not a generic error sentinel. The server needs to encode this using its advertised result contract; the host should not treat it as a dependency failure.
The detailed mapping of failures to protocol errors, tool errors and business outcomes belongs to Q165–169. This lesson focuses on the representation of the JSON-RPC error itself.
8. Safe error disclosure#
An error may be consumed by a host, developer interface or model. Treat it as an external data channel with its own trust boundary.
Imagine the inventory backend raises an exception whose message includes a private service endpoint and a database connection string. Returning the exception text in error.message or error.data would reveal sensitive deployment information to a caller. It may also enter model context or logs.
Prefer a documented, stable external representation:
JSON{ "jsonrpc": "2.0", "id": 23, "error": { "code": -32603, "message": "Internal error" } }
The operator may need protected internal diagnostic records to investigate the issue. Log only what is appropriate for the environment, with access controls and redaction. Avoid recording raw credentials in internal logs as well as in external responses.
| Information | Typical treatment |
|---|---|
| Standard failure code | Include when applicable |
| Short safe message | Include |
| Allowlisted field name | Include if helpful and permitted |
| Sanitized support reference | Optional, if the contract permits it |
| Raw exception and stack trace | Keep out of external errors |
| Authorization tokens and private keys | Never include |
| Private customer records or raw upstream bodies | Do not disclose without a specific justified contract |
An error object can contain malicious text. The host should not execute instructions found in error.message or error.data. For example, a message instructing the model to forward an access token to another service cannot authorize that action.
Do not trust arbitrary retryAfter, approved or retryable values just because they occur in error.data. Honor only documented fields from the correct trusted relationship, and apply local policy. Error disclosure and retry behavior are separate decisions.
9. Tested practical example: construct and classify errors#
The following dependency-free Python exercise illustrates a generic single-request JSON-RPC handler for a fictional resources/read operation. It deliberately demonstrates generic JSON-RPC parse and invalid-request diagnostics with null IDs. Those diagnostics are not asserted to be valid ordinary MCP error envelopes under the historical schema.
The handler uses fixed public messages and an allowlist of safe field names. Backend failures are simulated through an injected function. It uses an illustrative implementation-defined error code for a timeout, and does not forward the exception message.
Save as mcp_q31.py:
PYTHONimport json MESSAGES = { -32700: 'Parse error', -32600: 'Invalid Request', -32601: 'Method not found', -32602: 'Invalid params', -32603: 'Internal error', -32010: 'Service unavailable', } def error_reply(request_id, code, field=None): if request_id is not None and type(request_id) not in (int, str): raise ValueError('Invalid identifier') if type(code) is not int or code not in MESSAGES: raise ValueError('Unregistered code') error = {'code': code, 'message': MESSAGES[code]} if field is not None: if code != -32602 or field not in ('params', 'uri'): raise ValueError('Unsupported public detail') error['data'] = {'field': field} return {'jsonrpc': '2.0', 'id': request_id, 'error': error} def handle(raw, read): # Generic single-request JSON-RPC teaching fixture. try: msg = json.loads(raw) except json.JSONDecodeError: return error_reply(None, -32700) if (type(msg) is not dict or msg.get('jsonrpc') != '2.0' or type(msg.get('method')) is not str): return error_reply(None, -32600) if 'id' not in msg: return None # This fixture ignores notifications. rid = msg['id'] if type(rid) not in (int, str): return error_reply(None, -32600) if msg['method'] != 'resources/read': return error_reply(rid, -32601) params = msg.get('params') if type(params) is not dict: return error_reply(rid, -32602, 'params') if type(params.get('uri')) is not str: return error_reply(rid, -32602, 'uri') try: value = read(params['uri']) except TimeoutError: return error_reply(rid, -32010) except Exception: return error_reply(rid, -32603) return {'jsonrpc': '2.0', 'id': rid, 'result': value} def fail(exc): def read(uri): raise exc return read if __name__ == '__main__': def read(uri): return {'contents': [{'uri': uri, 'text': 'Returns within 30 days.'}]} req = {'jsonrpc': '2.0', 'id': 0, 'method': 'resources/read', 'params': {'uri': 'policy://returns'}} def call(msg, backend=read): return handle(json.dumps(msg), backend) assert handle('{', read) == error_reply(None, -32700) assert call([]) == error_reply(None, -32600) assert call({**req, 'jsonrpc': '1.0'})['error']['code'] == -32600 assert call({**req, 'id': True})['id'] is None assert call({**req, 'method': 'unknown'}) == error_reply(0, -32601) assert call({**req, 'params': []}) == error_reply(0, -32602, 'params') assert call({**req, 'params': {'uri': 7}}) == error_reply(0, -32602, 'uri') assert call(req, fail(TimeoutError('private endpoint'))) == error_reply(0, -32010) reply = call({**req, 'id': 'r1'}, fail(RuntimeError('private credential'))) assert reply == error_reply('r1', -32603) assert 'private' not in json.dumps(reply) assert 'result' not in reply assert call(req)['result'] == read('policy://returns') assert call({'jsonrpc': '2.0', 'method': 'unknown'}) is None try: error_reply(0, -32602, 'private credential') except ValueError: pass else: raise AssertionError('Unsafe detail accepted') print('14 error representation checks passed')
Run:
BASHpython -m py_compile mcp_q31.py python mcp_q31.py
Actual local output on Python 3.13.5:
14 error representation checks passedWhat was tested#
The first four checks exercise invalid JSON, a non-object fixture message, the wrong version and a boolean ID. Three checks exercise unsupported method and invalid resource parameters. The timeout check demonstrates the documented fictional server-error mapping. Three checks confirm the internal-error response with its matching string ID, no private exception text and no simultaneous result member. The remaining checks exercise successful execution, no reply to a method message without an ID, and rejection of an unsupported public diagnostic field.
The example demonstrates how an error construction helper can centralize its external vocabulary and prevent arbitrary exception text from being returned. The safe field detail is explicitly allowlisted rather than derived from a raw backend error.
Deliberate limitations#
This is not a full generic JSON-RPC implementation or a revision-conformant MCP implementation. It deliberately handles one ordinary request at a time, rejects arrays rather than implementing generic batching, rejects null and fractional request IDs under its local policy, and returns generic null-ID diagnostics for malformed messages. It assumes bounded string input and does not detect all invalid JSON extensions, duplicate keys, invalid envelope members, session ID reuse or all malformed notifications. Its no-ID branch ignores method messages after minimal classification, rather than implementing actual notification handlers.
The resource operation is simulated. It does not check URI semantics, resource availability, actor identity or authorization, actual backend result validity or real timeouts. The injected function receives any string URI and returns a fictional policy. Catching all Exception values is a deliberately simplified boundary; a production handler should distinguish known failures, safely record unexpected errors and handle asynchronous cancellation appropriately.
The timeout code is a fixture-specific choice, not a standardized MCP mapping. The tests do not prove that all secrets are excluded from every possible response or that real errors are safe to retry. No live resource, actual network or SDK operation was exercised.
10. Diagnose before retrying#
The error category helps determine the next investigation, but it is not a complete retry policy.
| Error | Sensible first action |
|---|---|
| Parse error | Inspect serialization and framing |
| Invalid Request | Inspect envelope structure and applicable revision |
| Method not found | Check exact method, implementation and supported features |
| Invalid params | Inspect method schema and the relevant input |
| Internal error | Investigate safely using service diagnostics |
| Documented dependency error | Consult the backend contract, deadline and retry policy |
Blindly retrying a misspelled method or malformed parameter is unlikely to help. Retrying an uncertain write may cause duplicate side effects unless the authoritative service implements suitable idempotency and reconciliation.
A request ID correlates one protocol exchange, not an enduring business operation. A retry that is actually a new request requires a new ID under historical MCP's non-reuse rule. Q170–171 and Q230–231 develop deadlines, retry classification and uncertain business outcomes.
In operational monitoring, record error category and code, trusted connection identity, method and sanitized correlation information. Track protocol errors separately from tool execution failures and domain rejection rates. Avoid treating all failures as one metric.
11. Common implementation mistakes#
| Mistake | Better approach |
|---|---|
| Use result and error together | Choose the prescribed mutually exclusive outcome branch |
| Return string codes such as "-32602" | Preserve the required integer code |
| Expose raw exception text | Use safe documented messages and controlled details |
| Guess the failed request ID | Correlate only using verified request association |
| Assume generic null-ID errors are ordinary MCP responses | Follow the selected MCP schema and transport rules |
| Assign arbitrary application codes inside reserved ranges | Respect the standard and higher-level code registry |
| Treat every tool failure as an RPC error | Preserve method-specific tool and business result semantics |
| Automatically retry every internal error | Evaluate side effects, deadlines and service guarantees |
Interview-ready answer#
A JSON-RPC error response contains jsonrpc set to "2.0", the corresponding request ID when identifiable, and an error object instead of result. The error requires an integer code and a string message; optional data can carry safe additional details. Standard codes include -32700 for Parse error, -32600 for Invalid Request, -32601 for Method not found, -32602 for Invalid params and -32603 for Internal error. The range -32099 through -32000 is reserved for implementation-defined server errors within the broader reserved interval. Generic JSON-RPC uses null when a request ID cannot be determined; ordinary historical MCP correlated errors use the applicable string or integer ID schema. A protocol error must be distinguished from transport failures, tool results marked isError and valid business rejections. Safe implementations preserve meaningful failure categories without leaking internal details.
Next lesson: Q32 examines the difference between MCP protocol envelopes, content blocks and business payloads, connecting the message structures to application data contracts.
References
- 1.JSON-RPC 2.0 specification, section 5.1jsonrpc.org
- 2.RFC 8259rfc-editor.org
- 3.MCP historical specification (2025-06-18)modelcontextprotocol.io
- 4.MCP base protocolmodelcontextprotocol.io
- 5.MCP toolsmodelcontextprotocol.io
- 6.MCP resourcesmodelcontextprotocol.io
- 7.MCP transportsmodelcontextprotocol.io
- 8.OWASP Error Handling Cheat Sheetcheatsheetseries.owasp.org
- 9.Official MCP Python SDKgithub.com
- 10.Python json documentationdocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation