MCP: Model Context ProtocolBeginnerModule 03 — MCP messages and JSON-RPC

How is an MCP request message structured?

Question 20 of 43 · Updated

On this page

Direct answer#

An MCP request is a JSON-RPC 2.0 message that asks the receiving participant to perform a named protocol operation and return a response. In the historical MCP 2025-06-18 specification, the request contains three required envelope fields: jsonrpc, id and method. A params object carries the method-specific input when needed, including supported request metadata.

For example, after initialization and confirmation of the appropriate server capability, a client might invoke a stock lookup:

JSON
{ "jsonrpc": "2.0", "id": "req-101", "method": "tools/call", "params": { "name": "stock", "arguments": { "sku": "A12" } } }

The method identifies the MCP protocol operation, tools/call. The name identifies the particular tool, stock. Its arguments contain the application-level input, sku. The request ID associates the eventual response with this request.

A syntactically correct request is not necessarily executable. The receiver must also check the supported MCP revision, lifecycle state, negotiated capabilities, method-specific schema and authorization. The tool implementation must validate its business inputs.

Learning continuity: Q25 explained why MCP uses JSON-RPC 2.0. This lesson explains how to read and construct one request envelope. Q27 covers response structure, Q28 notifications, Q29 identifier rules, Q30 method and parameter design, Q31 errors, Q32 envelope versus content/payload boundaries, Q33 comprehensive message validation and Q34 concurrent correlation. Those later lessons remain distinct.

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 specification. Official links were not live-verified. The standard-library Python fixture was syntax-compiled and executed locally on Python 3.13.5: all 14 checks passed (2 accepted, 12 rejected). It validates a deliberately restricted stock request, not the complete MCP specification. The MCP SDK and Mermaid parser were unavailable locally; real SDK/transport interoperability and live website rendering remain unverified.

1. Read the four parts of the envelope#

FieldRequired?Expected representationPurpose
jsonrpcYesExact string "2.0"Identifies the JSON-RPC version
idYes for a request expecting a responseString or integer in the historical MCP baselineCorrelates the request with its response
methodYesStringIdentifies the MCP operation
paramsDepends on the operationMethod-specific object in MCPSupplies arguments and supported metadata

This table describes requests in the selected historical MCP revision, not all possible generic JSON-RPC messages.

Generic JSON-RPC 2.0 permits structured positional array parameters as well as named object parameters. MCP uses its own typed method contracts with object-shaped params. Generic JSON-RPC also permits ID forms that MCP restricts. Always follow the MCP schema rather than treating generic JSON-RPC validity as sufficient.

Loading diagram…

The diagram shows the nesting of a tools/call request. The name and arguments fields belong inside params; they are not universal top-level members. Other MCP methods have different parameter contracts. The ordering of JSON object members does not establish their meaning.

2. The jsonrpc version marker#

The value of jsonrpc must be the string "2.0". It is not a numeric value and it is not the MCP specification revision.

These examples are incorrect:

JSON
{"jsonrpc":2.0,"id":1,"method":"ping"}
JSON
{"jsonrpc":"2025-06-18","id":1,"method":"ping"}

The first uses a JSON number instead of the required string. The second substitutes an MCP revision for the JSON-RPC version.

An initialize request illustrates how the two version concepts coexist:

JSON
{ "jsonrpc": "2.0", "id": 1, "method": "initialize", "params": { "protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": { "name": "retail-client", "version": "1.0.0" } } }

Here:

  • jsonrpc identifies the underlying message protocol.
  • params.protocolVersion proposes the MCP specification revision.
  • params.clientInfo.version identifies the client software in this fictional example.

The server's response and subsequent lifecycle messages establish the applicable communication state. Q36–41 examine initialization and negotiation in detail. Do not copy protocolVersion into every ordinary request merely because it appears in initialize. Transport-specific version headers, where required, are separate from the JSON-RPC envelope.

3. The request identifier#

The id field identifies a request that expects a response. In the historical MCP baseline, a request ID is a string or integer, must not be null, and must follow the applicable uniqueness rules within the same session and requesting participant.

Valid illustrative forms include:

JSON
{"jsonrpc":"2.0","id":0,"method":"ping"}
JSON
{"jsonrpc":"2.0","id":"inventory-17","method":"ping"}

Numeric zero is a valid identifier; do not reject it merely because it is false-like in a programming language. Boolean values are not integer identifiers in the protocol even though Python's bool is a subclass of int.

The following are invalid MCP request IDs in this baseline:

JSON
{"jsonrpc":"2.0","id":null,"method":"ping"}
JSON
{"jsonrpc":"2.0","id":true,"method":"ping"}

A notification omits the id member entirely. Missing id is not necessarily malformed JSON-RPC; it indicates that the message should be examined as a potential notification rather than as a request expecting a response. Whether its method is an actual supported MCP notification remains a separate question.

Use identifiers that survive serialization and comparison without precision loss. A string ID can avoid cross-language integer-precision problems. Do not use a request ID as a credential, approval token or business idempotency key. Q29 and Q34 cover allocation, reuse restrictions and pending-request correlation.

4. The method identifies the protocol operation#

The method value tells the receiver what operation is being requested. The historical MCP specification defines method names and their associated contracts.

MethodIntended operation
initializeBegin compatible lifecycle negotiation
pingCheck responsiveness
tools/listDiscover tool descriptors
tools/callInvoke a named tool
resources/readRetrieve identified resource content
prompts/getRetrieve a named prompt with applicable arguments

Method names are not URLs or arbitrary tool names. For example, invoking an advertised stock tool does not use method stock unless a separate supported extension actually defines that protocol method. The normal tool invocation uses method tools/call and params.name stock.

The receiver must match the applicable method contract rather than infer a similar name. Method support also depends on the lifecycle and negotiated features. A tools/call message can be correctly structured but inappropriate before initialization or when the server does not support tools.

In generic JSON-RPC, names beginning with rpc. are reserved for RPC-internal methods. Use the actual MCP method names and applicable extension rules rather than inventing names that a compatible peer is expected to recognize.

Q30 will develop method naming and parameter schema design. The focus here is the position and purpose of method within the envelope.

5. Parameters: the nested method-specific input#

The params member is optional at the general request level, but individual methods may require a particular parameter object. There is no universal argument schema shared by every operation.

Example A: ping#

JSON
{"jsonrpc":"2.0","id":1,"method":"ping"}

A minimal ping illustrates a method that needs no business arguments. In the historical schema, applicable request metadata can still be supplied where supported.

Example B: discover tools#

JSON
{"jsonrpc":"2.0","id":2,"method":"tools/list"}

A subsequent discovery request may include a pagination cursor if the previous result supplied one:

JSON
{ "jsonrpc": "2.0", "id": 3, "method": "tools/list", "params": { "cursor": "opaque-next-page-token" } }

The cursor is an illustrative opaque value, not a universal token. A real client should use the value returned by the server and follow the applicable pagination rules. It should not invent or interpret a cursor as a page number.

Example C: call a tool#

JSON
{ "jsonrpc": "2.0", "id": 4, "method": "tools/call", "params": { "name": "stock", "arguments": { "sku": "A12" } } }

For the historical tools/call contract, the tool name is required and the arguments object is optional at the method-schema level. The specific tool can require arguments through its advertised input schema. The fictional stock tool requires sku, so omitting arguments is invalid for that tool even though the generic method may allow an omitted arguments object.

Example D: read a resource#

JSON
{ "jsonrpc": "2.0", "id": 5, "method": "resources/read", "params": { "uri": "policy://returns" } }

The URI is an application-defined identifier. This request does not mean that the client opens a local file or visits an HTTP URL directly. The server interprets the resource identifier according to its supported capability contract.

These examples illustrate alternative supported requests after the appropriate lifecycle setup. They are not a complete interaction transcript. The dedicated tools, resources and prompts modules examine the contracts in depth.

6. MCP-specific request metadata#

The historical MCP request schema includes an optional params._meta object for supported protocol metadata. One example is progressToken, used by an application that requests progress information for an operation.

JSON
{ "jsonrpc": "2.0", "id": "lookup-5", "method": "tools/call", "params": { "name": "stock", "arguments": {"sku": "A12"}, "_meta": { "progressToken": "progress-5" } } }

The progress token is distinct from the request ID. It identifies associated progress reporting under the applicable protocol rules; the request ID identifies the request-response interaction. Supplying a progress token does not guarantee that a particular server will emit progress messages.

The request metadata belongs in params._meta, not in the tool's arguments object. The tool arguments must match the tool's own input schema. Moving progressToken into arguments could cause the stock tool to reject the request or misinterpret it as business data.

Do not treat metadata as a universal place for authentication claims, credentials or model-generated permissions. The server derives authority from its validated authorization context. Extension metadata must follow the applicable specification's extension and naming rules, and unsupported metadata should not be presumed to have meaningful effects.

The example uses a string progress token to avoid numeric representation ambiguity. The historical type permits string or numeric values under its schema; consult the exact revision and SDK for constraints. Q159 covers progress reporting and token lifecycle.

7. Two levels of schema for a tool call#

A common beginner mistake is to validate only the JSON-RPC envelope and assume the request is ready for execution. There are several distinct validation layers.

For tools/call, the method-level params object contains the name of a tool and the optional arguments object. The discovered tool descriptor supplies a separate input schema describing the allowed business arguments.

For example, the inventory server could advertise this fictional input schema:

JSON
{ "type": "object", "properties": { "sku": { "type": "string", "minLength": 1, "maxLength": 16, "pattern": "^[A-Za-z0-9]+$" } }, "required": ["sku"], "additionalProperties": false }

An argument object containing sku A12 satisfies this example. A numeric sku, an empty value or an extra tenant field does not. These are invented business restrictions for the stock tool, not universal MCP restrictions.

The server must also authorize the actual resource. A valid SKU may belong to another tenant, or the user may lack permission to read it. JSON Schema validation cannot establish ownership or current business state.

Do not confuse the tool's input schema with the top-level request envelope. The schema validates arguments, not the jsonrpc and id fields. Likewise, an LLM's provider-specific tool call is not already an MCP message; a trusted adapter must construct an appropriate protocol request.

8. Valid versus invalid request examples#

Example conditionInterpretation
Exact version string, valid ID, recognized method and correct paramsStructurally valid request, subject to further checks
Missing jsonrpc or wrong version typeInvalid protocol envelope
Null or boolean IDInvalid MCP request ID
Missing IDNot a request expecting a response; check notification rules
tools/call with no tool nameInvalid method-specific parameters
tools/call with an unknown tool nameValid shape may still identify an unavailable operation
Array instead of MCP params objectDoes not match the applicable MCP method contract
Correct tool name but wrong SKU typeInvalid arguments for the fictional stock tool
Correct request before lifecycle readinessStructurally valid but inappropriate for current protocol state
Correct request from an unauthorized actorNot permitted to execute

The distinction between structural validity and executability is crucial. Do not label all rejections as malformed JSON. A well-formed request can fail because the method or tool is unavailable, permission is absent, or a domain invariant prevents execution.

The receiver should return the appropriate protocol or application outcome according to the supported schema and method. Detailed response and error handling belongs to the next lessons.

9. Serialization and transport framing#

Before a message can travel over a connection, the sender serializes it into valid JSON. Build a typed object or dictionary and let a trusted serializer handle escaping and representation. Avoid constructing messages by interpolating untrusted strings into raw JSON.

For example, a Python application can serialize a request using json.dumps and decode it using json.loads. The serialization layer must preserve types, especially identifiers and numeric values. JSON permits neither NaN nor Infinity as standard numeric literals, even though some language libraries accept them by default. Configure appropriate strictness for protocol data.

Duplicate object member names are another interoperability risk. Different parsers can interpret repeated keys differently. Rejecting ambiguous duplicates is a prudent validation policy; it is not a claim that every JSON parser rejects them automatically.

The transport determines how messages are carried. In the historical stdio transport, each message is serialized as a single newline-delimited JSON message, so pretty-printed examples must be compacted for actual transmission. An escaped newline within a JSON string is different from a physical delimiter between messages. For Streamable HTTP, follow its applicable HTTP content, session and version requirements.

The serialized envelope does not contain arbitrary HTTP authentication headers. Credentials and transport metadata belong to the appropriate trusted connection layer. The historical 2025-06-18 revision does not support JSON-RPC batching; sending an array of messages as a batch is not a valid ordinary request under that baseline.

10. A request's validation path#

Loading diagram…

This is a conceptual validation path, not a normative ordering of every check. Transport authentication, size limits and policy checks may occur earlier. Some messages must be classified as notifications or responses rather than rejected simply because they are not requests.

The important architectural invariant is that untrusted input must not reach a privileged operation merely because it can be parsed as JSON. Use a revision-compatible SDK for the protocol-specific validation, and retain application-specific validation and authorization around the handler.

Q33 will cover comprehensive incoming message validation and failure classification. This lesson provides the request-specific mental model.

11. Tested Python exercise: validate one stock request#

The following dependency-free program parses and validates one deliberately restricted request type, tools/call for a fictional stock tool. It checks the envelope, request ID, method parameters, tool arguments and optional progress metadata. It rejects ambiguous duplicate members and nonstandard JSON numeric constants.

The fixture is stricter than a general MCP implementation: it allows only the listed envelope and params fields, only a single method and tool, and string or integer progress tokens. It does not define the complete set of permitted MCP extensions or metadata types. Its ValueError exceptions represent local validation failures, not actual JSON-RPC error responses.

Save as mcp_q26.py:

PYTHON
import json def validate(raw): def pairs(items): result = {} for key, value in items: if key in result: raise ValueError('Duplicate member') result[key] = value return result def bad_constant(value): raise ValueError('Non-JSON number') message = json.loads(raw, object_pairs_hook=pairs, parse_constant=bad_constant) if type(message) is not dict or message.get('jsonrpc') != '2.0': raise ValueError('Invalid envelope') if 'id' not in message or type(message['id']) not in (str, int): raise ValueError('Invalid request ID') if message.get('method') != 'tools/call': raise ValueError('Unsupported fixture method') if set(message) - {'jsonrpc', 'id', 'method', 'params'}: raise ValueError('Unexpected envelope member') params = message.get('params') if type(params) is not dict or set(params) - {'name', 'arguments', '_meta'}: raise ValueError('Invalid params') if params.get('name') != 'stock': raise ValueError('Unsupported fixture tool') args = params.get('arguments') if (type(args) is not dict or set(args) != {'sku'} or type(args['sku']) is not str or not 1 <= len(args['sku']) <= 16 or not args['sku'].isascii() or not args['sku'].isalnum()): raise ValueError('Invalid stock arguments') if '_meta' in params: meta = params['_meta'] if type(meta) is not dict: raise ValueError('Invalid metadata') if 'progressToken' in meta and type(meta['progressToken']) not in (str, int): raise ValueError('Invalid progress token') return message if __name__ == '__main__': req = {'jsonrpc': '2.0', 'id': 0, 'method': 'tools/call', 'params': {'name': 'stock', 'arguments': {'sku': 'A12'}}} assert validate(json.dumps(req).encode('utf-8')) == req with_meta = {**req, 'id': 'r1', 'params': {**req['params'], '_meta': {'progressToken': 'p1'}}} assert validate(json.dumps(with_meta)) == with_meta invalid = [ json.dumps({**req, 'jsonrpc': '1.0'}), json.dumps({k: v for k, v in req.items() if k != 'id'}), json.dumps({**req, 'id': None}), json.dumps({**req, 'id': True}), json.dumps({**req, 'method': 'stock'}), json.dumps({**req, 'params': []}), json.dumps({**req, 'params': {'name': 'stock'}}), json.dumps({**req, 'params': {'name': 'stock', 'arguments': {'sku': 12}}}), json.dumps({**req, 'params': {**req['params'], '_meta': {'progressToken': False}}}), '{"jsonrpc":"2.0","id":1,"id":2,"method":"ping"}', json.dumps({**req, 'id': float('nan')}), '[' + json.dumps(req) + ']', ] for raw in invalid: try: validate(raw) except ValueError: pass else: raise AssertionError('Invalid fixture accepted') print('14 request validation checks passed (2 accepted, 12 rejected)')

Run:

BASH
python -m py_compile mcp_q26.py python mcp_q26.py

Actual local output on Python 3.13.5:

14 request validation checks passed (2 accepted, 12 rejected)

What the tests establish#

The accepted cases verify a UTF-8 serialized request with numeric ID zero and a request with a string ID and progress token. The twelve rejected cases cover the wrong version, absent ID, null ID, boolean ID, wrong fixture method, array params, missing required stock arguments, numeric SKU, boolean progress token, duplicate member names, NaN and an array of messages.

The object_pairs_hook sees member pairs before they are collapsed into a dictionary. This makes it possible to reject duplicate keys, including nested duplicates. The parse_constant hook rejects the nonstandard constants that Python's JSON decoder otherwise accepts. The NaN test deliberately uses the serializer's permissive default to generate invalid JSON for this decoder; normal outgoing messages should use allow_nan=False where appropriate.

Using type(value) rather than isinstance(value, int) prevents Python booleans from passing the integer checks. The params and arguments checks demonstrate that the two objects serve different purposes.

The code validates a single message at a time. It neither allocates IDs nor enforces uniqueness across an actual session. The absence-of-ID rejection applies to this request-only validator; a real protocol dispatcher would separately recognize supported notifications.

Production limitations#

This program is not a general schema validator, secure transport parser or MCP server. It assumes bounded inputs and does not impose size/depth limits, enforce strict UTF-8-only transport framing, validate all Unicode and numeric edge cases, authenticate the caller, negotiate revisions, handle responses or notifications, authorize resources, or execute a stock lookup. It accepts arbitrary additional metadata entries within the _meta object without validating their application semantics. Its strict allowlist is a local fixture policy, not a universal prohibition on all MCP extension fields.

The tests establish the stated examples, not full conformance. For real integrations use the applicable official SDK and schemas; test message handling across actual client-server pairs and separately test application authorization.

12. Practical production example and troubleshooting#

Suppose a model proposes a stock lookup for A12. A host-side adapter has already selected the trusted inventory server. It verifies that stock is an approved tool, constructs the method and parameters from a trusted route, and lets the client allocate an appropriate request ID and serialize the message.

If the model supplies an unknown field such as tenant, the adapter should validate it against the advertised tool schema rather than forward it blindly. The server independently enforces resource permissions even if the host validation succeeds.

When a request fails, investigate the layer responsible rather than repeatedly changing the model's prompt.

SymptomFirst check
Peer cannot parse the messageJSON encoding, framing and transport
Version errorExact jsonrpc marker and separate MCP negotiation
Request treated as notificationPresence and validity of id
Operation not recognizedExact method and negotiated capabilities
Tool not recognizedparams.name and trusted server catalog
Argument rejectedparams.arguments and tool input schema
Progress not receivedSupported metadata and progress behavior
Valid message but access deniedAuthenticated actor and resource policy

For diagnostics, record sanitized method names, local correlation identifiers, negotiated revision and failure categories. Avoid logging raw confidential parameters or credentials. Keep the distinction between protocol metadata and business input clear.

Interview-ready answer#

An MCP request is a JSON-RPC 2.0 object containing the required jsonrpc version string, a valid request ID and a method name, plus a method-specific params object when needed. For a tool call, method is tools/call, params.name identifies the tool, and params.arguments supplies its business input. Supported request metadata such as a progress token can appear in params._meta. The JSON-RPC version is distinct from the negotiated MCP specification revision. A receiver must validate the envelope, the method's parameter contract, the relevant lifecycle and capabilities, and the underlying authorization and business rules before execution. A notification omits the request ID and is handled under its own rules.

Next lesson: Q27 examines the structure of MCP response messages and how their result or error fields relate to the original request.

References

  1. 1.
  2. 2.
  3. 3.
  4. 4.
    MCP base protocolmodelcontextprotocol.io
  5. 5.
    MCP lifecyclemodelcontextprotocol.io
  6. 6.
    MCP toolsmodelcontextprotocol.io
  7. 7.
    MCP progressmodelcontextprotocol.io
  8. 8.
    MCP transportsmodelcontextprotocol.io
  9. 9.
  10. 10.

Related questions

Explore other topics:Forward Deployed EngineeringAI AgentsLarge Language ModelsRetrieval-Augmented Generation