Skip to main content
LearnMLAcademy
Advanced10 min read

Model Context Protocol (MCP) & Agent Interoperability

Implement Model Context Protocol (MCP) clients and servers for AI tools, with workflow diagrams, tool-use traces, and safety-focused exercises.

What you will master in this lesson
Intuitive core mechanisms & practical real-world intuition
Step-by-step mathematical breakdown & visual diagrams
Runnable Python implementation & practical trade-offs

Connect an agent application to tools through a shared protocol

Model Context Protocol is an open protocol for connecting AI applications to tools and contextual resources through a consistent client-server interface. It standardizes discovery and invocation; it does not replace the underlying API or service and does not make a capability automatically trusted or safe.

What You Will Learn

  • Trace an MCP request from host and client to server and underlying service.
  • Distinguish protocol compatibility from trust and authorization.
  • Compare MCP with direct APIs and ordinary function-tool integration.
  • Treat exact SDK details as version-dependent implementation choices.

The protocol is not the underlying service

An MCP server exposes supported protocol capabilities—such as tools, resources, or prompts—to a compatible client. The server may then call a separate database, filesystem, search index, or business API that performs the real operation. MCP standardizes the connection and discovery layer; it does not replace that service.

Compatibility does not grant trust. Hosts and servers still need authentication, authorization, user consent, least-privilege scopes, input validation, credential protection, audit logs, and version management. SDK names may evolve, so the stable lesson is the host–client–server–service boundary.

Instructional figure

MCP architecture and its trust boundary

How does an AI host reach an underlying service through MCP?

AI host
model + application
MCP client
MCP server
Tools • resources • prompts

Authorization / consent / validation boundary

Underlying API or data
performs the real operation
MCP standardizes compatible discovery and invocation. Authentication, consent, authorization, and the safety of the underlying API remain system responsibilities.

MCP, direct APIs, and ordinary function tools

MCP, direct APIs, and ordinary function tools
ApproachWhat is standardized?DiscoveryPortabilitySecurity responsibility
Direct APIService-specific endpoints and schemasDeveloper reads service contractIntegration is service-specificApplication and service
Ordinary function toolApplication-defined tool schemaTools supplied in each applicationPortable only by local conventionApplication and underlying service
MCPCompatible protocol messages and capabilitiesClient discovers server capabilitiesCompatible hosts can reuse serversHost, client/server deployment and underlying service

Discover a capability, request it and handle the response

  1. An MCP server exposes tools, resources, or prompts supported by that implementation.

  2. An MCP client connects the server to an AI host and discovers the advertised capabilities.

  3. The host presents relevant capabilities to the model, which may propose an invocation.

  4. The application validates permission, credentials, arguments, and trust boundaries before the server reaches the underlying API or data source.

  5. Structured results return through the client, while operators manage server versions, compatibility, credentials, and governance separately.

Worked Example: Discovery enables invocation; it does not grant access

An AI host has MCP client functionality connected to a billing MCP server. The server exposes a read_invoice capability backed by a separate billing API. The example uses conceptual messages because exact SDK and wire fields can evolve.

  1. Discovery: the client learns that read_invoice accepts an invoice identifier. This establishes protocol compatibility, not permission to read every invoice.
  2. Normal path: the host requests INV-42; the server authenticates the caller and confirms invoices:read scope for account A-7 before asking the underlying billing API. The API returns $320, which the server packages as a structured protocol result.
  3. Rejection path: a different credential sends the same well-formed request but lacks invoices:read for A-7. The server returns a structured insufficient_scope error and never sends a request to the billing API.

What the result means: The protocol request/result belongs to the MCP boundary; the billing request/result belongs to the underlying service. Least privilege is enforced at the server/service boundary even when discovery and message structure are valid.

One discovered capability, two authorization outcomes

One discovered capability, two authorization outcomes
StageNormal invocationInsufficient-scope invocation
DiscoveryServer advertises read_invoiceServer advertises read_invoice
Protocol requestClient requests invoice INV-42 using a version-compatible structured messageClient requests INV-42 using the same capability
Server boundaryCredential has invoices:read for account A-7Credential lacks invoices:read for A-7
Underlying serviceServer calls billing API and receives amount $320Not called
Protocol resultStructured result: invoice INV-42, amount $320Structured insufficient_scope error
Host decisionPlace compact result in model contextExplain missing permission; do not invent data or broaden scope

Instructional figure

MCP discovery and invocation are distinct protocol steps

Which messages are protocol interactions, and which call actually reaches the underlying service?

1 · Host/client discovers
Server advertises approved capability
2 · Protocol invocation
Structured request crosses to server
3 · Server checks scope
Authorize before service call
4 · Underlying service
Separate API/data request and result
5 · Protocol result
Compact data or structured error
6 · Host/model
Result becomes bounded context
Insufficient scope → structured rejection → underlying service is not called
The diagram is version-conscious: exact wire fields are not assumed. Discovery advertises a capability; invocation crosses server-side auth before the separate service request. Insufficient scope returns a structured rejection without calling the service.

A Realistic Example: Connecting a documentation server

One MCP server exposes approved documentation search. Different compatible AI hosts can use the same server without implementing a unique integration for each host.

Read the Mechanism in Code

Use the label and note to understand what this block represents before reading each line.

Illustrative framework/API fragment — external dependency/setup required
# Conceptual MCP tool definition
@server.tool()
def search_docs(query: str, limit: int = 5) -> list[Document]:
    """Search only the approved documentation index."""
    authorize_current_user()
    return docs.search(query, limit=min(limit, 10))
Learner note: Illustrative MCP server tool fragment. Exact imports and APIs depend on the MCP SDK/version; the conceptual client/server/trust model is the lesson’s stable part.

Hands-On Runnable Python Lab: Inspect Discovery, Invocation and a Scope Rejection

An in-memory teaching trace uses MCP-style JSON-RPC envelopes, not a complete MCP server or SDK. Discovery and invocation follow a simulated initialization. Version 2025-11-25 is the explicitly selected example version.

service_read_allowed = authenticated_scope_allows_read AND invoice_belongs_to_account
Discovery and valid messages are not authorization. Account A-7 and scopes come from trusted runtime context, never tool arguments.
  1. Print initialize followed by notifications/initialized, distinguishing request from notification.
  2. Return read_invoice and its input schema.
  3. Invoke without read scope and confirm the service is not called.
  4. Invoke with invoices:read and matching account, returning $320. Count one service call.

Discovery, authorization and the underlying service are different steps

Client discovers a server tool. A call without read scope is denied before reaching billing. The authorized call reaches billing and returns invoice 320 dollars.ClientServerBillingtools/listread_invoice schemacall · no scopeinsufficient_scope× no service readcall · read scoperead INV-42account A-7 · $320tool resultInitialization precedes this sequence
Horizontal arrows are messages or service calls; dashed vertical lines are participant lifelines. Denial stops at the server boundary. Initialization happens before the depicted tool operations.

Horizontal arrows are messages or service calls; dashed vertical lines are participant lifelines. Denial stops at the server boundary. Initialization happens before the depicted tool operations.

Complete Python ExercisepythonRunnable
import json
tool = {
    "name": "read_invoice",
    "description": "Read one invoice in the authenticated account",
    "inputSchema": {"type": "object", "properties": {"invoice_id": {"type": "string"}},
                    "required": ["invoice_id"], "additionalProperties": False},
}
invoices = {"INV-42": {"account": "A-7", "amount_usd": 320}}
service_calls = 0

def invoke(request, scopes, account):
    global service_calls
    args = request["params"]["arguments"]
    if request["params"]["name"] != "read_invoice" or set(args) != {"invoice_id"}:
        message, failed = "Invalid tool request", True
    elif "invoices:read" not in scopes:
        message, failed = "insufficient_scope", True
    elif args["invoice_id"] not in invoices or invoices[args["invoice_id"]]["account"] != account:
        message, failed = "Invoice unavailable", True
    else:
        service_calls += 1
        message, failed = json.dumps(invoices[args["invoice_id"]]), False
    return {"jsonrpc": "2.0", "id": request["id"],
            "result": {"content": [{"type": "text", "text": message}], "isError": failed}}

print("client -> server: initialize (version 2025-11-25)")
print("server -> client: version and tools capability accepted (fixture)")
print("client -> server: notifications/initialized")
print("tools/list result:", json.dumps({"tools": [tool]}, sort_keys=True))
request = {"jsonrpc": "2.0", "id": 2, "method": "tools/call",
           "params": {"name": "read_invoice", "arguments": {"invoice_id": "INV-42"}}}
for scopes in [set(), {"invoices:read"}]:
    response = invoke(request, scopes, "A-7")
    print(json.dumps(response, sort_keys=True))
print("underlying service calls:", service_calls)
Run with Python 3 using only its standard library. No API key, paid service or model download is required. Model proposals and external observations are explicitly simulated; the application logic really executes.
Output from This Exact ProgramOutput
client -> server: initialize (version 2025-11-25)
server -> client: version and tools capability accepted (fixture)
client -> server: notifications/initialized
tools/list result: {"tools": [{"description": "Read one invoice in the authenticated account", "inputSchema": {"additionalProperties": false, "properties": {"invoice_id": {"type": "string"}}, "required": ["invoice_id"], "type": "object"}, "name": "read_invoice"}]}
{"id": 2, "jsonrpc": "2.0", "result": {"content": [{"text": "insufficient_scope", "type": "text"}], "isError": true}}
{"id": 2, "jsonrpc": "2.0", "result": {"content": [{"text": "{\"account\": \"A-7\", \"amount_usd\": 320}", "type": "text"}], "isError": false}}
underlying service calls: 1
Captured with Python 3.12. Fixture timings, prices and evaluation results are teaching inputs, not provider benchmarks.

What This Run Shows

  1. The arguments are identical; trusted authorization context changes the outcome.
  2. Denial uses isError=True in a tool result. A malformed protocol envelope is a different error class.
  3. The counter proves discovery and rejection did not themselves read invoice data.

MCP improves interoperability at a connection boundary. It does not make a tool safe, a source authoritative or the underlying API unnecessary.

From the Exercise to an Application

From the Exercise to an Application
SituationPractical choiceImportant qualification
Reusable integration across compatible hostsExpose a scoped MCP capabilityPin compatible versions and test negotiation.
Single simple serviceA direct API may sufficeA protocol is not a prerequisite for tool safety.
Missing scopeReturn denial and request legitimate authorizationDo not broaden permission automatically.
Experiment: Keep invoices:read but change the account to A-99.

The tool returns Invoice unavailable without calling the service. Scope and record ownership are separate gates.

Summary / Key Takeaways

  • MCP standardizes how compatible AI hosts and clients discover and invoke capabilities exposed by MCP servers.
  • An MCP server can expose protocol capabilities such as tools, resources, and prompts, while the underlying API or data source remains a separate system.
  • MCP improves interoperability by reducing one-off integration work between hosts and compatible servers.
  • Protocol compatibility is not the same as trust: authentication, authorization, consent, validation, and credentials still matter.
  • Clients should request only the scopes and capabilities needed for the task, following least-privilege principles.
  • Versioning and compatibility must be managed because protocol and SDK details evolve.
  • MCP complements tool calling; it does not replace the application’s responsibility for safe execution and governance.

Verified Further Reading

These primary research papers and current official specifications support the concepts and implementation guidance in this lesson. The explanations, analogies, exercises, and code above remain original teaching material.

Apply this concept in a real hands-on project

You have studied the idea. Now use it in working Python code, see the calculation and output, and explain what changed. Each project includes step-by-step instructions, full source and tests.

Practice challenge: predict an outcome first, run the code, and explain the difference.

Track Your Progress0% curriculum done

Finished "Model Context Protocol (MCP) & Agent Interoperability"?

Mark this lesson as completed to update your progress bar and track your milestones across the full curriculum.

Overall Progress0 / 167 lessons

Was this tutorial helpful?

Your feedback helps us continuously refine and improve our open-access tutorials.

Knowledge Check

Progress: 0/5

Test your active recall. Choose one answer for each question, then check it to reveal the step-by-step reasoning.

Question 1 of 5conceptual
What problem does MCP primarily address?
Question 2 of 5conceptual
An MCP server follows the protocol correctly. Does that make every exposed tool safe to run?
Question 3 of 5interpretation
Which statement best distinguishes MCP from a direct underlying API?
Question 4 of 5debugging/diagnostic
A client requests broad scopes for every connected MCP server even though the task needs one read-only capability. Which principle is violated?
Question 5 of 5practical selection
Why should the lesson avoid hard-coding unstable SDK details as the core concept?

Knowledge Check Review & Explanations

Review the questions, verified correct answers, and conceptual explanations for this lesson.

1What problem does MCP primarily address?▼

Correct Answer: Standardizing how compatible AI applications discover and invoke external capabilities/resources

MCP provides a standardized client-server interface for exposing and using capabilities across compatible AI hosts.

2An MCP server follows the protocol correctly. Does that make every exposed tool safe to run?▼

Correct Answer: No; authentication, authorization, validation, consent, and least privilege are still required

Interoperability does not eliminate security responsibility. Safe execution remains an application/system concern.

3Which statement best distinguishes MCP from a direct underlying API?▼

Correct Answer: MCP can standardize discovery/invocation, while the actual service/API still performs the real operation

MCP is an integration protocol layer; the underlying API, service, or data source still exists and must be governed.

4A client requests broad scopes for every connected MCP server even though the task needs one read-only capability. Which principle is violated?▼

Correct Answer: Least privilege

Clients should request only the permissions required for the task and expand access only when needed.

5Why should the lesson avoid hard-coding unstable SDK details as the core concept?▼

Correct Answer: Protocol/SDK APIs evolve, while the client-server/trust model is the durable concept learners should retain

Version-conscious teaching keeps the conceptual model stable while treating exact imports/APIs as changeable implementation details.

Keep moving through the path

Continue Learning

Free Download: ML Interview Cheatsheet

100 essential Machine Learning interview questions and answers covering foundations, algorithms, evaluation, deep learning, Python, system design and interview strategy. Enter your email to download it instantly.

Next