Back to Course|MCP Mastery: Building AI-Powered Integrations with Model Context Protocol
Lab

Parse an MCP JSON-RPC Message

20 min
Beginner
3 Free Attempts

Instructions

Objective

Write a Python function that parses MCP JSON-RPC messages and extracts key information.

Background

MCP uses JSON-RPC 2.0 for communication. Every message has a specific structure that includes version, method, parameters, and an optional ID for request-response correlation.

Requirements

Create a function parse_mcp_message(message: dict) -> dict that:

  1. Validates the message format: Check for required fields (jsonrpc, method)

  2. Extracts message type: Determine if it's a request, response, or notification

    • Request: Has id and method
    • Response: Has id and either result or error
    • Notification: Has method but no id
  3. Parses method details: Extract namespace and action from method (e.g., "tools/call" → namespace: "tools", action: "call")

  4. Returns structured output:

    {
        "valid": bool,
        "type": "request" | "response" | "notification" | "invalid",
        "method": str | None,
        "namespace": str | None,
        "action": str | None,
        "id": int | str | None,
        "has_params": bool,
        "has_error": bool
    }
    

Example Input

message = {
    "jsonrpc": "2.0",
    "id": 1,
    "method": "tools/call",
    "params": {
        "name": "search",
        "arguments": {"query": "test"}
    }
}

Example Output

{
    "valid": True,
    "type": "request",
    "method": "tools/call",
    "namespace": "tools",
    "action": "call",
    "id": 1,
    "has_params": True,
    "has_error": False
}

Hints

  • Use message.get("key") to safely access optional fields
  • The method field uses "/" to separate namespace and action
  • A response message has no method field

Grading Rubric

Correctly validates JSON-RPC 2.0 format25 points
Accurately determines message type (request/response/notification)25 points
Correctly parses method namespace and action25 points
Returns complete structured output with all fields25 points

Your Solution

Use any programming language
3 free attempts remaining