---
title: "MCP servers, end to end: Model Context Protocol explained"
author: Ata (ND Orbit)
published: 2026-11-13
canonical: https://ndorbit.co.nz/articles/mcp/
language: en-NZ
spec_revision: 2026-07-28 (current), with the 2025-11-25 legacy flow for interoperability
license: Read, summarise and cite with a link to the canonical URL.
---

# MCP servers, end to end

> An MCP server gives an AI application a standard way to use tools, data and prompts: files, databases, business APIs and search. The Model Context Protocol (MCP) is the adapter boundary between them. This guide explains the architecture, both tool-call sequences, transports, authorization, security pitfalls and a tested Python server.

Canonical article with diagrams: https://ndorbit.co.nz/articles/mcp/

## Key facts

- The **host** (the AI application) owns the conversation, model access, permissions and orchestration. It creates **one MCP client per server relationship**.
- An **MCP server** exposes **tools**, **resources** and **prompts**, and translates approved requests into calls to its own files, databases or APIs. It does not need an LLM.
- MCP is not the model, not the agent loop and not a security boundary. The model *proposes* a tool call; the host *decides*; the client sends JSON-RPC; the host returns the result to the model.
- Transports: **stdio** for local child-process servers, **Streamable HTTP** for remote services.
- The current revision **2026-07-28 is stateless**: no `initialize` handshake, no `Mcp-Session-Id`, no standalone GET stream, no independent server-to-client requests. Every request carries its protocol version and client capabilities in `params._meta`.
- The `initialize → notifications/initialized` handshake is the **legacy** flow (2025-11-25 and earlier), still needed to talk to older clients and servers.

## Specification revisions

| Revision | What changed |
|---|---|
| 2025-03-26 | Streamable HTTP replaces the two-endpoint HTTP+SSE transport. |
| 2025-06-18 | Structured tool output, elicitation, OAuth resource-server separation, resource indicators; JSON-RPC batching removed. |
| 2025-11-25 | URL elicitation, sampling with tools, Client ID Metadata Documents; experimental tasks. |
| 2026-07-28 (current) | Per-request version and capabilities; `server/discover`; MRTR (multi round-trip requests); `subscriptions/listen`; `resultType`; explicit state handles; tasks moved to an extension. Roots, sampling, logging and Dynamic Client Registration deprecated (removal no earlier than a revision on or after 28 July 2027). |

## Architecture

```mermaid
flowchart TB
  User[User] --> Host
  subgraph Host[Host application: UI, permissions, orchestration, model adapter]
    LLM[LLM access / conversation]
    C1[MCP client A]
    C2[MCP client B]
    C3[MCP client C]
    LLM <--> C1
    LLM <--> C2
    LLM <--> C3
  end
  C1 <-->|Local stdio: child process pipes| S1[Filesystem MCP server]
  C2 <-->|Remote Streamable HTTP: HTTPS POST| S2[Business MCP server]
  C3 <-->|Remote Streamable HTTP: HTTPS POST| S3[Search MCP server]
  S1 --> Disk[Allowed files / OS permissions]
  S2 --> API[Business APIs / database]
  S3 --> Search[Search index / upstream API]
  AS[OAuth authorization server] -. audience-bound token .-> C2
  C2 -. token validation at resource server .-> S2
```

The host does not send every conversation, or every server's data, to every server. Select and disclose context intentionally.

## Tool-call sequence: legacy handshake (2025-11-25 and earlier)

```mermaid
sequenceDiagram
  autonumber
  actor U as User
  participant H as Host
  participant M as LLM
  participant C as MCP client
  participant S as MCP server
  Note over C,S: LEGACY: 2025-11-25 and earlier
  H->>C: Start local process / configure HTTP endpoint
  C->>S: initialize(version, clientInfo, client capabilities)
  S-->>C: result(version, serverInfo, server capabilities)
  C->>S: notifications/initialized (no id; no response)
  C->>S: tools/list
  S-->>C: tool names, descriptions, input/output schemas
  U->>H: What is 2 + 3?
  H->>M: User request + selected tool schemas
  M-->>H: Propose add(a=2,b=3)
  H->>U: Approval if required by host policy
  U-->>H: Approve or deny
  H->>C: Approved invocation
  C->>S: tools/call(name=add, arguments)
  S-->>C: content + structuredContent / tool error
  C-->>H: Tool result
  H->>M: Tool result associated with model tool-call id
  M-->>H: Final answer
  H-->>U: 5
```

## Tool-call sequence: current revision (2026-07-28)

```mermaid
sequenceDiagram
  participant C as MCP client
  participant S as MCP server
  actor U as User
  Note over C,S: MODERN: 2026-07-28; no initialize or session
  opt Discovery / dual-era stdio probe
    C->>S: server/discover + per-request _meta
    S-->>C: supportedVersions + capabilities + identity metadata
  end
  C->>S: tools/list + version + clientCapabilities in _meta
  S-->>C: resultType=complete, tools, ttlMs, cacheScope
  Note over C: Host/model selects a tool and authorizes its invocation
  C->>S: tools/call(id=10) + per-request _meta
  opt More user input needed
    S-->>C: resultType=input_required; inputRequests; requestState
    C->>U: Elicitation with accept / decline / cancel
    U-->>C: Reviewed answer
    C->>S: Retry original tools/call(id=11), inputResponses, requestState
  end
  S-->>C: resultType=complete; content; structuredContent
  Note over C: Host sends result back to its model
  opt Change notifications requested
    C->>S: subscriptions/listen (POST response stream on HTTP)
    S-->>C: acknowledged + opted-in change notifications
  end
```

MRTR (multi round-trip requests): what used to be a server-initiated request becomes data inside an interim result. The client answers by retrying the original operation with a new JSON-RPC id. This is a targeted continuation, not a blind retry of a failed mutation.

## Primitives and who controls them

| Primitive | Mechanism and owner |
|---|---|
| Tools | `tools/list → tools/call`. Model-selected; host policy and user consent govern execution. |
| Resources | `resources/list` or `templates/list → resources/read`. Application-controlled context; a resource URI need not be HTTP. |
| Prompts | `prompts/list → prompts/get`. User-selected template; fetching a prompt does not call an LLM. |
| Elicitation | User answers a form or URL interaction via the client. Modern: `elicitation/create` inside `inputRequests`. |
| Roots (deprecated) | Advisory `file://` workspace scope, not an OS sandbox. |
| Sampling (deprecated) | The host controls access to its model, with user oversight. |

These control labels are design conventions, not permission grants.

## Lifecycle

```mermaid
stateDiagram-v2
  [*] --> TransportReady
  TransportReady --> Era: which protocol era?
  Era --> LegacyInit: 2025 and earlier
  Era --> ModernReady: 2026-07-28
  LegacyInit --> LegacyOperational: initialize, result, initialized
  ModernReady --> IndependentRequest: per-request version + capabilities
  IndependentRequest --> InputRequired: MRTR input_required
  InputRequired --> IndependentRequest: retry with new id
  InputRequired --> Closed: decline / stop
  IndependentRequest --> ModernReady: complete / cancel
  LegacyOperational --> Closed: stop
  ModernReady --> Closed: stop
  Closed --> [*]
```

Modern HTTP has request and stream lifetimes, not a protocol connection lifecycle. Closing a response SSE stream cancels that request. For stdio, close input and wait for the process; there is no JSON-RPC shutdown method.

## How a tool call works, step by step

1. **Bind a server to a client.** stdio launches the executable and connects stdin/stdout; HTTP targets an MCP endpoint. Neither supplies your agent loop.
2. **Identify the protocol era.** Modern servers implement `server/discover`. A dual-era stdio client probes discovery and falls back to `initialize` on a legacy response.
3. **Declare capabilities.** Legacy: negotiate once in `initialize`. Modern: send `protocolVersion` and `clientCapabilities` in `params._meta` on every request.
4. **Discover.** List tools, resources and prompts; follow `nextCursor`. Scope caches by authorization.
5. **Adapt schemas to the model API.** The host converts MCP tool definitions into its provider's tool format. Model call ids and JSON-RPC ids are separate.
6. **Authorize, invoke, validate.** Enforce allowlists, schemas, least-privilege credentials and approval; the server validates inputs and permissions again.
7. **Continue the loop.** Return the result with the originating model call id. Server content is untrusted data, never higher-priority instructions.

JSON-RPC 2.0: requests have an id and need a response; notifications have no id and no response; errors carry `error: {code, message, data?}`. A successful result with `isError: true` means the tool failed, not the protocol. Batch arrays are not supported. A modern server rejects an unsupported version with `-32022` and its supported list.

### Modern messages

```jsonc
{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{
  "name":"add","arguments":{"a":2,"b":3},
  "_meta":{
    "io.modelcontextprotocol/protocolVersion":"2026-07-28",
    "io.modelcontextprotocol/clientCapabilities":{}
  }
}}
{"jsonrpc":"2.0","id":3,"result":{
  "resultType":"complete",
  "content":[{"type":"text","text":"5"}],
  "structuredContent":{"result":5},"isError":false
}}
```

### Streamable HTTP request (modern)

```http
POST /mcp HTTP/1.1
Content-Type: application/json
Accept: application/json, text/event-stream
MCP-Protocol-Version: 2026-07-28
Mcp-Method: tools/call
Mcp-Name: add
Authorization: Bearer <audience-bound-access-token>
```

Headers mirror the body; servers must reject mismatches. Legacy Streamable HTTP (2025-03-26 to 2025-11-25) used an optional `Mcp-Session-Id`, GET back-channel and DELETE termination; the modern transport has none of these. HTTP+SSE (2024) is deprecated.

Stateless protocol does not mean a stateless application: return opaque handles (for example a workflow id), authorize them on every request, and make mutation tools idempotent.

## Authorization

1. A protected MCP server is an OAuth **resource server**, not necessarily the authorization server. Authorization happens at the transport boundary.
2. Clients discover protected-resource metadata (RFC 9728), then authorization-server metadata, and get a client id via Client ID Metadata Documents, pre-registration or (deprecated) Dynamic Client Registration.
3. User flows use PKCE and the MCP resource indicator; validate the issuer.
4. Send the audience-bound token in `Authorization: Bearer` on every request, never in a query string. Validate audience, expiry, issuer and permissions.
5. Never relay a client's token upstream; use separate downstream credentials. Local stdio servers get credentials from a controlled environment.

## Build and test a server (Python SDK v2)

Tested with Python 3.13.5 and `mcp` 2.3.0, in modern (2026-07-28) and legacy (2025-11-25) modes. SDK v2 renamed FastMCP to `MCPServer`.

```bash
python3 -m venv .venv
.venv/bin/python -m pip install "mcp[cli]==2.3.0"
```

```python
# server.py
from mcp.server import MCPServer

mcp = MCPServer("ND Orbit MCP example")

@mcp.tool()
def add(a: int, b: int) -> int:
    """Add two integers without side effects."""
    return a + b

@mcp.resource("lesson://intro")
def intro() -> str:
    """Read a short lesson note."""
    return "MCP connects a host's clients to tools, resources, and prompts."

@mcp.prompt()
def explain(topic: str) -> str:
    """Prepare a user-selected explanation request."""
    return f"Explain {topic} to an engineer, with one concrete example."

if __name__ == "__main__":
    mcp.run(transport="stdio")
```

```python
# smoke.py
import asyncio, sys
from pathlib import Path
from mcp import Client, StdioServerParameters

async def check(mode: str) -> None:
    params = StdioServerParameters(command=sys.executable,
                                   args=[str(Path(__file__).with_name("server.py"))])
    async with Client(params, mode=mode) as client:
        result = await client.call_tool("add", {"a": 2, "b": 3})
        assert result.structured_content == {"result": 5}
        print(f"PASS mode={mode} protocol={client.protocol_version}")

async def main() -> None:
    await check("auto")
    await check("legacy")

asyncio.run(main())
```

Expected output:

```text
PASS mode=auto protocol=2026-07-28
PASS mode=legacy protocol=2025-11-25
```

Inspect with MCP Inspector (Node 22.19+):

```bash
npx -y @modelcontextprotocol/inspector --cli "$PWD/.venv/bin/python" "$PWD/server.py" \
  --method tools/call --tool-name add --tool-arg a=2 --tool-arg b=3
```

Register in Claude Desktop (`claude_desktop_config.json`, merge into `mcpServers`):

```json
{"mcpServers": {"ndorbit-mcp-example": {
  "command": "/absolute/path/.venv/bin/python",
  "args": ["/absolute/path/server.py"]}}}
```

Never print to stdout in a stdio server: stdout is the protocol pipe. Log to stderr.

## Security pitfalls

| Failure mode | Response |
|---|---|
| stdout pollution (stdio) | Log to stderr only. |
| Tool poisoning / prompt injection | Treat descriptions, annotations and results as untrusted; enforce allowlists outside the model. |
| Confused deputy | Bind consent to the actual client and user; validate redirect URIs, state and PKCE. |
| Token passthrough (forbidden) | Accept only tokens issued for this MCP resource; separate upstream credentials. |
| Over-broad scopes | Minimal scopes, explicit elevation, per-operation checks. |
| DNS rebinding / local HTTP | Validate Origin (403 on invalid), bind to 127.0.0.1, authenticate. CORS is not authentication. |
| Rug-pull tool changes | Pin versions, diff tool definitions, re-approve material changes. |
| Unsafe execution / exfiltration | Human review of sensitive calls; sandbox local servers; minimise files, network and env vars. |
| SSRF in OAuth discovery | Validate metadata URLs; block private and cloud-metadata destinations. |
| State and retries | Bind handles to caller; timeouts, rate limits, idempotency. |

Elicitation is not authorization, and form elicitation must never ask for passwords, API keys, tokens or payment details. Roots are not a sandbox. MCP standardises the conversation; it does not certify the server.

## How other platforms compare (checked 8 November 2026)

- **OpenAI function calling + Agents SDK**: app-executed function schemas; the Agents SDK adds MCP clients (stdio, Streamable HTTP, legacy SSE) and a hosted MCP tool.
- **AWS Bedrock Agents Classic**: action groups (OpenAPI/function schemas, Lambda); not an MCP endpoint; in maintenance since 30 July 2026.
- **AWS AgentCore Gateway**: managed MCP façade over OpenAPI, Lambda, Smithy and remote MCP targets.
- **Microsoft Foundry Agent Service**: remote MCP tool with allowlists and approval; no local stdio.
- **Open WebUI**: native MCP over Streamable HTTP; stdio/SSE via mcpo; admin-only registration.
- **Google ADK**: `McpToolset` imports MCP tools over stdio or HTTP; ADK can also expose MCP.
- **A2A**: agent-to-agent delegation, complementary to MCP; an A2A agent may itself use MCP tools.

## FAQ

**What is an MCP server?** A program that exposes tools, resources and prompts to AI applications over the Model Context Protocol, translating approved requests into calls to its own systems. It does not need an LLM.

**MCP vs function calling?** Function calling is how one model API requests a tool your app executes. MCP standardises how any host discovers and calls tools in separate servers, so one server works with many AI applications.

**Is initialize still required?** Not in 2026-07-28. It is the legacy flow for 2025-11-25 and earlier.

**stdio or Streamable HTTP?** stdio for a local server launched by the host; Streamable HTTP for a remote shared service protected as an OAuth resource server.

**Who decides when a tool runs?** The model proposes; the host checks policy and user approval; the server validates again.

**Is MCP the same as A2A?** No. MCP connects agents to tools and data; A2A connects agents to other agents.

## Sources

- MCP specification: https://modelcontextprotocol.io/specification
- MCP documentation: https://modelcontextprotocol.io/docs
- Python SDK: https://github.com/modelcontextprotocol/python-sdk
- TypeScript SDK: https://github.com/modelcontextprotocol/typescript-sdk
- MCP Inspector: https://github.com/modelcontextprotocol/inspector
- RFC 9728: https://www.rfc-editor.org/rfc/rfc9728
- OpenAI Agents SDK MCP: https://openai.github.io/openai-agents-python/mcp/
- Google ADK MCP tools: https://google.github.io/adk-docs/tools/mcp-tools/
- A2A protocol: https://a2a-protocol.org/

---

Written by Ata at ND Orbit (Niliarya Limited, New Zealand), which designs AI agents, MCP servers and business automation. Full article with interactive diagrams: https://ndorbit.co.nz/articles/mcp/ · Contact: admin@ndorbit.co.nz
