Lesson 8 of 9 · Building
Advanced MCP Features and Latest Specification
MCP's latest specification: version negotiation, extensions, multi round-trip requests, elicitation, Tasks, MCP Apps, OAuth 2.1 and updated security.
- 21 min read
- Intermediate
- Reviewed
- List what changed in MCP specification 2026-07-28 and what is deprecated
- Explain version and capability negotiation, including errors -32022 and -32021
- Use multi round-trip requests and elicitation to ask the user for input
- Describe the Tasks and MCP Apps extensions and when to use them
- Follow the OAuth 2.1 authorization flow and the updated security rules
- Build a server with elicitation and an MCP App using the Python SDK
What changed in the latest specification
MCP is versioned by date. This course follows 2026-07-28, the current version, which changed more than any earlier one. Earlier lessons already used its basics: _meta on every request, server/discover and the new HTTP headers. This lesson covers the rest.
| Area | Before (2025-11-25 and earlier) | Now (2026-07-28) |
|---|---|---|
| Starting a connection | initialize handshake creates a session | No handshake: version and capabilities travel in every request's _meta; server/discover describes the server |
| Sessions | Mcp-Session-Id header | None. State that spans calls uses handles the server creates and the client passes as tool arguments |
| Server asks the client | Server sends its own requests (sampling, elicitation, roots) mid-call | Multi round-trip requests: the server returns input_required and the client retries |
| Change notifications | HTTP GET stream, resources/subscribe | One subscriptions/listen request |
| Long-running work | Experimental tasks in the core | The Tasks extension (io.modelcontextprotocol/tasks) |
| Rich UI | Not standard | The MCP Apps extension (io.modelcontextprotocol/ui) |
| Results | No type marker | Every result has resultType: complete, input_required (or task with the Tasks extension) |
| Caching | Not specified | List and read results carry ttlMs and cacheScope |
| Removed | ping, logging/setLevel, notifications/roots/list_changed, SSE resumability | |
| Deprecated | Roots, Sampling and Logging; the HTTP+SSE transport; Dynamic Client Registration |
Versions and capability negotiation
There's no handshake: the server accepts or rejects each request on its own. Three terms describe who speaks what:
- Modern: version 2026-07-28 and later, with metadata on every request.
- Legacy: 2025-11-25 and earlier, with an
initializehandshake. - Dual-era: software that supports both, which is what SDKs do today.
If a request names a version the server doesn't support, the server must answer with UnsupportedProtocolVersionError (code -32022), listing the versions it does support. The client picks one it also knows and retries. Capabilities work the same way: the client declares them in each request, and a server that needs one the client didn't declare answers MissingRequiredClientCapability (code -32021). The program below plays both sides:
# Every MCP request names its protocol version and the client's capabilities in _meta.
# The server accepts or rejects each request on its own: there is no handshake.
SERVER_VERSIONS = ["2026-07-28"]
def server_handle(request):
meta = request["params"]["_meta"]
version = meta["io.modelcontextprotocol/protocolVersion"]
if version not in SERVER_VERSIONS:
return {"error": {"code": -32022, "message": "Unsupported protocol version",
"data": {"supported": SERVER_VERSIONS, "requested": version}}}
capabilities = meta["io.modelcontextprotocol/clientCapabilities"]
if request["params"].get("name") == "reserve_bike" and "elicitation" not in capabilities:
return {"error": {"code": -32021, "message": "Missing required client capability",
"data": {"requiredCapabilities": {"elicitation": {"form": {}}}}}}
return {"result": {"resultType": "complete", "content": [{"type": "text", "text": "Reserved a City E."}]}}
def make_request(method, version, capabilities, **params):
params["_meta"] = {"io.modelcontextprotocol/protocolVersion": version,
"io.modelcontextprotocol/clientCapabilities": capabilities}
return {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}
client_versions = ["2027-01-15", "2026-07-28"] # newest first; 2027-01-15 is a made-up future version
call = {"name": "reserve_bike", "arguments": {"model": "City E"}}
reply = server_handle(make_request("tools/call", client_versions[0], {}, **call))
print("1.", reply["error"]["code"], reply["error"]["data"])
supported = reply["error"]["data"]["supported"]
version = next(v for v in client_versions if v in supported) # newest version both sides know
reply = server_handle(make_request("tools/call", version, {}, **call))
print("2.", reply["error"]["code"], reply["error"]["data"])
reply = server_handle(make_request("tools/call", version, {"elicitation": {"form": {}}}, **call))
print("3.", version, reply["result"]["content"][0]["text"])The first request uses a made-up future version and is rejected with the supported list. The retry uses 2026-07-28 but declares no elicitation support, so a tool that needs to ask the user is refused. With both fixed, the call succeeds.
Extensions are negotiated through the extensions field of the capabilities: the client lists the ones it supports in each request, and the server lists its own in the server/discover result. If only one side supports an extension, the supporting side must fall back to core behaviour or reject the request.
Here's the same negotiation with the Python SDK. rides_server.py (shown in full in the elicitation section) uses the MCP Apps extension, and two clients connect to it:
import anyio
from mcp import Client
from rides_server import mcp
async def main():
async with Client(mcp) as modern: # mode="auto": tries server/discover first
print("modern:", modern.protocol_version, modern.server_info.name)
print(" server extensions:", list(modern.server_capabilities.extensions or {}))
async with Client(mcp, mode="legacy") as old: # an older client: initialize handshake
print("legacy:", old.protocol_version, old.server_info.name)
anyio.run(main)modern: 2026-07-28 Velo Rides server extensions: ['io.modelcontextprotocol/ui'] legacy: 2025-11-25 Velo Rides
The same server code serves both eras. The default client (mode="auto") tries server/discover and stays modern; a legacy client still gets the old initialize handshake. When a modern-only client meets a legacy-only server, the connection fails, so SDK clients probe first and fall back.
Multi round-trip requests
Sometimes a server needs something in the middle of a call: an answer from the user, or a model completion. Before 2026-07-28, the server sent its own request back over the open connection. That needs a connection that stays open and a server that remembers the call. The new pattern needs neither.
Only tools/call, prompts/get and resources/read may return input_required, and only with request types the client declared support for. Because requestState passes through the client, the specification treats it as attacker-controlled input: if it affects permissions or business logic, the server must protect its integrity (for example with an HMAC signature) and should bind it to the user, the request and a short expiry. The program below does exactly that:
import hashlib
import hmac
import json
import time
SECRET = b"known only to the server" # every copy of the server shares this key
def seal(state): # the client can carry this, but can't change it
body = json.dumps(state, sort_keys=True)
tag = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()[:16]
return f"{body}|{tag}"
def unseal(token, user):
body, tag = token.rsplit("|", 1)
expected = hmac.new(SECRET, body.encode(), hashlib.sha256).hexdigest()[:16]
if not hmac.compare_digest(tag, expected):
raise ValueError("requestState failed verification")
state = json.loads(body)
if state["user"] != user or time.time() > state["expires"]:
raise ValueError("requestState belongs to someone else or has expired")
return state
def reserve_bike(params, user):
"""tools/call for reserve_bike. Needs the rider's height, which only the user knows."""
answers = params.get("inputResponses", {})
if "rider" not in answers: # round 1: ask, and remember the request in requestState
return {"resultType": "input_required",
"inputRequests": {"rider": {"method": "elicitation/create", "params": {
"mode": "form", "message": "How tall is the rider (cm)?",
"requestedSchema": {"type": "object", "required": ["height_cm"],
"properties": {"height_cm": {"type": "integer"}}}}}},
"requestState": seal({"user": user, "model": params["arguments"]["model"],
"expires": time.time() + 600})}
state = unseal(params["requestState"], user) # round 2: any server copy can finish the job
answer = answers["rider"]
if answer["action"] != "accept":
return {"resultType": "complete", "content": [{"type": "text", "text": "No reservation made."}]}
frame = "M" if answer["content"]["height_cm"] < 180 else "L"
return {"resultType": "complete",
"content": [{"type": "text", "text": f"Reserved a {state['model']}, frame {frame}."}]}
first = reserve_bike({"name": "reserve_bike", "arguments": {"model": "City E"}}, user="asha")
print("Round 1:", first["resultType"], "->", list(first["inputRequests"]))
retry = {"name": "reserve_bike", "arguments": {"model": "City E"}, # a NEW request, new id
"inputResponses": {"rider": {"action": "accept", "content": {"height_cm": 172}}},
"requestState": first["requestState"]} # echoed back unchanged
print("Round 2:", reserve_bike(retry, user="asha")["content"][0]["text"])
for label, params, user in [
("Tampered", dict(retry, requestState=first["requestState"].replace("City E", "Cargo X")), "asha"),
("Replayed by another user", retry, "omar"),
]:
try:
reserve_bike(params, user)
except ValueError as error:
print(f"{label}: rejected ({error})")Round 1 asks for the rider's height and seals the chosen bike into requestState. Round 2 is a new request carrying the answer and the state, so any server instance can finish the job. A state edited to switch the bike, or replayed by a different user, is rejected.
Elicitation: asking the user
Elicitation lets a server ask the user for information through the client. It travels inside multi round-trip requests, and it has two modes:
| Form mode | URL mode | |
|---|---|---|
| What happens | The client shows a form built from a JSON schema | The client opens a web page in the user's browser, after asking for consent |
| Use it for | Choices, numbers, short answers | Passwords, API keys, payments, signing in to a third-party service |
| Data passes through the client? | Yes | No: the user talks to the web page directly |
Form schemas are deliberately simple: a flat object whose fields are strings, numbers, integers, booleans or enums (strings can be formatted as email, URI, date or date-time). The user answers with one of three actions: accept (with the content), decline or cancel. Clients declare elicitation in their capabilities, with form and url inside it; an empty object means form only.
The rules that keep users safe:
- Servers must not ask for passwords, API keys or other sensitive data in form mode; that's what URL mode is for.
- For URL mode, the client must show which server is asking and the full URL, and get the user's consent before opening it, without loading the page in advance.
- The user can always decline or cancel, and the server must handle both.
Here's the bike-rental server. The reserve_bike tool asks for the rider's height through a resolver, which the SDK fills in by asking the user:
# rides_server.py: a bike-rental MCP server using elicitation and the MCP Apps extension
from typing import Annotated
from pydantic import BaseModel, Field
from mcp.server.apps import Apps, client_supports_apps
from mcp.server.mcpserver import AcceptedElicitation, Context, Elicit, ElicitationResult, MCPServer, Resolve
class RiderDetails(BaseModel):
height_cm: int = Field(description="Rider's height in centimetres", ge=120, le=220)
helmet: bool = Field(default=True, description="Add a helmet (free)")
async def ask_rider(ctx: Context) -> Elicit[RiderDetails]:
return Elicit("To pick the right frame size, how tall is the rider?", RiderDetails)
apps = Apps()
ROUTE_HTML = """<!doctype html>
<html><body>
<h1 id="title">Route</h1>
<p>Interactive route map for Velo Rides.</p>
</body></html>"""
@apps.tool(resource_uri="ui://rides/route-map.html", description="Show a cycling route on an interactive map")
def show_route(start: str, end: str, ctx: Context) -> str:
if client_supports_apps(ctx):
return f"Showing the {start} to {end} route on the map."
return f"Route {start} to {end}: 12 km, mostly flat, riverside path." # text fallback
apps.add_html_resource("ui://rides/route-map.html", ROUTE_HTML)
mcp = MCPServer("Velo Rides", instructions="Bike rentals in Porto.", extensions=[apps])
@mcp.tool()
async def reserve_bike(model: str, answer: Annotated[ElicitationResult[RiderDetails], Resolve(ask_rider)]) -> str:
"""Reserve a rental bike. Asks the user for the rider's height."""
if not isinstance(answer, AcceptedElicitation): # the user declined or cancelled
return f"No reservation made ({answer.action})."
rider = answer.data
frame = "S" if rider.height_cm < 165 else "M" if rider.height_cm < 180 else "L"
extra = " with a helmet" if rider.helmet else ""
return f"Reserved a {model}, frame size {frame}{extra}."And a client that answers the form, then one that declines, then one that declared no elicitation support:
import anyio
from mcp import Client
from mcp.shared.exceptions import MCPError
from mcp.types import ElicitResult
from rides_server import mcp
async def answer(context, params): # the host would show a form to the user
print("Form shown to the user:", params.message)
print(" fields:", list(params.requested_schema["properties"]))
return ElicitResult(action="accept", content={"height_cm": 172, "helmet": True})
async def decline(context, params):
return ElicitResult(action="decline")
async def main():
async with Client(mcp, elicitation_callback=answer) as client:
result = await client.call_tool("reserve_bike", {"model": "City E"})
print("Result:", result.content[0].text)
async with Client(mcp, elicitation_callback=decline) as client:
result = await client.call_tool("reserve_bike", {"model": "City E"})
print("Declined:", result.content[0].text)
async with Client(mcp) as client: # no elicitation support declared
try:
await client.call_tool("reserve_bike", {"model": "City E"})
except MCPError as error:
print("No elicitation support:", error.code, error.error.message)
anyio.run(main)Form shown to the user: To pick the right frame size, how tall is the rider? fields: ['height_cm', 'helmet'] Result: Reserved a City E, frame size M with a helmet. Declined: No reservation made (decline). No elicitation support: -32021 Client did not declare the form elicitation capability required by resolver 'rides_server:ask_rider'
Under 2026-07-28, the SDK turns the resolver into a multi round-trip request. The server's first answer to tools/call looks like this (shortened):
{
"resultType": "input_required",
"inputRequests": {
"rides_server:ask_rider": {
"method": "elicitation/create",
"params": {
"mode": "form",
"message": "To pick the right frame size, how tall is the rider?",
"requestedSchema": {
"type": "object",
"properties": {
"height_cm": {"type": "integer", "minimum": 120, "maximum": 220, "description": "Rider's height in centimetres"},
"helmet": {"type": "boolean", "default": true, "description": "Add a helmet (free)"}
},
"required": ["height_cm"]
}
}
}
},
"requestState": "v1.d1c45bg6RFq..."
}The client's elicitation_callback produces the answer, and the client retries automatically. With a legacy client, the same server code sends a classic elicitation/create request instead. Declining reaches the tool as a DeclinedElicitation, so it can reply politely, and a client without the capability gets error -32021.
Tasks: work that takes a while
Some operations take minutes or hours: a data export, a CI pipeline, a human approval. Holding a connection open that long breaks easily. The Tasks extension lets the server return a durable handle instead.
- The client declares
io.modelcontextprotocol/tasksin its capabilities, and the server lists it inserver/discover. A server must never return a task to a client that didn't declare support. - For a long request, the server answers with
resultType: "task", ataskId, itsstatus,ttlMs(how long it's kept) andpollIntervalMs(how often to check). The task must be stored before this reply is sent. - Statuses:
working,input_required,completed,failedandcancelled. The last three are final. tasks/getreturns the current state, and the result whencompleted(or the error whenfailed).- When a task needs input,
tasks/getincludesinputRequests; the client answers withtasks/update. tasks/cancelasks the server to stop. Cancellation is cooperative: the work may still finish.
The Python SDK 2.3 doesn't include a Tasks implementation yet (its Extension class lets you add methods such as tasks/get yourself), so this program shows the protocol in plain Python:
import itertools
from datetime import datetime, timezone
# A toy server that supports the Tasks extension (io.modelcontextprotocol/tasks)
TASKS = {}
ids = itertools.count(1)
def now():
return datetime.now(timezone.utc).isoformat(timespec="seconds")
def tools_call(name, arguments, client_extensions):
if "io.modelcontextprotocol/tasks" not in client_extensions: # never send a task to a client
return {"resultType": "complete", "content": [{"type": "text", "text": "Ran synchronously."}]}
task = {"taskId": f"task-{next(ids)}", "status": "working", "createdAt": now(),
"lastUpdatedAt": now(), "ttlMs": 3_600_000, "pollIntervalMs": 2000}
TASKS[task["taskId"]] = dict(task, steps_left=2) # stored BEFORE replying
return {"resultType": "task", **task}
def tasks_get(task_id):
task = TASKS[task_id]
if task["status"] == "working":
task["steps_left"] -= 1
if task["steps_left"] == 0: # the job needs a decision
task["status"] = "input_required"
task["inputRequests"] = {"confirm": {"method": "elicitation/create", "params": {
"mode": "form", "message": "Export 1,240 bookings to the accountant?",
"requestedSchema": {"type": "object", "properties": {}}}}}
return {"resultType": "complete", **{k: v for k, v in task.items() if k != "steps_left"}}
def tasks_update(task_id, input_responses):
task = TASKS[task_id]
accepted = input_responses["confirm"]["action"] == "accept"
task.pop("inputRequests", None)
task["status"] = "completed" if accepted else "cancelled"
task["lastUpdatedAt"] = now()
if accepted:
task["result"] = {"content": [{"type": "text", "text": "Exported 1,240 bookings."}]}
return {} # an empty result: acknowledged
# The client: start the job, then poll until the task reaches a terminal status
created = tools_call("export_bookings", {}, client_extensions={"io.modelcontextprotocol/tasks": {}})
print("Created:", created["resultType"], created["taskId"], created["status"],
"- poll every", created["pollIntervalMs"], "ms")
while True:
task = tasks_get(created["taskId"]) # a real client waits pollIntervalMs between polls
print("Poll:", task["status"])
if task["status"] == "input_required":
print(" Ask the user:", task["inputRequests"]["confirm"]["params"]["message"])
tasks_update(task["taskId"], {"confirm": {"action": "accept"}})
elif task["status"] in ("completed", "failed", "cancelled"):
break
print("Result:", task["result"]["content"][0]["text"])
print("Client without Tasks:", tools_call("export_bookings", {}, client_extensions={})["content"][0]["text"])Clients should store task IDs durably, so they can resume polling after a crash. Servers can also push task updates through subscriptions/listen, so a client that opted in doesn't need to poll.
MCP Apps: interactive interfaces
Text answers have limits: a route is easier to read on a map, and a form with twenty options is easier than twenty questions. The MCP Apps extension (io.modelcontextprotocol/ui) lets a tool come with an interactive HTML interface that the host shows inside the conversation.
- A tool's description carries
_meta.ui.resourceUri, pointing to aui://resource. - That resource is an HTML page with the MIME type
text/html;profile=mcp-app. - The host renders it in a sandboxed iframe: the app can't touch the host page, its cookies or its storage.
_meta.ui.csplists the outside origins the app may load from, and_meta.ui.permissionscan request things like the microphone. - The app talks to the host with JSON-RPC over
postMessage: it can call the server's tools through the host and receive fresh results. - Hosts that support it include Claude, Claude Desktop, VS Code GitHub Copilot and Microsoft 365 Copilot. The tool must still return useful text for hosts that don't.
The server above already registers an app with the SDK's Apps extension: @apps.tool(resource_uri=...) links show_route to its page, apps.add_html_resource serves the HTML, and client_supports_apps(ctx) picks the reply. Here are two hosts, one that advertises Apps support and one that doesn't:
import anyio
from mcp import Client
from mcp.client.extension import advertise
from rides_server import mcp
MCP_APPS = advertise("io.modelcontextprotocol/ui", {"mimeTypes": ["text/html;profile=mcp-app"]})
async def main():
async with Client(mcp, extensions=[MCP_APPS]) as host: # a host that can render apps
tools = {t.name: t for t in (await host.list_tools()).tools}
ui_uri = tools["show_route"].meta["ui"]["resourceUri"]
print("UI resource:", ui_uri)
page = await host.read_resource(ui_uri)
print("MIME type:", page.contents[0].mime_type)
result = await host.call_tool("show_route", {"start": "Ribeira", "end": "Foz"})
print("With Apps:", result.content[0].text)
async with Client(mcp) as plain: # a host without Apps support
result = await plain.call_tool("show_route", {"start": "Ribeira", "end": "Foz"})
print("Without Apps:", result.content[0].text)
anyio.run(main)UI resource: ui://rides/route-map.html MIME type: text/html;profile=mcp-app With Apps: Showing the Ribeira to Foz route on the map. Without Apps: Route Ribeira to Foz: 12 km, mostly flat, riverside path.
advertise() adds the extension to the client's capabilities. A real host would now render the ui:// page in its sandbox; the plain client gets the text fallback.
Authorization: OAuth 2.1 for remote servers
Authorization is optional, and it applies to HTTP servers only: stdio servers take credentials from the environment. A protected HTTP server is an OAuth 2.1 resource server; a separate authorization server signs users in and issues tokens. The flow:
- The client sends a request without a token. The server answers 401 with a
WWW-Authenticateheader pointing to its Protected Resource Metadata (RFC 9728), which every protected MCP server must publish, and usually ascopefor the operation. - That metadata names the authorization server. The client reads the authorization server's metadata (RFC 8414 or OpenID Connect discovery; clients must support both).
- The client identifies itself. Client ID Metadata Documents are preferred: the client ID is an HTTPS URL that hosts the client's description. Pre-registration also works. Dynamic Client Registration is now deprecated, kept for older authorization servers.
- The client opens the browser to sign in, with PKCE, the
resourceparameter (RFC 8707) naming the exact MCP server, and only the scopes it needs. It records the authorization server's issuer. - When the user returns, the client checks the
issvalue against the recorded issuer (RFC 9207) before using the code. This blocks mix-up attacks, where a malicious authorization server tries to capture a code meant for an honest one. - The client exchanges the code for a token and sends
Authorization: Bearer <token>on every request, never in the URL.
On the server side, tokens must have been issued for this server (the audience check), and the server must not accept or pass on any other token: no token passthrough. When a token lacks a permission, the server answers 403 with error="insufficient_scope" and the scopes needed, and the client asks for those scopes in addition to the ones it already has (step-up authorization). Clients must also store credentials per issuer and never reuse them with another authorization server.
Security best practices: what's new
The specification's security guidance now also covers:
- State handle hijacking. Without sessions, servers hand out IDs such as a cart or workflow ID. Possessing an ID is not proof of identity: make IDs random, let them expire, and store them under the authenticated user (for example
user_id:handle), rejecting anyone else. - SSRF during discovery. A malicious server can put internal addresses such as
http://169.254.169.254/(cloud metadata) in its metadata URLs. Clients should require HTTPS, block private and link-local IP ranges, check redirects, and use an egress proxy on servers. - Dangerous authorization URLs. Clients must only open
https://URLs (http://only for localhost during development), rejectjavascript:,data:andfile:, and never open URLs through a shell command. - Scope minimization. Start with a small scope set and ask for more only when an operation needs it, so a stolen token can do little.
- Local server installation. One-click setup must show the full command and get the user's consent before running it.
The Transports and MCP Security lessons covered the HTTP headers and the main risks; two transport details are also new: a broken response stream is no longer resumed (the client sends the request again with a new ID), and log messages only flow for requests that set a log level in _meta.
Common mistakes
Validate an authorization URL before opening it, as the MCP security best practices require: a malicious server could send a javascript: URL or a plain-http one.
from urllib.parse import urlparse
def safe_authorization_url(url):
# Return True only if a client may open this authorization URL:
# https:// is fine; http:// only for localhost, 127.0.0.1 or ::1 (local development);
# any other scheme (javascript:, data:, file: ...) must be rejected.
return True
for url in ["https://auth.velo.example/authorize", "http://localhost:8080/authorize",
"http://auth.velo.example/authorize", "javascript:alert(document.cookie)"]:
print(safe_authorization_url(url))
A tool needs the user's choice before it can finish. Under MCP 2026-07-28, what does the server do?
Summary
- 2026-07-28 made MCP stateless, added
server/discover, and moved server-to-client requests into multi round-trip requests. - Each request names its version and capabilities; errors -32022 (unsupported version) and -32021 (missing capability) tell the client what to fix.
- Extensions are negotiated in
capabilities.extensions; the supporting side falls back when the other doesn't support one. - Elicitation asks the user: form mode for simple answers, URL mode for anything sensitive; answers are accept, decline or cancel.
requestStateis untrusted input: seal it, bind it to the user and give it an expiry.- The Tasks extension handles long work with
tasks/get,tasks/updateandtasks/cancel; MCP Apps add sandboxed HTML interfaces with a text fallback. - Remote servers use OAuth 2.1: Protected Resource Metadata, PKCE, the
resourceparameter,isschecks, audience validation and no token passthrough. - Deprecated: Roots, Sampling, Logging, HTTP+SSE and Dynamic Client Registration.
Official sources: the 2026-07-28 changelog, versioning, multi round-trip requests, elicitation, authorization, security best practices, the Tasks extension and MCP Apps.
Next: the course project, an MCP server for your own data.
Finished reading? Tick it off to track your progress.