MCP: Model Context ProtocolBeginnerModule 03 — MCP messages and JSON-RPC
How is an MCP response message structured?
Question 21 of 43 · Updated
On this page
- Direct answer
- 1. The two possible envelope branches
- 2. A complete request and response pair
- 3. Successful responses have method-specific structures
- Example A: an empty result can be valid
- Example B: a tool discovery result
- Example C: a resource read
- Example D: a reusable prompt
- 4. Text content and structured tool results
- 5. JSON-RPC error responses
- Special case: unidentifiable requests
- 6. Exactly one of result and error
- 7. Matching request IDs without losing context
- 8. Distinguish protocol, tool and business outcomes
- 9. Result metadata and serialization
- 10. Tested practical example: validate a stock response
- What was tested
- Deliberate limitations
- 11. How to inspect a response in a real integration
- Interview-ready answer
Direct answer#
An MCP response is a JSON-RPC 2.0 message that reports the outcome of a request. In the historical MCP 2025-06-18 baseline, a normal response to an identifiable request contains the string jsonrpc with value "2.0", the matching request id, and exactly one of two members: result for the successful protocol response branch or error for the JSON-RPC error branch.
For example, a stock lookup might return:
JSON{ "jsonrpc": "2.0", "id": "req-101", "result": { "content": [ {"type": "text", "text": "7 units available"} ] } }
A response containing result is not necessarily evidence that the tool executed successfully or that the user's business objective was achieved. A tool result can contain isError: true, and a successful tool can return a valid domain outcome such as zero available units or an ineligible order.
The receiving client must match the response to the original request, validate the corresponding method's result or error structure, and preserve the outcome for the host application.
Learning continuity: Q25 explained the architectural choice of JSON-RPC, and Q26 introduced request envelopes. Q27 examines their response counterpart, including the shape of success and error branches. Q28 covers notifications, Q29 and Q34 cover IDs and concurrent correlation, Q31 covers error objects in depth, Q32 distinguishes envelopes from content and business payloads, and Q33 covers general message validation. The dedicated tool module develops content types and structured output separately.
Verification scope: Prepared under the authorized offline research and changelog exceptions. MCP 2025-06-18 is the historical reference baseline, not a claim about the latest revision. Official references were not opened live. The Python example was syntax-compiled and executed locally on Python 3.13.5; all 16 checks passed (4 accepted, 12 rejected). It validates responses for a deliberately restricted stock-tool fixture, not the complete protocol. The local MCP SDK and Mermaid CLI were unavailable. Live SDK interoperability, transport behavior and Mermaid parser/frontend rendering remain unverified.
1. The two possible envelope branches#
A response to an ordinary, identifiable MCP request contains a common outer envelope with either a result or an error.
The two branches are alternatives, not independent fields that can both be present. The diagram illustrates the historical MCP response model for a known request. Generic JSON-RPC has special error-response cases when a request identifier cannot be determined; those must not be mistaken for a normal correlated success or error.
| Member | Type and role |
|---|---|
| jsonrpc | Required exact string "2.0", identifying the message framework |
| id | Matches the original request in ordinary correlated responses |
| result | Successful protocol result branch; its object shape depends on the MCP method |
| error | JSON-RPC failure branch, with integer code, message string and optional data |
The generic JSON-RPC specification allows result values determined by the invoked method. MCP defines its own method-specific result objects. Do not assume that a bare number or array is automatically a valid MCP response result simply because generic JSON-RPC permits it.
The JSON-RPC version marker is not the MCP revision. A negotiated MCP protocolVersion is conveyed through the applicable lifecycle and transport rules, rather than substituted for jsonrpc.
2. A complete request and response pair#
Consider the inventory server used throughout the roadmap. After establishing a compatible connection and discovering an approved stock tool, a client might send:
JSON{ "jsonrpc": "2.0", "id": "stock-42", "method": "tools/call", "params": { "name": "stock", "arguments": {"sku": "A12"} } }
The corresponding response might be:
JSON{ "jsonrpc": "2.0", "id": "stock-42", "result": { "content": [ {"type": "text", "text": "Product A12 has 7 available units."} ], "isError": false } }
The matching id associates the message with the original invocation. Notice that the response does not repeat method or params. The client retains the original request context and uses it to choose the correct result schema.
The server's result is illustrative business data. Seven is not a universal stock value, and a model should not treat the textual description as verified current availability beyond the actual observation's semantics and freshness.
For this result, isError: false indicates that the server is not reporting a tool execution error. The host still needs to interpret the observation correctly. Seven available units are not a promise that a future reservation or purchase will succeed.
3. Successful responses have method-specific structures#
Different operations return different result objects. There is no single MCP response content format shared by every method.
| Request method | Illustrative result members |
|---|---|
| ping | An empty result object when no additional supported metadata is supplied |
| initialize | protocolVersion, capabilities and serverInfo, with applicable optional fields |
| tools/list | tools array and optional nextCursor |
| tools/call | content array, optional structuredContent and optional isError |
| resources/read | contents array |
| prompts/get | messages array and optional description |
These examples follow the selected historical specification. They are not complete schemas and do not establish that every server supports every method. A compatible implementation should use its negotiated capabilities and the applicable SDK schemas.
Example A: an empty result can be valid#
JSON{"jsonrpc":"2.0","id":1,"result":{}}
This is a valid illustration of a successful ping response. An empty object is not automatically a missing result. It can be exactly the method's expected outcome.
Conversely, returning an empty object for an operation requiring specific content fields may fail that operation's result contract. Always validate the response against the original method.
Example B: a tool discovery result#
JSON{ "jsonrpc": "2.0", "id": 2, "result": { "tools": [ { "name": "stock", "description": "Return available units for a permitted SKU", "inputSchema": { "type": "object", "properties": {"sku": {"type": "string"}}, "required": ["sku"] } } ] } }
This is an illustrative discovery result, not a call to stock. Discovery returns metadata describing operations; it does not execute those operations. A result containing an empty tools array can be a legitimate discovery outcome.
If a paginated result includes nextCursor, the client treats it as the server's opaque continuation value. It is not the JSON-RPC response ID or a universal page number. The full pagination contract appears later in Q111.
Example C: a resource read#
JSON{ "jsonrpc": "2.0", "id": 3, "result": { "contents": [ { "uri": "policy://returns", "mimeType": "text/plain", "text": "Returns within 30 days." } ] } }
The fictional policy document is contained in a resource result rather than the content array of a tool result. The resource URI and MIME type describe the returned information. The host should still check source, authorization, freshness and applicability before using it.
Example D: a reusable prompt#
JSON{ "jsonrpc": "2.0", "id": 4, "result": { "messages": [ { "role": "user", "content": { "type": "text", "text": "Summarize the verified stock observation." } } ] } }
Retrieving a prompt returns messages for potential use by the host. It does not prove that the host sent those messages to a model or that any tool was invoked.
4. Text content and structured tool results#
A historical tools/call result may include typed content blocks and optional structuredContent. The two representations serve different purposes.
A text block can contain human-readable information or a serialized representation of structured data. Structured content provides an object that compatible consumers can validate and process programmatically.
For example, assume that the discovered stock tool advertises an output schema requiring a string sku and a nonnegative integer available_units. A compatible structured response might be:
JSON{ "jsonrpc": "2.0", "id": "stock-42", "result": { "content": [ { "type": "text", "text": "{\"sku\":\"A12\",\"available_units\":7}" } ], "structuredContent": { "sku": "A12", "available_units": 7 }, "isError": false } }
The historical 2025-06-18 tool specification introduced structured output support. When a tool declares an output schema, the corresponding successful structured result must conform to that schema. A serialized JSON text block is recommended for backward compatibility in the historical structured-output design.
This example deliberately includes equivalent text and structured representations. The client should not add the two values together or treat them as two independent observations. A consumer should use the contractually appropriate representation and handle disagreement safely. If both are present but contradictory, the application should not choose whichever is more convenient without verification.
An actual tool result can also contain other supported content block types. Text-only processing is a limited implementation choice, not a universal rule for all MCP results. The dedicated tool content and structured output lessons, Q51–52, cover these representations in more depth.
For the stock contract, the client should check not only that available_units is a nonnegative integer but also that the returned SKU corresponds to the requested product. A schema-valid result for B34 is not an acceptable observation for A12 merely because its quantity is valid.
5. JSON-RPC error responses#
A protocol-level error response uses error instead of result.
JSON{ "jsonrpc": "2.0", "id": "stock-42", "error": { "code": -32601, "message": "Method not found" } }
This error example illustrates the case of an unsupported RPC method with an identifiable request. It is an alternative response scenario, not a claim that an advertised stock tool must produce this error.
The error object includes a numeric integer code and a message string. Optional data may supply additional information under the applicable contract. Do not interpret arbitrary data as trusted instructions or automatically disclose it to the model.
The generic JSON-RPC standard includes error categories such as invalid request, method not found, invalid parameters and internal error. Their precise meaning, recommended mapping, server-specific codes and safe error messages are covered in Q31 and the later error-handling module.
A protocol error is not an empty successful result. Do not return a fallback count such as zero merely because error is present.
Special case: unidentifiable requests#
Generic JSON-RPC specifies null IDs in certain error responses when the request ID cannot be determined, such as some parse or invalid-request errors. Historical MCP restricts ordinary request IDs to strings or integers and requires matched identifiers for ordinary correlated responses. Implementations must follow their selected MCP schema and error handling rules rather than blindly apply generic JSON-RPC examples.
An uncorrelatable diagnostic or error must not complete a pending request chosen at random. The fixture in this lesson only handles responses to a known request and deliberately rejects null IDs.
6. Exactly one of result and error#
Both response members must not occur in the same ordinary envelope.
Invalid example:
JSON{ "jsonrpc": "2.0", "id": 5, "result": {}, "error": { "code": -32603, "message": "Internal error" } }
A response with neither member is invalid for the same reason: the receiver cannot identify the prescribed outcome branch.
Check member presence rather than truthiness. An empty result object is a meaningful result for certain methods; an error object with invalid fields is still an attempted error branch and must be validated. A JSON member whose value is null is present, not absent. For an MCP method that requires a result object, result: null does not satisfy the expected shape.
In programming languages with false-like values, a condition such as if response.get("result") can mistakenly reject an empty valid result. Use explicit presence checks followed by schema validation.
Similarly, do not treat a response with both result and error as successful merely because the application prefers the result branch.
7. Matching request IDs without losing context#
The response ID must match the originating request's ID for normal correlated responses. It identifies an interaction; it does not identify the business resource, tool or transaction.
For example, the string "0" and the integer 0 are not interchangeable identifiers. A receiver must preserve their types rather than compare their string representations. Boolean true is not an allowed historical MCP request identifier and should not match integer 1 just because the programming language treats them as equal.
The originating connection and current request context also matter. Q21 showed why independent client sessions must not share a bare-ID pending map. A response on one connection cannot be assumed to belong to another connection with the same ID.
The client uses the stored request context to validate the result. For example, a valid resources/read result is not a valid tools/call result merely because the ID matches.
Do not interpret a response ID as proof that an order was committed. Durable operation identifiers and verified service receipts serve different purposes. Q29 and Q34 will develop ID allocation, uniqueness, reuse and concurrent response correlation.
8. Distinguish protocol, tool and business outcomes#
The result branch means that the peer returned a result using the successful JSON-RPC envelope. It does not by itself guarantee a successful operation at every application layer.
The diagram focuses on tools/call; other methods have their own result semantics and may not define isError.
Consider the following illustrative tool execution error:
JSON{ "jsonrpc": "2.0", "id": "stock-42", "result": { "content": [ {"type": "text", "text": "Inventory service unavailable."} ], "isError": true } }
The result object is inside the result branch, yet the tool reports failure. The host must not interpret the error text as a stock observation. In the historical tool contract, a missing isError flag defaults to the non-error interpretation; the content and business result still need validation.
| Observed outcome | What the host can conclude |
|---|---|
| Transport timeout | No usable response was obtained; actual business state may be uncertain |
| Valid error envelope | The peer reported a JSON-RPC error |
| Valid tool result with isError true | The tool reported an execution error |
| Valid stock result with count 0 | The observed available quantity is zero |
| Valid stock result with count 7 | Seven units were observed; a future reservation still needs authoritative validation |
| Valid domain result reporting an ineligible cancellation | The operation was rejected under its business rules |
A successful HTTP response, a valid JSON-RPC result, and a confirmed business transaction are three different claims. A transport may acknowledge a message without delivering a final result. Likewise, a write may have committed even if the response was lost. Reconciliation and idempotency appear in later modules.
9. Result metadata and serialization#
In the historical MCP schema, supported result objects may contain an optional _meta object. It is located inside the result, not used as a substitute for result or error. Its actual fields and meanings must follow the applicable specification and extension contract.
For example:
JSON{ "jsonrpc": "2.0", "id": "stock-42", "result": { "content": [ {"type": "text", "text": "7 units available"} ], "_meta": {} } }
An empty metadata object is included here only to illustrate placement. Metadata is not business content and need not be displayed to a user or supplied to a model. An implementation may maintain local tracing or authorization records outside the response entirely. Do not assume that every returned metadata field is authoritative or intended for model consumption.
Result metadata is distinct from request params._meta and from metadata or annotations defined for particular content blocks. JSON-RPC error data belongs inside the error object. Transport headers are yet another layer.
Use a standards-compatible serializer to preserve JSON member types and escaping. In the structured output example, text contains an escaped JSON string; structuredContent contains an actual nested object. Decoding the outer response does not automatically turn every text string into a structured object. Parse text as JSON only when the tool's contract says that it represents JSON and appropriate size and validation controls are in place.
Reject ambiguous duplicate member names as a defensive parsing policy. Bound message size before parsing where appropriate, and follow the selected transport's framing and encoding requirements. A pretty-printed documentation example is not necessarily the exact serialized representation transmitted over stdio or HTTP.
10. Tested practical example: validate a stock response#
The following standard-library Python exercise parses a response associated with a known tools/call request for A12. It checks the envelope, exact identifier type and value, result-error exclusivity, basic error fields, optional metadata, text-only content and a deliberately narrow structured stock contract.
The three accepted outcome categories are rpc_error, tool_error and stock_observed. An accepted error response is structurally valid for this fixture; it is not a successful business operation.
Save as mcp_q27.py:
PYTHONimport json def parse_response(raw, expected_id): def pairs(items): obj = {} for key, value in items: if key in obj: raise ValueError('Duplicate member') obj[key] = value return obj def reject_constant(value): raise ValueError('Non-JSON constant') msg = json.loads(raw, object_pairs_hook=pairs, parse_constant=reject_constant) if type(msg) is not dict or msg.get('jsonrpc') != '2.0': raise ValueError('Invalid response envelope') if (type(expected_id) not in (int, str) or 'id' not in msg or type(msg['id']) is not type(expected_id) or msg['id'] != expected_id): raise ValueError('Unmatched response ID') if ('result' in msg) == ('error' in msg): raise ValueError('Require exactly one result or error') if 'error' in msg: err = msg['error'] if (type(err) is not dict or type(err.get('code')) is not int or type(err.get('message')) is not str): raise ValueError('Invalid error object') return 'rpc_error', err result = msg['result'] if type(result) is not dict: raise ValueError('Expected MCP result object') if '_meta' in result and type(result['_meta']) is not dict: raise ValueError('Invalid result metadata') content = result.get('content') if type(content) is not list or any( type(b) is not dict or b.get('type') != 'text' or type(b.get('text')) is not str for b in content): raise ValueError('Expected text-only fixture content') if 'isError' in result and type(result['isError']) is not bool: raise ValueError('Invalid tool error flag') if result.get('isError', False): return 'tool_error', result data = result.get('structuredContent') if (type(data) is not dict or set(data) != {'sku', 'available_units'} or data['sku'] != 'A12' or type(data['available_units']) is not int or data['available_units'] < 0): raise ValueError('Invalid stock result') return 'stock_observed', data if __name__ == '__main__': base = {'jsonrpc': '2.0', 'id': 0, 'result': { 'content': [{'type': 'text', 'text': '{"sku":"A12","available_units":7}'}], 'structuredContent': {'sku': 'A12', 'available_units': 7}, '_meta': {}}} def read(msg, expected=0): return parse_response(json.dumps(msg, allow_nan=False), expected) assert read(base) == ('stock_observed', {'sku': 'A12', 'available_units': 7}) zero = {**base, 'result': {**base['result'], 'content': [{'type': 'text', 'text': '{"sku":"A12","available_units":0}'}], 'structuredContent': {'sku': 'A12', 'available_units': 0}}} assert read(zero)[1]['available_units'] == 0 err = {'jsonrpc': '2.0', 'id': 0, 'error': {'code': -32601, 'message': 'Method not found'}} assert read(err)[0] == 'rpc_error' tool_err = {**base, 'result': {'content': [{'type': 'text', 'text': 'Unavailable'}], 'isError': True}} assert read(tool_err)[0] == 'tool_error' invalid = [ {**base, 'jsonrpc': 2.0}, {**base, 'id': '0'}, {**base, 'id': True}, {**base, 'id': None}, {**base, 'error': err['error']}, {'jsonrpc': '2.0', 'id': 0}, {**err, 'error': {'code': True, 'message': 'Bad code'}}, {**base, 'result': None}, {**base, 'result': {**base['result'], 'content': 'seven'}}, {**base, 'result': {**base['result'], 'isError': 'false'}}, {**base, 'result': {**base['result'], 'structuredContent': {'sku': 'A12', 'available_units': True}}}, {**base, 'result': {**base['result'], '_meta': []}}, ] for msg in invalid: try: read(msg) except ValueError: pass else: raise AssertionError('Invalid response accepted') print('16 response checks passed (4 accepted, 12 rejected)')
Run:
BASHpython -m py_compile mcp_q27.py python mcp_q27.py
Actual local output on Python 3.13.5:
16 response checks passed (4 accepted, 12 rejected)What was tested#
| Accepted fixture | Expected classification |
|---|---|
| Structured result for A12 with seven units | stock_observed |
| Structured result for A12 with zero units | stock_observed |
| Correlated JSON-RPC error | rpc_error |
| Correlated result containing isError true | tool_error |
The twelve rejection cases exercise a numeric version marker, wrong ID type, boolean ID, null ID, simultaneous result and error, missing outcome members, boolean error code, null result, malformed content array, string-valued error flag, boolean stock count and non-object metadata.
The code also includes duplicate-key and nonstandard numeric-constant rejection hooks; those branches were not independently exercised by the sixteen cases. The error branch returns validated basic error fields, not a user-facing explanation. The result branch validates the fixed stock contract and preserves zero as a meaningful observation.
Deliberate limitations#
This is a single-request, text-only, structured-stock teaching fixture. It requires structuredContent for a successful stock result because that is the assumed fixture contract; many actual MCP tools have other valid outputs. It does not support all content block types, generic JSON-RPC error diagnostics, server-initiated requests, notifications, arbitrary method results, complete schema validation, batch handling or concurrent requests.
The expected ID and SKU are trusted fixtures, not dynamically retrieved session state. It does not compare the text block's meaning with the structured result, authenticate the response origin, check freshness, validate error.data or metadata semantics, enforce message size/depth, reject every unexpected member or implement strict transport framing. No actual tool was invoked. The sixteen tests establish only the specified behaviors. Use a compatible SDK, full method-specific schemas and trusted application policy in a real implementation.
11. How to inspect a response in a real integration#
A practical client or SDK starts with the current protocol session and the original outstanding request. It decodes and validates a bounded message, determines whether it is a response, checks the identifier and validates the selected result or error schema. An invalid message should not accidentally resolve a different pending request.
The host then uses the verified result to make an application decision. It may extract a structured observation, show an error to the user, seek clarification or reconcile an uncertain write. A model should receive only relevant authorized information; a raw error object may contain internal details that should not be disclosed.
| Symptom | Inspect first |
|---|---|
| Response cannot be decoded | Encoding, framing and JSON parser |
| Response version is unexpected | JSON-RPC marker and applicable MCP session |
| Wrong or missing ID | Original request association and connection context |
| Both result and error appear | Envelope classification |
| Result has unexpected shape | Method-specific response schema |
| Tool returns isError true | Tool execution outcome, not ordinary success |
| Data is well formed but belongs to another SKU | Business identity and result verification |
| No response after a side effect | Authoritative state and reconciliation |
When debugging, capture sanitized method and connection identities, local correlation information, response branch and failure category. Avoid dumping sensitive result content or credentials into logs. Tests of response structure should be separate from tests of actual backend correctness and authorization.
Interview-ready answer#
An MCP response is a JSON-RPC 2.0 object with the exact jsonrpc version marker, the original request's matching identifier for an ordinary correlated response, and exactly one of result or error. The result is method-specific: a ping can return an empty object, discovery returns descriptors, and a tool invocation returns content with optional structured output, error status and supported metadata. An error contains an integer code, message and optional data. The client must validate the envelope, request association and result schema, while the host distinguishes JSON-RPC success from tool execution and authoritative business success. The response's ID is a correlation identifier, not proof that a business operation completed.
Next lesson: Q28 examines MCP notifications and why their message and response semantics differ from requests.
References
- 1.JSON-RPC 2.0 specificationjsonrpc.org
- 2.JSON Data Interchange Format (RFC 8259)rfc-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 promptsmodelcontextprotocol.io
- 8.MCP lifecyclemodelcontextprotocol.io
- 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