MCP: Model Context ProtocolBeginnerModule 03 — MCP messages and JSON-RPC
What are JSON-RPC request IDs, and why are they important?
Question 23 of 43 · Updated
On this page
- Direct answer
- 1. What problem does a request ID solve?
- 2. Valid request ID types
- 3. IDs are scoped to a requestor and session
- 4. Choose an allocation strategy
- 5. Numeric precision and serialization
- 6. How the response uses the ID
- 7. Notifications do not consume request IDs
- 8. Different identifiers serve different purposes
- 9. Tested practical example: allocate and validate IDs
- What the tests establish
- Production limitations
- 10. Common mistakes and troubleshooting
- Interview-ready answer
Direct answer#
A JSON-RPC request ID is an identifier assigned by the sender of a request so that the receiver's response can be associated with that particular request. In MCP, request IDs are especially important because clients and servers may exchange multiple requests, receive responses in a different order, and send supported requests in either direction.
In the historical MCP 2025-06-18 specification, a request ID must be a string or integer, must not be null, and must not have been used previously by the same requestor within the same session. An ordinary correlated response carries the matching ID. A notification has no top-level ID and does not expect a JSON-RPC response.
The ID is a communication identifier, not proof of authentication, authorization, tool success or a committed business transaction.
Learning continuity: Q26–28 introduced requests, responses and notifications. Q29 isolates the identifier contract: types, allocation, non-reuse, scope, numeric representation and distinctions from other identifiers. Q34 develops concurrent request correlation and pending-task management; Q159 develops progress tracking; Q230 covers persistent business idempotency and Q237–238 cover distributed tracing.
Verification scope: Prepared under the authorized offline research and changelog exceptions using MCP 2025-06-18 as a historical reference baseline, not a claim about the latest revision. Official references were not checked live. The Python standard-library example was syntax-compiled and executed locally with Python 3.13.5: all 18 checks passed. It tests a single-threaded ID allocator and matching helper, not a complete MCP implementation. The MCP Python SDK and Mermaid CLI were unavailable locally. Actual SDK/transport interoperability and Mermaid parser/frontend rendering remain unverified.
1. What problem does a request ID solve?#
Suppose a retail support host requests inventory information for A12. After the appropriate lifecycle setup, the client sends:
JSON{ "jsonrpc": "2.0", "id": "stock-17", "method": "tools/call", "params": { "name": "stock", "arguments": {"sku": "A12"} } }
A corresponding illustrative response is:
JSON{ "jsonrpc": "2.0", "id": "stock-17", "result": { "content": [ {"type": "text", "text": "7 units available"} ] } }
The response does not have to repeat the method, tool name or input arguments. The requestor retains the original request context and uses the returned ID to identify it.
This matters even for simple requests. If two stock lookups have identical arguments, they may still be separate protocol interactions. Their IDs distinguish them. If the same user later checks stock again, that is another observation, not necessarily the same request or result.
A receiver may complete independent work in a different order, subject to its supported implementation. The ID allows the requestor to associate each result with the correct input rather than assume that the first response belongs to the first request. Q34 covers the algorithms needed to manage concurrent pending requests; here we focus on the identifier invariant.
2. Valid request ID types#
Generic JSON-RPC 2.0 defines an ID as a string, number or null, discourages null for requests and recommends avoiding fractional numbers. MCP uses stricter request ID rules in the historical baseline.
| JSON value used as id | Historical MCP request ID | Explanation |
|---|---|---|
| 0 | Valid | Integer zero is an identifier, not absence |
| 42 | Valid | Integer |
| -5 | Valid by the general type rule | An application may adopt a positive-only allocation policy |
| "42" | Valid | String, distinct from integer 42 |
| "req-42" | Valid | Opaque string |
| "" | String by type | Prefer a nonempty local ID policy for operational clarity |
| null | Invalid | Historical MCP does not permit null request IDs |
| true or false | Invalid | JSON booleans are not integer IDs |
| 1.5 | Invalid | Not an integer |
| [] or {} | Invalid | Array and object are not allowed identifier types |
The table describes the historical request ID type, not a guarantee that every value is accepted by every SDK or is unique in its actual session. An integer may still be unsafe across languages if it exceeds their exact numeric representation. An application can impose narrower allocation conventions without presenting them as universal MCP requirements.
For ordinary correlated responses, preserve the ID's type and value. The string "42" and numeric 42 must not be collapsed into one key. Python treats True as equal to 1 in certain comparisons, but a boolean must never pass an MCP integer-ID validation check.
Do not coerce a returned ID into a string merely to make matching succeed. If the request used numeric 42, a response using string "42" is a different ID representation and should not silently resolve it.
3. IDs are scoped to a requestor and session#
The historical MCP base protocol prohibits reusing an ID previously used by the same requestor within the same session. This requirement extends beyond the set of currently outstanding requests.
Suppose the client issues req-1 and receives a valid response. Removing the completed request from a pending map does not make req-1 available for reuse during that session. A subsequent request requires a new ID.
Why is this important? A delayed callback, duplicate response, timeout or implementation bug could otherwise associate an old response with a newly issued request. Non-reuse reduces that ambiguity and maintains the identity of each request.
The scope is not necessarily global across every user, server or process. Q21 introduced separate client relationships. Both sides can initiate supported requests, and each requestor has its own ID scope.
The diagram shows valid conceptual reuse of the same literal across independent sender scopes. The client-originated req-1 and server-originated req-1 in Session A represent different requests. Session B's req-1 also represents a separate interaction.
The application must preserve the direction and actual connection/session association. It must not infer origin from an ID prefix, a user-controlled payload field, or the apparent uniqueness of a string.
For example, a server-initiated ping carrying ID 1 may arrive while the client is waiting for a response to its own ID 1. The ping is a request (method present); the corresponding response to the client's request uses result or error. Separate inbound-request handling from outbound-response matching.
The logical protocol session is not necessarily identical to a physical TCP socket. Reconnecting a transport does not automatically establish a new session or justify restarting an ID counter. Reset a sender's allocation state only when the supported lifecycle establishes a genuinely new scope, with appropriate isolation from old callbacks and pending work. Exact transport and lifecycle rules are revision-dependent.
4. Choose an allocation strategy#
Request IDs should be assigned by trusted client or server protocol code. A language model does not need to generate them.
| Strategy | Advantages | Considerations |
|---|---|---|
| Incrementing integer | Simple, compact, easy to inspect | Synchronize allocation and handle numeric range limits |
| Incrementing string such as req-1 | Readable and avoids numeric precision loss | Scope and synchronize the counter; do not reset early |
| Random UUID string | Useful for distributed allocation | Negligible collision risk is not a formal guarantee; preserve non-reuse |
| Timestamp alone | Readable time association | Multiple requests can share a timestamp; clock changes can create collisions |
A sequential counter is sufficient for a simple single-owner session. A prefix such as req- is merely an application convention, not a standardized MCP field. A UUID can be useful when IDs are generated by several components, but it is not a substitute for trusted session association and appropriate uniqueness guarantees.
Do not derive IDs solely from method names, SKU values, argument hashes, user identifiers or wall-clock timestamps. Multiple requests with the same operation or inputs must still receive distinct IDs within the scope.
A useful implementation separates three actions:
- Allocate an unused ID before sending a request.
- Associate the ID with the original operation and its local context.
- Mark completion or failure without making that ID reusable in the same session.
A monotonic counter owned by the session may guarantee non-reuse without storing all historical IDs, provided it cannot wrap, reset or be bypassed by manual assignment. An implementation that accepts externally provided IDs needs an appropriate duplicate-prevention policy. A set of used IDs is simple for a small teaching fixture but may grow unbounded during a long-lived session.
Concurrency requires atomic allocation or synchronization. The exercise below deliberately runs sequentially. Q34 addresses concurrent dispatch, timeouts and pending futures.
5. Numeric precision and serialization#
JSON numbers are not represented identically by all programming languages. Python can represent arbitrarily large integers, while ordinary JavaScript Number values use IEEE 754 binary64 floating-point representation.
The commonly used safe integer interval for cross-language JSON interoperability is from -(2^53 - 1) to 2^53 - 1, inclusive. Its positive endpoint is 9,007,199,254,740,991.
For example, these distinct integer IDs are unsafe choices for a system that parses JSON numbers into JavaScript Number values:
JSON{"jsonrpc":"2.0","id":9007199254740992,"method":"ping"}
JSON{"jsonrpc":"2.0","id":9007199254740993,"method":"ping"}
Both may be represented by the same numeric value after binary64 conversion. The receiver cannot reliably preserve their distinction using that numeric representation.
A string ID can preserve the intended sequence of digits:
JSON{"jsonrpc":"2.0","id":"9007199254740993","method":"ping"}
This is not a claim that MCP universally prohibits every integer beyond the safe range. It is an interoperability recommendation motivated by the JSON number representation discussed in RFC 8259. A receiver may support a lossless numeric parser, but a mixed-language deployment should not assume that every peer does.
Also distinguish the JSON number's mathematical value from its lexical representation. A parser may represent 1.0 or 1e0 differently from a Python integer even when mathematically integral. Follow the selected schema and SDK's handling of numeric IDs. Emitting ordinary integer JSON values or opaque strings avoids many such ambiguities.
Use a standards-compatible serializer rather than constructing JSON with string interpolation. Preserve the original ID value; do not accidentally change a string into a number or serialize a language-specific identifier object without an explicit mapping.
6. How the response uses the ID#
The response repeats the request ID in both ordinary result and error branches.
JSON{"jsonrpc":"2.0","id":"r-9","result":{}}
JSON{"jsonrpc":"2.0","id":"r-9","error":{"code":-32603,"message":"Internal error"}}
These are alternative outcomes for an identifiable request, not two valid terminal responses to the same ordinary request. The first can illustrate a successful ping; the second illustrates a correlated error.
A matching ID is necessary but not sufficient to accept the response. The client still checks the actual connection association, envelope, selected method's schema and relevant lifecycle. A stock result for the wrong SKU is not valid evidence merely because the request ID matches.
Generic JSON-RPC has special error-response cases with null IDs when an original request ID cannot be determined. Such messages are not normal correlated responses. Historical MCP has its own schema restrictions and applicable handling requirements. Never resolve an arbitrary pending request using an unidentifiable error.
An unknown or duplicate response ID should be handled as an unexpected message according to the applicable protocol and implementation policy. Do not assign it to another request because the intended operation appears similar.
7. Notifications do not consume request IDs#
As Q28 established, a notification omits the top-level id member entirely:
JSON{"jsonrpc":"2.0","method":"notifications/tools/list_changed"}
No response is expected to that notification, so it does not need a request ID or an entry in the request-response tracking state.
Some notification parameters contain identifiers. For example, notifications/cancelled can refer to an earlier request through params.requestId:
JSON{ "jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": "r-9", "reason": "User cancelled"} }
The nested requestId references an existing interaction. It is not the notification's own top-level ID and does not establish a new request-response exchange. The applicable cancellation rules still determine whether the signal may be sent and how the recipient handles it.
A null top-level id is not a notification. An integer zero is not a notification. Check for the presence of the member and classify the message using its actual schema.
8. Different identifiers serve different purposes#
An MCP-enabled application may encounter several identifiers while performing one task. They should not be treated as interchangeable.
| Identifier | Scope and purpose | Example |
|---|---|---|
| JSON-RPC request ID | Correlate one protocol request with its response | req-41 |
| Progress token | Associate supported progress notifications with an operation | scan-progress-7 |
| Protocol session identifier, where supported | Identify an applicable transport/session relationship | Opaque session value |
| Trace or correlation ID | Associate related telemetry across services | Trace context ID |
| Model-provider tool-call ID | Match provider-specific tool calls and results | Provider-issued call identifier |
| Business operation ID | Identify a durable domain operation or status record | reservation-84 |
| Business idempotency key | Support duplicate-effect prevention under an explicit service contract | reservation-attempt-84 |
A progress token may be supplied in params._meta.progressToken under the historical request schema. It is not automatically the request ID. An implementation may choose related values where the contracts permit it, but each field has its own meaning and lifecycle.
A trace identifier may remain the same across several protocol requests and backend calls. It helps diagnose the workflow; it does not replace the request ID.
A business idempotency key may intentionally be reused for a safe retry of the same business operation, according to the authoritative service's contract. The protocol request ID must be new for a new request within the same historical MCP requestor/session scope. The service must actually enforce the idempotency guarantee; merely passing a string labeled idempotency_key does not prevent duplicate effects.
For example, a reservation request with ID req-41 might time out after a possible commit. A subsequent authorized retry could use req-42 while preserving the same business idempotency key if the backend explicitly supports that behavior. If it does not, blindly retrying is unsafe. The host needs authoritative status or reconciliation. Q230–231 cover those mechanisms.
None of these identifiers is inherently an authentication credential or approval token. Avoid putting secrets or unnecessary personal information into IDs. A readable identifier can appear in diagnostic logs and traces.
9. Tested practical example: allocate and validate IDs#
This dependency-free Python exercise implements a small sender-scoped allocator. Each SenderIDs instance represents one requestor within one logical session. It supports manually reserved integer or string IDs and generates sequential string IDs while avoiding already issued values.
The local policy accepts integers in the interoperable safe range and strings of length 1–128. These are deliberately stricter than the historical general MCP type rule. The program is not an MCP SDK or a concurrent request manager.
Save as mcp_q29.py:
PYTHONimport json SAFE_INTEGER = 2**53 - 1 def id_key(value): # Local interoperability policy, stricter than the protocol. if type(value) is int and -SAFE_INTEGER <= value <= SAFE_INTEGER: return ('integer', value) if type(value) is str and 1 <= len(value) <= 128: return ('string', value) raise ValueError('Invalid or unsupported request ID') class SenderIDs: def __init__(self): self.used = set() self.counter = 0 def reserve(self, value): key = id_key(value) if key in self.used: raise ValueError('ID already issued in this sender scope') self.used.add(key) return value def allocate(self): while True: self.counter += 1 value = f'req-{self.counter}' if id_key(value) not in self.used: return self.reserve(value) def matches(expected, response): return 'id' in response and id_key(expected) == id_key(response['id']) def reject(fn): try: fn() except ValueError: return raise AssertionError('Expected rejection') if __name__ == '__main__': client_a = SenderIDs() server_a = SenderIDs() client_b = SenderIDs() assert client_a.allocate() == 'req-1' assert client_a.allocate() == 'req-2' reject(lambda: client_a.reserve('req-1')) assert server_a.allocate() == 'req-1' assert client_b.allocate() == 'req-1' assert client_a.reserve(0) == 0 assert client_a.reserve('0') == '0' assert matches(0, json.loads('{"id":0}')) assert not matches(0, {'id': '0'}) assert not matches(0, {}) assert client_a.reserve('req-3') == 'req-3' assert client_a.allocate() == 'req-4' for invalid in (None, True, 1.5, 2**53, [], ''): reject(lambda: id_key(invalid)) print('18 request ID checks passed')
Run:
BASHpython -m py_compile mcp_q29.py python mcp_q29.py
Actual local output on Python 3.13.5:
18 request ID checks passedWhat the tests establish#
The twelve checks before the loop cover consecutive allocations, rejection of previously issued IDs, reuse of the same literal in independent sender and session fixtures, reservation of both integer zero and string zero, JSON-decoded matching, type-sensitive mismatch, absent ID, manual reservation and skipping a reserved sequential ID. Six additional rejection checks cover null, boolean, fraction, unsafe integer, array and empty string under the local policy.
The tuple returned by id_key makes the representation explicit. The exact-type check excludes Python booleans from the integer branch. The used set is not cleared when a request would complete, so reserve rejects an identifier already issued in this allocator's scope. The fixture demonstrates that a server and client can maintain separate allocators even when both produce req-1.
The matches helper is intentionally narrow. It checks only the supplied expected ID and the presence and validated value of the response ID. Invalid ID types raise ValueError; absence or a valid but different ID yields False. It does not establish that the input is a complete valid JSON-RPC response.
Production limitations#
This sequential fixture assumes trusted association of SenderIDs instances with real sessions and requestors. It does not validate transport origin, complete envelopes, lifecycle, capability negotiation, schema conformance, authentication or authorization. It does not implement a pending map, timeouts, concurrent allocation, persistence, session replacement or late response processing. The used set grows with issued IDs and is appropriate only for bounded demonstrations. A production allocator needs appropriate resource and synchronization controls.
No actual client or server exchanged messages. The test confirms the listed local behaviors, not full MCP compliance or cross-language numeric parsing. The numeric policy is motivated by JSON interoperability guidance; the example does not run a JavaScript parser. Use a revision-compatible SDK for actual ID management and test the SDK with the intended transport.
10. Common mistakes and troubleshooting#
| Mistake | Consequence | Correct approach |
|---|---|---|
| Reuse an ID after the earlier response | Violates historical session non-reuse rule; late responses become ambiguous | Allocate a new ID for each request |
| One global map keyed only by ID | Responses from separate relationships can collide | Preserve session and direction scope |
| Convert all IDs to strings | Loses distinction between 7 and "7" | Preserve type and value |
| Use truthiness to detect an ID | Numeric zero may be treated as a notification | Check member presence |
| Use timestamps without uniqueness control | Concurrent requests can share IDs | Use a trusted allocator |
| Use excessively large numeric IDs | Precision loss across some runtimes | Prefer safe integers or strings |
| Treat request ID as idempotency key | Duplicate business effects may occur | Use explicit durable business protection |
| Trust a matching ID as proof of success | Invalid or unauthorized results may be accepted | Validate the complete response and business evidence |
When debugging a correlation failure, inspect the actual outbound ID and type, inbound ID and type, session identity, originating direction and request lifecycle. Use sanitized logs and avoid exposing confidential inputs. A matching ID is meaningful only within its correct scope.
Interview-ready answer#
JSON-RPC request IDs identify individual protocol requests so the response can be matched to the correct operation. In the historical MCP 2025-06-18 baseline, IDs are strings or integers, cannot be null and cannot be reused by the same requestor within the same session. Separate sessions and opposite request directions can have independent ID scopes. Preserve both type and value, prefer interoperable numeric ranges or strings, and allocate IDs in trusted protocol code. Notifications have no top-level request ID. Request IDs are distinct from progress tokens, session identifiers, tracing identifiers and business idempotency keys. They provide correlation, not authentication, authorization or exactly-once execution.
Next lesson: Q30 examines how MCP method names and parameter objects express the operation and its input contract.
References
- 1.JSON-RPC 2.0 specificationjsonrpc.org
- 2.RFC 8259, section 6rfc-editor.org
- 3.MCP historical specification (2025-06-18)modelcontextprotocol.io
- 4.MCP base protocolmodelcontextprotocol.io
- 5.MCP lifecyclemodelcontextprotocol.io
- 6.MCP progressmodelcontextprotocol.io
- 7.MCP cancellationmodelcontextprotocol.io
- 8.W3C Trace Contextw3.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