Module 4: Developer's Guide to Model Context Protocol (MCP)

As LLMs became more powerful, developers wanted to connect them to external tools and data. Early attempts relied on custom, one-off solutions, which were difficult to maintain, inconsistent, and often insecure.

This module introduces developers to the Model Context Protocol (MCP), a standardized protocol developed by Anthropic that enables Large Language Models (LLMs) to interact with external tools, APIs, and data sources in a structured and secure way.

Hands-On Lab:
Launch the companion lab notebook to practice building and testing MCP client-server integrations. In the lab, you'll transform direct tool calls into protocol-based interactions, experience the three-layer MCP architecture, and see how modular, secure AI integrations work in practice.

What You'll Learn

  • Architecture: The roles and responsibilities of the host, client, and server in an MCP system, ensuring modularity, security, and clear separation of concerns.
  • Core Message Types: Standardized JSON-RPC message types—requests, responses, notifications, and errors—that enable structured, reliable, and extensible communication between MCP components.
  • Features: Outlines the core capabilities MCP enables—such as resources, tools, prompts, and sampling—allowing clients and servers to declare, negotiate, and use powerful, composable functions.
  • Connection Lifecycle: How MCP sessions are initialized, maintained, and terminated, including capability negotiation and supported transport protocols for robust, stateful connections.
  • Transport Protocols: Supported communication protocols (stdio, HTTP), session management, and authorization.
  • Security Principles: Best practices and requirements for user consent, access control, and safe tool use, ensuring secure and trustworthy MCP integrations.

You will learn how these elements together make MCP a robust, extensible, and secure foundation for advanced AI integrations.

Architecture

MCP System Overview

Quick Summary: MCP uses a modular, client-server architecture with strict security boundaries and clear separation of concerns.

High-Level Architecture: Host, Client, and Server

MCP Component Architecture Diagram
Figure: The Host manages multiple clients, each connecting to a specific server. Each client-server pair is isolated, ensuring security and modularity.
Role Main Responsibility Example
Host Manages user input, LLM interactions, security, user consent, and connections
IDE Application: Receives a user's code question, uses the LLM to interpret it, decides to call the code search tool, and displays the answer in the UI.
Client Protocol handler, connects to one server, enforces boundaries Code Search Connector: Receives a search request from the host, sends it to the code search server, and returns the results.
Server Operates independently—cannot access the full conversation or other servers. Processes requests only from its assigned client and provides access to resources, tools and prompts. Code Search Server: Indexes project files and responds to search queries from the client.

MCP Design Principles

🛠️ Servers should be extremely easy to build: Host applications handle orchestration, so servers focus on simple, well-defined capabilities.
🧩 Servers should be highly composable: Each server works in isolation but can be seamlessly combined with others via the shared protocol.
🔒 Servers should not be able to read the whole conversation or "see into" other servers: Servers only receive necessary context; each connection is isolated and controlled by the host.
⬆️ Features can be added to servers and clients progressively: The protocol allows new capabilities to be negotiated and added as needed, supporting independent evolution.

How It Works (At a Glance): Practical Example

Scenario: A user interacts with an AI-powered productivity assistant (the host) that integrates both a calendar tool and a weather tool.

  1. User: Asks, "Do I have any meetings this afternoon, and what's the weather forecast for that time?"
  2. Host: Uses the LLM to interpret the request and determines it needs to:
    • Check the user's calendar for meetings this afternoon (calendar tool)
    • Get the weather forecast for the meeting time (weather tool)
  3. Host: Uses Client 1 to connect to Server 1 (Calendar Tool), which returns: "You have a meeting at 3:00 PM."
  4. Host: Uses Client 2 to connect to Server 2 (Weather Tool), which returns: "The forecast at 3:00 PM is sunny, 75°F."
  5. Security Boundary: Each client only communicates with its assigned server. The calendar server never sees weather data, and vice versa.
  6. Host: Aggregates the results and presents: "You have a meeting at 3:00 PM. The weather at that time is expected to be sunny, 75°F."

Key Point: This example shows how MCP enables secure, modular, and orchestrated multi-tool workflows.

Note: MCP provides official SDKs for multiple languages, including Python and TypeScript, to simplify development and integration. See official documentation for more details.

Core Message Types

Overview

MCP uses JSON-RPC 2.0 as its foundation for structured, reliable communication between hosts, clients, and servers. There are four core message types—Request, Response, Error, and Notification—which enable both sides to exchange actions, results, errors, and updates in a consistent way. Understanding these types is essential for building and integrating MCP-compliant tools and applications.

Main Message Types

📤 Request

Asks another component to perform an action or provide information.

FieldTypeDescriptionRequired?
idstring/numberUnique identifier for the requestYes
methodstringOperation to invokeYes
paramsobject/arrayParameters for the methodOptional
{
  "jsonrpc": "2.0",
  "id": 1,
  "method": "resources/read",
  "params": { "id": "abc123" }
}
Note: A reply to a request is either a Response (with a result) or an Error (with an error object), never both.

📥 Response

Returns the result of a request.

FieldTypeDescriptionRequired?
idstring/numberMatches the original requestYes
resultobject/anyResult of the requestYes, if successful
errorobjectError object (must not be present if result is present)No
{
  "jsonrpc": "2.0",
  "id": 1,
  "result": { "id": "abc123", "name": "Resource Name", "data": "..." }
}

Error

Returns an error for a request.

FieldTypeDescriptionRequired?
idstring/numberMatches the original requestYes
errorobjectObject with code (number) and message (string)Yes
resultobject/anyMust not be present if error is presentNo

Common error codes:

CodeNameMeaning
-32700ParseErrorInvalid JSON was received by the server
-32600InvalidRequestThe JSON sent is not a valid Request object
-32601MethodNotFoundThe method does not exist or is not available
-32602InvalidParamsInvalid method parameter(s)
-32603InternalErrorInternal JSON-RPC error
> -32000CustomApplication-defined errors
{
  "jsonrpc": "2.0",
  "id": 1,
  "error": { "code": -32601, "message": "Method not found" }
}

🔔 Notification

Sends a one-way event or update; no response expected.

FieldTypeDescriptionRequired?
jsonrpcstringMust be "2.0"Yes
methodstringEvent or action nameYes
paramsobject/arrayParameters for the eventOptional
idn/aMust not be includedn/a (must be omitted)
{
  "jsonrpc": "2.0",
  "method": "notifications/resources/updated",
  "params": { "resourceId": "abc123" }
}

Additional Notes

References

Features

MCP defines a set of features—such as resources, tools, prompts, sampling, and roots—that enable applications to interact with external data, perform actions, and extend AI capabilities in a standardized, secure manner.

Server Features

📦 Resources: Structured data or context a server provides.
How it works: Exposes data (files, DB tables, API results) as resources for the client/LLM.
Example: List of files in a project; customer records from a database.

🛠️ Tools: Functions or actions the AI assistant can invoke.
How it works: Client/LLM calls tools via MCP to perform operations.
Example: Search database, format code.

📝 Prompts: Templated messages or workflows to guide LLM/user.
How it works: Standardizes tasks and interactions.
Example: Summarize a document; onboarding workflow.

Tip: Use a resource for static or subscribable data; use a tool for dynamic, parameterized queries or actions.

Client Features

🎲 Sampling: Lets the server request the client to generate a completion or response from the LLM.
How it works: Server asks the client to use its LLM for tasks like summarization or drafting.
Example: Server requests a summary of a document.

📁 Roots: Defines boundaries of accessible directories/files for the server.
How it works: Client exposes only specific directories to the server.
Example: Only the "/projects/my-app" folder is accessible to a code analysis server.

MCP Connection Lifecycle

The connection lifecycle in the Model Context Protocol (MCP) defines how a session is established, maintained, and terminated between a client and a server, with the host orchestrating the process. This lifecycle ensures robust, secure, and feature-negotiated communication for all MCP-compliant integrations.

Lifecycle Phases

1. Initialization 🤝

2. Active Session 🔄

Once initialized, the session enters an active state where both sides know which features are available.

3. Termination ⏹️

Lifecycle Diagram

MCP Connection Lifecycle

The diagram above illustrates the key phases and message flows in a typical MCP session, including initialization, active session management, requests, notifications, and termination.

Key Points

Transport Protocols

Transport Protocols in MCP

HeaderUsed InPurpose
Content-TypePOSTSpecifies message format (JSON)
AcceptPOST/GETIndicates accepted response types (JSON, streaming)
Mcp-Session-IdBothIdentifies the session
This approach enables both single-response and real-time, streaming communication, making MCP suitable for a wide range of use cases.
See the MCP Transports documentation for more details.

Authorization in MCP (2025-03-26 Spec)


Session Management in MCP

For more, see Session Management in the MCP spec.

Security and Trust & Safety

Reference: MCP Specification: Security and Trust & Safety
This section is a direct, word-for-word reference from the official MCP specification for accuracy and authority.

The Model Context Protocol (MCP) enables powerful integrations between LLMs and external tools or data sources. With this power comes significant responsibility: implementers must ensure robust security, user trust, and safety at every stage of development and deployment.

Key Principles

  1. User Consent and Control
    Users must explicitly consent to all data access and operations. Users should always understand and control what data is shared and what actions are taken on their behalf. Applications should provide clear UIs for reviewing and authorizing activities.
  2. Data Privacy
    Hosts must obtain explicit user consent before exposing user data to servers. Resource data must not be transmitted elsewhere without user consent, and all user data should be protected with appropriate access controls.
  3. Tool Safety
    Tools represent arbitrary code execution and must be treated with caution. Descriptions of tool behavior should be considered untrusted unless obtained from a trusted server. Hosts must obtain explicit user consent before invoking any tool, and users should understand what each tool does before authorizing its use.
  4. LLM Sampling Controls
    Users must explicitly approve any LLM sampling requests. Users should control whether sampling occurs, the actual prompt sent, and what results the server can see. The protocol intentionally limits server visibility into prompts.

Implementation Guidelines

While MCP itself cannot enforce these principles at the protocol level, it is the responsibility of every implementer to uphold them in practice.

References

MCP Module Quiz

1. Which of the following are the three main roles in the MCP architecture?

  • A) Host, Client, Server
  • B) User, Model, Database
  • C) Agent, Tool, Resource
  • D) Application, API, Service
Answer: A) Host, Client, Server

2. True or False: In MCP, only the client can send requests to the server.

  • True
  • False
Answer: False. Both the client and server can send requests and notifications.

3. Which protocol is used by MCP for encoding messages?

  • A) XML-RPC
  • B) JSON-RPC 2.0
  • C) SOAP
  • D) REST
Answer: B) JSON-RPC 2.0

4. What is the difference between a resource and a tool in MCP?

  • A) Resources are actions, tools are data
  • B) Resources are data or information, tools are actions or functions
  • C) Both are the same
  • D) Tools are only for security
Answer: B) Resources are data or information, tools are actions or functions

5. True or False: MCP supports both stdio and HTTP as transport protocols.

  • True
  • False
Answer: True

6. Which of the following is the recommended method for authorization in MCP when using HTTP-based transports?

  • A) Basic Auth
  • B) OAuth 2.1
  • C) API Key in URL
  • D) No authorization is needed
Answer: B) OAuth 2.1

7. True or False: Notifications in MCP are one-way messages that do not expect a response.

  • True
  • False
Answer: True